1.看了下网易IM android端代码实现,给我的启发就是我可以用MarsDaemon-master 做为保活的方法
2.进程间通讯方式
e.g
假定Service为server(子进程),代码如下
public class PushService extends Service {
private static final intMSG_NUM=0x110;
privateMessengermessenger;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d("WLTest","onBind PushService ..");
initMessager();
returnmessenger.getBinder();
}
@Override
public voidonCreate() {
super.onCreate();
Log.d("WLTest","onCreate PushService ..");
initMessager();
}
private void initMessager() {
if(messenger!=null)
return;
HandlerThread handlerThread =newHandlerThread("RemoteAgent");
handlerThread.start();
messenger=newMessenger(newHandler(handlerThread.getLooper()) {
@Override
public voidhandleMessage(Message msgFromClient) {
Message msgToClient = Message.obtain(msgFromClient);
switch(msgFromClient.what) {
case MSG_NUM:
msgToClient.what=MSG_NUM;
try{
//模拟耗时
Thread.sleep(2000);
msgToClient.arg2= msgFromClient.arg1+ msgFromClient.arg2;
msgFromClient.replyTo.send(msgToClient);
}catch(InterruptedException e) {
e.printStackTrace();
}catch(RemoteException e) {
e.printStackTrace();
}
break;
}
super.handleMessage(msgFromClient);
}
});
}
}
manifest.xml 中定义
<service android:name="com.wl.demo.mybasecontruct.service.PushService" android:process=":remote">
<intent-filter>
<action android:name="com.wl.demo.remote.service"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
client端(主进程)
privateServiceConnectionmConn=newServiceConnection()
{
@Override
public voidonServiceConnected(ComponentName name,IBinder service)
{
mService=newMessenger(service);
isConn=true;
Log.d("WLTest","connected!");
}
@Override
public voidonServiceDisconnected(ComponentName name)
{
mService=null;
isConn=false;
Log.d("WLTest","disconnected!");
}
};
privateMessengermMessenger=newMessenger(newHandler()
{
@Override
public voidhandleMessage(Message msgFromServer)
{
switch(msgFromServer.what)
{
caseMSG_NUM:
Log.d("WLTest","client receive :"+ msgFromServer.arg2);
break;
}
super.handleMessage(msgFromServer);
}
});
private voidbindServiceInvoked()
{
try{
Intent intent =newIntent();
intent.setAction("com.wl.demo.remote.service");
intent.setPackage(this.getPackageName());//这样写就是显示的intent了,否则会报错
bindService(intent,mConn,Context.BIND_AUTO_CREATE);
Log.d("WLTest","bindService invoked !");
}catch(Throwable t) {
Log.d("WLTest",t.toString());
}
}