Android 进程间通信
- - SegmentFault 最新的文章单例居然失效了,一个地方设置值,另个地方居然取不到,这怎么可能. 排查半天,发现这两就不在一个进程里,才恍然大悟……. 按照操作系统中的描述:进程一般指一个执行单元,在 PC 和移动设备上指一个程序或者一个应用. 我们都知道,系统为 APP 每个进程分配的内存是有限的,如果想获取更多内存分配,可以使用多进程,将一些看不见的服务、比较独立而又相当占用内存的功能运行在另外一个进程当中. 
package com.ryg.sayhi.aidl;
import com.ryg.sayhi.aidl.Student;
interface IMyService {
    List<Student> getStudent();
    void addStudent(in Student student);
}说明:package com.ryg.sayhi.aidl; parcelable Student;说明:这里parcelable是个类型,首字母是小写的,和Parcelable接口不是一个东西,要注意。
package com.ryg.sayhi.aidl;
import java.util.Locale;
import android.os.Parcel;
import android.os.Parcelable;
public final class Student implements Parcelable {
    public static final int SEX_MALE = 1;
    public static final int SEX_FEMALE = 2;
    public int sno;
    public String name;
    public int sex;
    public int age;
    public Student() {
    }
    public static final Parcelable.Creator<Student> CREATOR = new
            Parcelable.Creator<Student>() {
                public Student createFromParcel(Parcel in) {
                    return new Student(in);
                }
                public Student[] newArray(int size) {
                    return new Student[size];
                }
            };
    private Student(Parcel in) {
        readFromParcel(in);
    }
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(sno);
        dest.writeString(name);
        dest.writeInt(sex);
        dest.writeInt(age);
    }
    public void readFromParcel(Parcel in) {
        sno = in.readInt();
        name = in.readString();
        sex = in.readInt();
        age = in.readInt();
    }
    
    @Override
    public String toString() {
        return String.format(Locale.ENGLISH, "Student[ %d, %s, %d, %d ]", sno, name, sex, age);
    }
}说明:通过AIDL传输非基本类型的对象,被传输的对象需要序列化,序列化功能java有提供,但是android sdk提供了更轻量级更方便的方法,即实现Parcelable接口,关于android的序列化,我会在以后写文章介绍。这里只要简单理解一下就行,大意是要实现如下函数  /**
 * @author scott
 */
public class MyService extends Service
{
    private final static String TAG = "MyService";
    private static final String PACKAGE_SAYHI = "com.example.test";
    private NotificationManager mNotificationManager;
    private boolean mCanRun = true;
    private List<Student> mStudents = new ArrayList<Student>();
    
    //这里实现了aidl中的抽象函数
    private final IMyService.Stub mBinder = new IMyService.Stub() {
        @Override
        public List<Student> getStudent() throws RemoteException {
            synchronized (mStudents) {
                return mStudents;
            }
        }
        @Override
        public void addStudent(Student student) throws RemoteException {
            synchronized (mStudents) {
                if (!mStudents.contains(student)) {
                    mStudents.add(student);
                }
            }
        }
        //在这里可以做权限认证,return false意味着客户端的调用就会失败,比如下面,只允许包名为com.example.test的客户端通过,
        //其他apk将无法完成调用过程
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            String packageName = null;
            String[] packages = MyService.this.getPackageManager().
                    getPackagesForUid(getCallingUid());
            if (packages != null && packages.length > 0) {
                packageName = packages[0];
            }
            Log.d(TAG, "onTransact: " + packageName);
            if (!PACKAGE_SAYHI.equals(packageName)) {
                return false;
            }
            return super.onTransact(code, data, reply, flags);
        }
    };
    @Override
    public void onCreate()
    {
        Thread thr = new Thread(null, new ServiceWorker(), "BackgroundSercie");
        thr.start();
        synchronized (mStudents) {
            for (int i = 1; i < 6; i++) {
                Student student = new Student();
                student.name = "student#" + i;
                student.age = i * 5;
                mStudents.add(student);
            }
        }
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        super.onCreate();
    }
    @Override
    public IBinder onBind(Intent intent)
    {
        Log.d(TAG, String.format("on bind,intent = %s", intent.toString()));
        displayNotificationMessage("服务已启动");
        return mBinder;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy()
    {
        mCanRun = false;
        super.onDestroy();
    }
    private void displayNotificationMessage(String message)
    {
        Notification notification = new Notification(R.drawable.icon, message,
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_ALL;
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MyActivity.class), 0);
        notification.setLatestEventInfo(this, "我的通知", message,
                contentIntent);
        mNotificationManager.notify(R.id.app_notification_id + 1, notification);
    }
    class ServiceWorker implements Runnable
    {
        long counter = 0;
        @Override
        public void run()
        {
            // do background processing here.....
            while (mCanRun)
            {
                Log.d("scott", "" + counter);
                counter++;
                try
                {
                    Thread.sleep(2000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}说明:为了表示service的确在活着,我通过打log的方式,每2s打印一次计数。上述代码的关键在于onBind函数,当客户端bind上来的时候,将IMyService.Stub mBinder返回给客户端,这个mBinder是aidl的存根,其实现了之前定义的aidl接口中的抽象函数。        <service
            android:name="com.ryg.sayhi.MyService"
            android:process=":remote"
            android:exported="true" >
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="com.ryg.sayhi.MyService" />
            </intent-filter>
        </service>
   说明:上述的 <action android:name="com.ryg.sayhi.MyService" />是为了能让其他apk隐式bindService,通过隐式调用的方式来起activity或者service,需要把category设为default,这是因为,隐式调用的时候,intent中的category默认会被设置为default。
import com.ryg.sayhi.aidl.IMyService;
import com.ryg.sayhi.aidl.Student;
public class MainActivity extends Activity implements OnClickListener {
    private static final String ACTION_BIND_SERVICE = "com.ryg.sayhi.MyService";
    private IMyService mIMyService;
    private ServiceConnection mServiceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            mIMyService = null;
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            //通过服务端onBind方法返回的binder对象得到IMyService的实例,得到实例就可以调用它的方法了
            mIMyService = IMyService.Stub.asInterface(service);
            try {
                Student student = mIMyService.getStudent().get(0);
                showDialog(student.toString());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button1) {
            Intent intentService = new Intent(ACTION_BIND_SERVICE);
            intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MainActivity.this.bindService(intentService, mServiceConnection, BIND_AUTO_CREATE);
        }
    }
    public void showDialog(String message)
    {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("scott")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show();
    }
    
    @Override
    protected void onDestroy() {
        if (mIMyService != null) {
            unbindService(mServiceConnection);
        }
        super.onDestroy();
    }
}