不同App(进程)之间的数据交换,使用带到的核心技术是Messenger
技术概述
Messenger的核心也就是Message和Handler,同样是Service提供方法,供其他地方进行调用
Service代码示例
public class MyService extends Service {
class ServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Log.i("MyService", "msg.what is 1");
break;
default:
super.handleMessage(msg);
}
super.handleMessage(msg);
}
}
final Messenger messenger = new Messenger(new ServiceHandler());
@Override
public IBinder onBind(Intent intent) {
Log.i("MyService", "service is binded");
return messenger.getBinder();
}
}
由于需要别的App来调用,所以这个Service在AndroidManifest需要进行一些属性的设置,具体如下
android:name=".MyService"
android:enabled="true"
android:exported="true" >
Activity代码示例
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Messenger messenger = null;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messenger = new Messenger(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
messenger = null;
}
};
@Override
protected void onStart() {
super.onStart();
Log.i("MyActivity", "activity start bind service");
Intent it = new Intent();
// 这个设置的是Service所在的AndroidManifest里面设置的action属性
it.setAction("com.serviceHandler");
// 这个是Service的包名
it.setPackage("com.test");
bindService(it, serviceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
unbindService(serviceConnection);
}
// 执行这个方法,会在logcat看到 'msg.what is 1' 的消息输出,这样就可以通过Message来进行数据交互了
public void testBindService(View v){
Message msg = Message.obtain();
msg.what = 1;
try {
messenger.send(msg);
}catch (Exception e) {
Log.e("MyActivity", utils.getExceptionMsg(e));
}
}
}