Android实现远程服务端与客户端的通信AIDLSumDemo

第三次作业:使用AIDL实现远程服务端与客户端的通信

注:所建工程均为Android 6.0 所以只要是Android 6.0(包括6.0)以上的真机,模拟机都可以使用

首先来了解什么是AIDL:

AIDL是一个缩写,全称是Android Interface Definition Language,也就是Android接口定义语言。是的,首先我们知道的第一点就是:AIDL是一种语言,而设计这门语言的目的是为了实现进程间通信,所以接下来我们就开始来使用AIDL来实现远程通信。

这里写了一个案例:AIDLSumDemo1

通过在服务端写Sum方法,通过接口实现客户端的调用,一般会建立两个工程,一个是客户端,一个是服务端,通过复制AIDL文件,保证两者一致,但其实现在一个工程里也是可以的,本例就是在一个工程里实现的。

相关代码:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    //public static int w(String tag, String msg, Throwable tr)
    private static final String TAG = "MainActivity";

    IAdditionService service;
    AdditionServiceConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initService();

        Button buttonCalc = (Button)findViewById(R.id.buttonCalc);
        buttonCalc.setOnClickListener(new View.OnClickListener() {
            EditText value1 = (EditText)findViewById(R.id.value1);
            EditText value2= (EditText)findViewById(R.id.value2);
            TextView result = (TextView)findViewById(R.id.result);
            @Override
            public void onClick(View v) {
                int v1, v2, res = -1;
                v1 = Integer.parseInt(value1.getText().toString());
                v2 = Integer.parseInt(value2.getText().toString());

                try {
                    res = service.add(v1, v2);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                result.setText(Integer.valueOf(res).toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseService();
    }

    class AdditionServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder boundService) {
            service = IAdditionService.Stub.asInterface(boundService);
            Toast.makeText(MainActivity.this, "Service connected", Toast.LENGTH_LONG).show();
            Log.i(TAG, "onServiceConnected: 连接成功");
            Log.d(TAG, "onServiceConnected() called with: name = [" + name.toString() + "], boundService = [" + boundService.toString()+ "]");

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            service = null;
            Toast.makeText(MainActivity.this, "Service disconnected", Toast.LENGTH_LONG).show();
        }
    }
    /*
     * This method connects the Activity to the service
     * 这个方法使Activity(客户端)连接到服务(service)
     */
    private void initService() {
        connection = new AdditionServiceConnection();
        Intent i = new Intent();
        i.setClassName("com.example.aidlsumdemo1", com.example.aidlsumdemo1.AdditionService.class.getName());
        bindService(i, connection, Context.BIND_AUTO_CREATE);
        Log.d(TAG, "initService() called");
    }

    /*
     * This method disconnects the Activity from the service
     * 这个方法使Activity(客户端)从服务(service)断开
     */
    private void releaseService() {
        unbindService(connection);
        connection = null;
    }


}

activity_main.xml:

 
       
        
        

        

        
        

        

        

    

新建的Class—AdditionService.java:

public class AdditionService extends Service {
    public AdditionService() {
    }
    private static final String TAG = "AdditionService";
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        Log.d(TAG, "onBind() called with: intent = [" + intent.toString() + "]");
        return new IAdditionService.Stub() {
            /*
             * Implement com.android.hellosumaidl.IAdditionService.add(int, int)
             * 实现了add方法
             */
            @Override
            public int add(int value1, int value2) throws RemoteException {
                return value1 + value2;
            }
        };

    }
}

在project视图下,找到main文件夹,新建aidl文件夹,在里面新建AIDL文件,或者直接新建AIDL文件也可,系统会自动生成文件夹,文件名为:IAdditionService.aidl。最重要的一点,在建立好aidl文件之后,一定要编译一下,才可以,要不是无法实现通信的,点击像锤子的按钮,或者快捷键(ctrl+F9).

IAdditionService.aidl:

// IAdditionService.aidl
package com.example.aidlsumdemo1;

// Declare any non-default types here with import statements

interface IAdditionService {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    int add(in int value1, in int value2);

}

AndroidManifest.xml:


    

    
        
            

            
        
    


实验可能用到的截图:

Android实现远程服务端与客户端的通信AIDLSumDemo_第1张图片
Android实现远程服务端与客户端的通信AIDLSumDemo_第2张图片
Android实现远程服务端与客户端的通信AIDLSumDemo_第3张图片

Android实现远程服务端与客户端的通信AIDLSumDemo_第4张图片

源代码下载:AIDLSumSemo1.zip

你可能感兴趣的:(Android,Studio)