Android Studio 1-16 Service進程間通信

Android Studio 1-16 Service進程間通信

方法一

服務端

package com.example.messager_server;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

import androidx.annotation.NonNull;

public class MyService extends Service {
    final Messenger messenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //接收客戶端的消息
            Bundle data = msg.getData();
            String string = data.getString("hello", "king");
            Toast.makeText(MyService.this, ""+string, Toast.LENGTH_SHORT).show();

            //發送給客戶端消息
            Messenger replyTo = msg.replyTo;/*獲取信使*/

            Message message = new Message();/*給信使一個信息*/

            Bundle bundle = new Bundle();/*創建 Bundle 對象 */
            bundle.putString("person","諸葛亮");/*放入信息*/

            message.setData(bundle);/*發現需要 Bundle 對象*/
            //倒敘編譯
            try {
                replyTo.send(message);/*信使帶信息返回*/
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    });
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}

<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.king"></action>
            </intent-filter>
        </service>

客戶端

package com.example.messager_client;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Messenger clientMessage = new Messenger(new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String person = data.getString("person");
            Toast.makeText(MainActivity.this, ""+"來自服務器的消息是------"+person, Toast.LENGTH_SHORT).show();
        }
    });

    private Messenger serverMessage;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            serverMessage = new Messenger(iBinder);
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("hello","服務器你好 我是客戶端");
            message.setData(bundle);

            //非常重要的一句話
            message.replyTo = clientMessage;

            try {
                serverMessage.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        intent.setAction("com.king");
        intent.setPackage("com.example.messager_server");
        bindService(intent,connection, Service.BIND_AUTO_CREATE);
    }

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

方法二

服務端

// IMyAidlInterface.aidl
package com.example.aidl_server;

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

interface IMyAidlInterface {
    int add(int a, int b);
    int multiply(int a, int b);
}

package com.example.aidl_server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

    IBinder iBinder = new IMyAidlInterface.Stub(){

        @Override
        public int add(int a, int b) throws RemoteException {
            return a + b;
        }

        @Override
        public int multiply(int a, int b) throws RemoteException {
            return a * b;
        }

    };

}
<service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.hong.king"></action>
            </intent-filter>
        </service>

客戶端

package com.example.aidl_client;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Toast;

import com.example.aidl_server.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {

    private IMyAidlInterface iMyAidlInterface;
    private ServiceConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        intent.setAction("com.hong.king");
        intent.setPackage("com.example.aidl_server");

        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
                try {
                    //調用服務端的add方法並得到結果
                    int num=iMyAidlInterface.add(4,6);
                    int multiply = iMyAidlInterface.multiply(3, 7);
                    Toast.makeText(MainActivity.this, ""+num, Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, ""+multiply, Toast.LENGTH_SHORT).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };
        bindService(intent,connection, Service.BIND_AUTO_CREATE);


    }

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章