Binder跨进程通信一:代码实例

进程A与进程B实现通信:


进程A

(项目结构)



(1).创建aidl文件


interface MyApp {
    String getName();

    String setName(String name);
}
 
(2).创建类MyAppIml继承MyApp.Stub
 
     
public class MyAppIml extends MyApp.Stub {
    private String name;
    @Override
    public String getName() throws RemoteException {
        return name;
    }

    @Override
    public String setName(String name) throws RemoteException {
        this.name = name;
        return name;
    }

}


(3).创建MyService类


public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }


    /**
     * 提供给客户端B
     * @param intent
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        MyAppIml myApp = new MyAppIml();
        return myApp;
    }
}

(4).在AndroidManifest.xml配置


<service android:name=".MyService">
    <intent-filter>
        <action android:name="com.example.test.binderframwork.MyService"/>
    </intent-filter>
</service>


(5).编译生成aidl文件如下





至此创建进程A完成。



同理创建进程B与进程A要实现通信,aidl文件必须使用同样的包名,进程B项目结构如下图:




进程B与进程A通信
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);
    }
}

猜你喜欢

转载自blog.csdn.net/u014133119/article/details/80799925
今日推荐