android process communication between two application

实现两个application之间的进程通信,需要用到service,并且在client端根据是否需要多线程可以分成使用Messenger和AIDL两种方法来实现。当你的client端需要多个线程时,此时需要用到AIDL, 在AIDL的方法,当被remote process调用时,会在thread pool启动一个线程来实现。下面是方法步骤:
一. 首先在Android studio中建立自己的AIDL 接口,并提供 相应的方法。如 ,

// IMyAidlInterface.aidl
package com.example.almoliu.aidlserver;

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

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

    long getCount();
}

然后在server端启动一个service,并实现该接口,返回该接口的一个Stub(IBinder)实例。如,

package com.example.almoliu.aidlserver;

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

import java.lang.ref.WeakReference;

public class CounterService extends Service {

    private long counter = 0;
    private static int WHOLE_COUNT = 60000;
    private static int INTERVAL_COUNT = 1000;

    private CountDownTimer mCountDownTimer = new CountDownTimer(WHOLE_COUNT,INTERVAL_COUNT) {
        @Override
        public void onTick(long millisUntilFinished) {
            counter = millisUntilFinished/INTERVAL_COUNT;
        }
        @Override
        public void onFinish() {
            counter = -1;
        }
    };

    public CounterService() {
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                mCountDownTimer.start();
            }
        });
        thread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCountDownTimer.cancel();
    }

    private long getCounter() {
        return counter;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mIBinder;
    }

    static private class MyStub extends IMyAidlInterface.Stub {

        private WeakReference<CounterService> mWeakCounterService;

        public MyStub(CounterService counterService) {
            mWeakCounterService = new WeakReference<CounterService>(counterService);
        }

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public long getCount() throws RemoteException {
            return mWeakCounterService.get().getCounter();
        }
    }

    private IBinder mIBinder = new MyStub(this);

}

然后需要在AndroidManifest文件中定义该服务的ACTION和属性,来提供绑定该service的途径。如

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.almoliu.aidlserver">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".CounterService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">
            <intent-filter>
                <action android:name="com.example.almoliu.CounterService"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>
        </service>
    </application>

</manifest>

然后在client端,首先你需要建立一个同样的AIDL文件,且要保证与Server端 的AIDL文件是统一个package,然后定义自己的ServiceConnection,实现AIDL接口的实例,如

package com.example.almoliu.aidlclient;

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.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.almoliu.aidlserver.IMyAidlInterface;

public class MainActivity extends AppCompatActivity {


    TextView tv;
    private IMyAidlInterface iMyAidlInterface;

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


        tv = (TextView)findViewById(R.id.text_tv);

        Button mButton = (Button)findViewById(R.id.start_btn);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    long value = iMyAidlInterface.getCount();
                    tv.append(String.valueOf(value));
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });

        Intent i = new Intent("com.example.almoliu.CounterService");
        bindService(i,mServiceCOnnection,BIND_AUTO_CREATE);
    }

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

    private ServiceConnection mServiceCOnnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            iMyAidlInterface = null;
        }
    };


}

这样你就可以通过 private IMyAidlInterface iMyAidlInterface调用server中的service方法了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值