Android中跨应用绑定Service并通信
2015-07-28 22:38
525 查看
第一步 : 创建l两个应用程序分别命名为app和anotherapp第二步:1.在app的应用程序中MainActivity的代码如下:
package com.example.yangjian.startservicefromanotherapp; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //startService(new Intent(this, AppService.class)); } @Override protected void onDestroy() { super.onDestroy(); //stopService(new Intent(this, AppService.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }2.在AppService中的代码如下:
package com.example.yangjian.startservicefromanotherapp; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; public class AppService extends Service { public AppService() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return new IAppServiceRemoteBinder.Stub() { @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { } @Override public void setData(String data) throws RemoteException { AppService.this.data = data; } }; } @Override public void onCreate() { super.onCreate(); System.out.println("Service started"); //创建的线程,测试程序是否正在运行 new Thread() { @Override public void run() { super.run(); running = true; while (running) { System.out.println(data); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } @Override public void onDestroy() { super.onDestroy(); System.out.println("Service destroy"); running = false; } private String data = "moren shuju"; private boolean running = false; }
3.Android的接口定义语言:AIDL
// IAppServiceRemoteBinder.aidl package com.example.yangjian.startservicefromanotherapp; // Declare any non-default types here with import statements interface IAppServiceRemoteBinder { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); void setData(String data); }
第三步:1.在another应用程序中MainActivity的代码如下:
package com.example.yangjian.anotherapp; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import com.example.yangjian.startservicefromanotherapp.IAppServiceRemoteBinder; public class MainActivity extends ActionBarActivity implements View.OnClickListener, ServiceConnection { private Intent serviceIntent; private EditText etInput; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etInput = (EditText) findViewById(R.id.etInput); serviceIntent = new Intent(); serviceIntent.setComponent(new ComponentName("com.example.yangjian.startservicefromanotherapp", "com.example.yangjian.startservicefromanotherapp.AppService")); findViewById(R.id.btnStartAppService).setOnClickListener(this); findViewById(R.id.btnStopAppService).setOnClickListener(this); findViewById(R.id.btnBindAppService).setOnClickListener(this); findViewById(R.id.btnUnbindAppService).setOnClickListener(this); findViewById(R.id.btnSync).setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnStartAppService: startService(serviceIntent); break; case R.id.btnStopAppService: stopService(serviceIntent); break; case R.id.btnBindAppService: bindService(serviceIntent, this, Context.BIND_AUTO_CREATE); break; case R.id.btnUnbindAppService: unbindService(this); binder = null; break; case R.id.btnSync: if(binder != null) { try { binder.setData(etInput.getText().toString()); } catch (RemoteException e) { e.printStackTrace(); } } break; } } @Override public void onServiceConnected(ComponentName name, IBinder service) { System.out.println("Bind Service"); System.out.println(service); binder = IAppServiceRemoteBinder.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } private IAppServiceRemoteBinder binder = null; }
2.在MainXml文件中的代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="启动外部服务" android:id="@+id/btnStartAppService" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止外部服务" android:id="@+id/btnStopAppService" android:layout_gravity="center_vertical" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="绑定外部服务" android:id="@+id/btnBindAppService" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解除外部服务" android:id="@+id/btnUnbindAppService" android:layout_gravity="center_vertical" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:text="这是另一个应用中的数据" android:id="@+id/etInput" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="同步数据到绑定的服务中" android:id="@+id/btnSync" /> </LinearLayout>
3.Android的接口定义语言:AIDL
// IAppServiceRemoteBinder.aidl package com.example.yangjian.startservicefromanotherapp; // Declare any non-default types here with import statements interface IAppServiceRemoteBinder { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); void setData(String data); }
相关文章推荐
- Android中客户端请求服务器端的方式讲解(一)附源码
- Android 布局中的include标签使用
- Android屏幕保持唤醒状态
- Android设计模式之代理模式 Proxy
- Android程序运行过程中因未捕获异常而异常终止
- 上传音乐到Android模拟器的SD卡,并在Android模拟器上播放
- 我遇见的关于android studio 导入studio项目常见问题
- 自定义统一title
- Android模拟器的sdcard操作技巧整理
- 优酷旋转菜单(RotateAnimation,Relativelayout知识点学习)
- Android 构建系统概览
- Android官网中关于Creating a Bound Service的介绍笔记
- LoaderManager的使用
- Android Day10-多媒体
- Android Day09四大组件之内容提供者ContentProvider
- android学习笔记四 ---- android文件安装知识
- Android如何实现侧拉栏
- Android手势滑动识别器应用
- Android 获取屏幕高度和宽度
- Android之ListView原理学习与优化总结