Binder跨进程通信一:代码实例
进程A与进程B实现通信:
(1).创建aidl文件 interface MyApp { String getName(); String setName(String name); }(2).创建类MyAppIml继承MyApp.Stub
(3).创建MyService类
(4).在AndroidManifest.xml配置
(5).编译生成aidl文件如下 |
至此创建进程A完成。
同理创建进程B与进程A要实现通信,aidl文件必须使用同样的包名,进程B项目结构如下图:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void load(View view) { Intent intent = new Intent(); intent.setAction("com.example.test.binderframwork.MyService"); intent.setPackage("com.example.test.binderframwork"); //进程B 目的 binderServise -----> IBinder iBinder bindService(intent, new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { MyApp myApp = MyApp.Stub.asInterface(iBinder); try { myApp.setName("张三"); Log.e("------------》", " ss"); Toast.makeText(MainActivity.this, "---> " + myApp.getName(), Toast.LENGTH_SHORT).show(); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName componentName) { } }, Context.BIND_AUTO_CREATE); } } |