1.添加进程 四大组件中 如android:process="android.services"
2.通信方式
发送者:
// 1)使用Bundle跨进程通信
Intent mIntent = new Intent(this, LActivity.class);
mIntent.putExtra("name", " value");
startActivity(mIntent);
// 2)使用文件共享
File file = new File("/sdcard/a.txt");
ObjectOutputStream mOutputStream = null;
try {
mOutputStream = new ObjectOutputStream(new FileOutputStream(file));
mOutputStream.writeObject(new UserEntity("勒布朗", "32"));
mOutputStream.flush();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
startActivity(mIntent);
// 3)使用Messenger
mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Messenger messenger = new Messenger(service);
sendMsg(messenger, 1, String.valueOf(2));
}
};
bindService(new Intent(this, MyBindServices.class), mConnection, 1);
}
public void sendMsg(Messenger messenger,int what, String msg){ //这个方法就是自己的业务信息发送消息 传递到Service中 有 Handler处理。
if (messenger == null) {
return;
}
Message msg1 = Message.obtain();
Bundle mBundle=new Bundle();
mBundle.putString("key", "value");
msg1.setData(mBundle);
//注意:msg.obj這些不是Bundler不能傳送
try {
messenger.send(msg1);
} catch (RemoteException e) {
e.printStackTrace();
}
}
接送者1:
//1)使用bundle通信
mTextView.setText(getIntent().getStringExtra("name"));
//2)使用文件共享
File file=new File("/sdcard/a.txt");
ObjectInputStream mInputStream = null;
try {
mInputStream=new ObjectInputStream(new FileInputStream(file));
try {
UserEntity mUserEntity= (UserEntity)mInputStream.readObject();
mTextView.setText(mUserEntity.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
mInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
接送者2:
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.widget.Toast;
public class MyBindServices extends Service {
Messenger message;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle mBundle = msg.getData();
Toast.makeText(MyBindServices.this, mBundle.getString("key"), 1)
.show();
}
};
@Override
public void onCreate() {
super.onCreate();
message = new Messenger(mHandler);
}
@Override
public IBinder onBind(Intent intent) {
return message.getBinder();
}
}
下载:IPC方式 Bundle 文件共享 Messenger以及aidl