Android的Activity和Service的三种数据交互方式,第一种:同一app(进程)内的

原创
2019/12/29 22:39
阅读数 12

使用IBinder作为交互媒介

方法概述

Activity端使用bindService的方式来绑定需要交互的Service,通过Service里面的bind方法来返回IBinder,进而返回Service的实例到Activity,Activity里面使用ServiceConnection类里面的回调方法来接收IBinder,并转换成Service实例。

  1. Service代码示例
public class MyService extends Service {
	public LocalBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        MyService getMyService() {
            return MyService.this;
        }
    }
	@Override
    public IBinder onBind(Intent intent) {
        Log.i("MyService", "service is binded");
        return mBinder;
    }

	public void showTestLog(String logInfo) {
        Log.i("MyService", logInfo);
    }
}
  1. Activity代码示例
public class MainActivity extends Activity {
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
	}
	MyService service;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyService.LocalBinder binder = (MyService.LocalBinder) iBinder;
            service = binder.getMyService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            service = null;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("MyActivity", "activity start bind service");
        Intent it = new Intent(MainActivity.this, MyService.class);
        bindService(it, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unbindService(serviceConnection);
    }

	// 执行这个方法,会在logcat看到 'i am mainactivity' 的消息输出,这样就可以调用MyService里面的方法了
    public void testBindService(View v){
        if (service != null) {
            service.showTestLog("i am mainactivity");
        }else {
            Log.e("MyActivity", "service is not bind");
        }
    }
}

本人技术有限,初学IPC,有错误请指正,谢谢!

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部