- 使用intent进行传值 效率不高
MainActivity.java
//使用startService启动service
public void start(View view) {
intent = new Intent(this, MyService.class);
//传出值
intent.putExtra("testValue", "testData");
startService(intent);
}
//使用stopService停止service
public void stop(View view) {
stopService(intent);
}
MyService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
data=intent.getStringExtra("testValue");
Log.e(TAG,"传入值 "+intent.getStringExtra("testValue"));
return super.onStartCommand(intent, flags, startId);
}
输出结果 传入值 11 testData
- 使用Binder进行传值与回调
MainActivity.java
MyService.DebugBinder binder;
public void start(View view) {
binder.getValue();
Log.e("===========", "getValue " + binder.getValue());
}
public void stop(View view) {
binder.setValue("123456789");
}
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//连接建立后IBinder 转型为MyService.DebugBinder
binder = (MyService.DebugBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//使用bindService 绑定Service
public void connect() {
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, connection, BIND_AUTO_CREATE);
}
//使用unbindService解绑Service
public void disConnect(View view) {
unbindService(connection);
}
MyService.java
@Override
public IBinder onBind(Intent intent) {
data=intent.getStringExtra("testValue");
return new DebugBinder();
}
//DebugBinder 继承Binder 开发者可在其中定义自己需要的各种方法
public class DebugBinder extends Binder {
String getValue(){
return "value";
}
void setValue(String value){
Log.e("===========","setValue "+value);
}
}
输出值 getValue value
setValue 123456789
3.使用EventBus等事件总线
// 引入eventbus包
implementation 'org.greenrobot:eventbus:3.2.0'
MainActivity.java
@Override
protected void onStart() {
super.onStart();
if (!EventBus.getDefault().isRegistered(this)){
EventBus.getDefault().register(this);
}
}
@Override
protected void onStop() {
super.onStop();
if (EventBus.getDefault().isRegistered(this)){
EventBus.getDefault().unregister(this);
}
}
//需添加 @Subscribe 注解 方法类型为public 方法有且仅能有一个参数
@Subscribe (threadMode = ThreadMode.MAIN)
public void event(String string){
Log.e("===========", "event " + string);
}
MyService.java
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
data=intent.getStringExtra("testValue");
Log.e(TAG,"传入值 "+intent.getStringExtra("testValue"));
EventBus.getDefault().post("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
输出值 event onStartCommand
- 使用广播 推荐LocalBroadcastManager 本地广播 效率快安全性高
- AIDL 一般在跨进程通信时使用
网友评论