Android跨進程通信傳輸大數據

Android跨進程通信的方式大概有如下幾種:

1.Activity方式:

Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:12345678" ); 
startActivity(callIntent);

2.Content Provider 方式:

Android應用程序可以使用文件或SqlLite數據庫來存儲數據。
Content Provider提供了一種在多個應用程序之間數據共享的方式(跨進程共享數據),
應用程序可以利用Content Provider完成下面的工作
1. 查詢數據
2. 修改數據
3. 添加數據
4. 刪除數據

3.廣播方式:

Intent intent = new Intent(“com.android.ACTION_TEST);
intent.putExtra("value","content");
mContext.sendBroadcast(intent);

4.LocalSocket方式

客戶端LocalSocket代碼
//創建對象
LocalSocket localSocket = new LocalSocket();
//連接socketServerSocket
localSocket.connect(new LocalSocketAddress(String addrStr));
獲取localSocket的輸入輸出流:
outputStream = localSocket.getOutputStream();
inputStream = localSocket.getInputStream();
寫入數據:
outputStream.write("數據".getBytes());
循環接收數據:
try {    
      int readed = inputStream.read();
      int size = 0;
      byte[] bytes = new byte[0];
      while (readed != -1) {
          byte[] copy = new byte[500000]; 
          System.arraycopy(bytes, 0, copy, 0, bytes.length);
          bytes = copy;
          bytes[size++] = (byte) readed; 
          //以換行符標識成結束
          if ('\n' == (byte) readed) {
              String resultStr = new String(bytes, 0, size); 
              break;                                                         				     
        } 
       readed = inputStream.read();
    }
} catch (IOException e) {
        return false;
}


服務端LocalServerSocket代碼

//初始化
try {
    //socketAddress需跟localSocket地址一致,否則無法連接上
    serverSocket = new LocalServerSocket(socketAddress);
} catch (IOException e) {
    LoggerHelper.e("Server to establish connection exception:" + e.toString());
    e.printStackTrace();
    return false;
}
try {
    //獲取接收的LocalSocket
    localSocket = serverSocket.accept();
    //設置緩衝大小
    localSocket.setReceiveBufferSize(ConstantConfig.BUFFER_SIZE);
    localSocket.setSendBufferSize(ConstantConfig.BUFFER_SIZE);
} catch (IOException e) {
    e.printStackTrace();
    LoggerHelper.d("Waiting to be linked to a bug,error:" + e.toString());
    return false;
}
獲取輸入輸出流一致:

if (localSocket != null) {
    try {
        inputStream = localSocket.getInputStream();
        outputStream = localSocket.getOutputStream();
        /** 允許一直接收數據,一直到連接被斷開,則認爲應用端退出,自己也退出 */
        while (isLock && receiveData()) ;
    } catch (IOException e) {
        LoggerHelper.e("Get stream exception:" + e.toString());        e.printStackTrace();
        return false;
    }
}

5.AIDL Service方式

這也是本文采取的主要方式,通過AIDL讀取共享內存的方式去實現大數據的傳輸
5.1首先定義兩個AIDL文件,注意服務端和客戶端的兩個文件要一樣,並且放在同一個文件夾下。

服務端使用
package com.example.administrator.testgsensor;

import com.example.administrator.testgsensor.ITestCallbackAidlInterface;

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

interface ITestAidlInterface {
    void registerCallback(ITestCallbackAidlInterface cb);
    void unregisterCallback(ITestCallbackAidlInterface cb);
    ParcelFileDescriptor getMemoryFileDescriptor();
    void serverSendData(String data);
}
客戶端使用
// ITestCallbackAidlInterface.aidl
package com.example.administrator.testgsensor;

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

interface ITestCallbackAidlInterface {
     void clintSenddata(String data);
}
服務端實現代碼
package com.example.administrator.testgsensor;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;

public class TestService extends Service{

    private String TAG = "TestService";
    private TestInterface mTestInterface = new TestInterface();
    final RemoteCallbackList<ITestCallbackAidlInterface> mCallbackList = new RemoteCallbackList<ITestCallbackAidlInterface>();
    private MemoryFile mMemoryFile = null;
    private ParcelFileDescriptor pfd = null;
    private boolean isRunFlag = false;
    private FileDescriptor fd;

    @Override
    public void onCreate(){
        super.onCreate();
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        isRunFlag = true;
        return mTestInterface;
    }

    @Override
    public void onStart(Intent intent, int startId){
        super.onStart(intent, startId);
    }


    @Override
    public boolean onUnbind(Intent intent){
        isRunFlag = false;
        if (mMemoryFile != null){
            mMemoryFile.close();
            mMemoryFile = null;
        }
        return super.onUnbind(intent);
    }

	//實現接口ITestAidlInterface
    public class TestInterface extends ITestAidlInterface.Stub {

        @Override
        public void registerCallback(ITestCallbackAidlInterface cb) throws RemoteException {
            if(cb != null) mCallbackList.register(cb);
        }

        @Override
        public void unregisterCallback(ITestCallbackAidlInterface cb) throws RemoteException {
            if(cb != null) mCallbackList.unregister(cb);
        }

        @Override
        public ParcelFileDescriptor getMemoryFileDescriptor() throws RemoteException {
            if (pfd == null){
                createMemoryFile();
            }
            if (pfd != null && !pfd.getFileDescriptor().valid()){
                if (mMemoryFile != null){
                    mMemoryFile.close();
                    mMemoryFile = null;
                }
                try {
                    pfd.close();
                    pfd = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                createMemoryFile();
            }
            return  pfd;
        }

        @Override
        public void serverSendData(String data) throws RemoteException {
            //客戶端返回數據
        }

    }
	
	//創建共享內存塊
    private void createMemoryFile(){
        if (mMemoryFile == null){
            try {
                mMemoryFile = new MemoryFile("memfile", 1000);
                Method method = MemoryFile.class.getDeclaredMethod("getFileDescriptor");
                fd = (FileDescriptor) method.invoke(mMemoryFile);
                if (fd.valid()){
                    Log.d(TAG, "createMemoryFile: fd valid");
                    pfd = ParcelFileDescriptor.dup(fd);
                    new Thread(testRunnable ).start();
                }else {
                    Log.e(TAG, "createMemoryFile: fd = -1");
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (mMemoryFile != null){
                    mMemoryFile.close();
                    mMemoryFile = null;
                }
                pfd = null;
            }
        }
    }

    Runnable testRunnable = new Runnable() {
        @Override
        public void run() {
            try {

                while (isRunFlag){
                    byte[] testData = {0x01,0x02,0x03};
                    if (fd.valid()) {
                    	//往內存塊裏面寫數據
                        mMemoryFile.writeBytes(testData, 0, 0, testData.length);
                    } else {
                        writeStop();
                    }
                    Thread.sleep(10);
                }
                isRunFlag = false;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                isRunFlag = false;
            }
        }
    };

	//發送數據給客戶端
    private void writeStop() {
        final int n = mCallbackList.beginBroadcast();
        for (int i=0; i < n; i++) {
            try {
                mCallbackList.getBroadcastItem(i).clintSenddata("stop");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mCallbackList.finishBroadcast();
    }
}


記得在AndroidManifest.xml中註冊service
<service
	   android:name="com.example.administrator.testgsensor.TestService"
	   android:enabled="true"
	   android:exported="true">
	   <intent-filter >
	       <action android:name="com.example.administrator.testgsensor.TestService" />
	   </intent-filter>
</service>

接下來看客戶端的代碼

客戶端代碼
package com.example.administrator.testgsensor;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;

import java.io.IOException;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    private boolean isBind = false;
    private ITestAidlInterface mTestAidlInterface;
    private MemoryFile mMemoryFile;
    private boolean bRead = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binderService();
        bRead = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] data = new byte[3];
                while (bRead){
                    if (mTestAidlInterface != null && mMemoryFile != null) {
                        try {
                            //讀取共享內存塊的數據
                            mMemoryFile.readBytes(data, 0, 0, data.length);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } 
                    }
                }
            }
        }).start();
        
    }

    @Override
    protected void onDestroy() {
	    if (mTestAidlInterface != null) {
	         try {
	             mTestAidlInterface.unregisterCallback(testCallbackAidlInterface);
	         } catch (RemoteException e) {
	             e.printStackTrace();
	         }
	    }
	    unBinderService();
        super.onDestroy();
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            if (mTestAidlInterface == null) {
                mTestAidlInterface = ITestAidlInterface.Stub.asInterface(service);
                Log.d(TAG, "onServiceConnected: ");

                if (mTestAidlInterface != null) {
                    try {
                        mTestAidlInterface.registerCallback(testCallbackAidlInterface);

                        //獲取共享內存文件描述符
                        ParcelFileDescriptor pfd = mTestAidlInterface.getMemoryFileDescriptor();

                        if (pfd != null) {
                            Log.d(TAG, "pfd != null "+pfd.toString());
                            mMemoryFile = MemoryFileHelper.openMemoryFile(pfd, 1000, MemoryFileHelper.PROT_READ);
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: ");//正常情況下是不會被調用的,只有遠程服務意外停止纔會
            unBinderService();
        }
    };

    ITestCallbackAidlInterface testCallbackAidlInterface = new ITestCallbackAidlInterface() {
        @Override
        public void clintSenddata(String data) throws RemoteException {
            //服務端發送數據
        }

        @Override
        public IBinder asBinder() {
            return null;
        }
    };

    private void binderService() {
        Intent intent = new Intent();
        intent.setAction("com.example.administrator.testgsensor.TestService");
        intent.setPackage("com.example.administrator.testgsensor");
        intent.setClassName("com.example.administrator.testgsensor",
                "com.example.administrator.testgsensor.TestService");
        this.bindService(intent, conn, Context.BIND_AUTO_CREATE);
        isBind = true;
    }

    private void unBinderService() {
        if (isBind) {
            this.unbindService(conn);
            isBind = false;
        }else {
            return;
        }

        testCallbackAidlInterface = null;
        if (mMemoryFile != null) {
            mMemoryFile.close();
            mMemoryFile = null;
        }
    }

}

到此服務端和客戶端的代碼已經完成,兩個進程間就可以通過讀寫共享內存塊的方式共享大數據啦。
最後附上兩個工具類的代碼。

package com.example.administrator.testgsensor;

import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;


public class MemoryFileHelper {

    public static final int PROT_READ = 0x01;//只讀方式打開,
    public static final int PROT_WRITE = 0x02;//可寫方式打開,PROT_WRITE|PROT_READ可讀可寫方式打開
    private static final String TAG = "MemoryFileHelper";

    /**
     * 創建共享內存對象
     *
     * @param name   描述共享內存文件名稱
     * @param length 用於指定創建多大的共享內存對象
     * @return MemoryFile 描述共享內存對象
     */
    public static MemoryFile createMemoryFile(String name, int length) {
        try {
            return new MemoryFile(name, length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static MemoryFile openMemoryFile(ParcelFileDescriptor pfd, int length, int mode) {
        if (pfd == null) {
            throw new IllegalArgumentException("ParcelFileDescriptor 不能爲空");
        }
        FileDescriptor fd = pfd.getFileDescriptor();
        Log.d(TAG, "openMemoryFile: pfd="+pfd.toString());
        Log.d(TAG, "openMemoryFile: fd="+fd.toString());
        return openMemoryFile(fd, length, mode);
    }

    /**
     * 打開共享內存,一般是一個地方創建了一塊共享內存
     * 另一個地方持有描述這塊共享內存的文件描述符,調用
     * 此方法即可獲得一個描述那塊共享內存的MemoryFile
     * 對象
     *
     * @param fd     文件描述
     * @param length 共享內存的大小
     * @param mode   PROT_READ = 0x1只讀方式打開,
     *               PROT_WRITE = 0x2可寫方式打開,
     *               PROT_WRITE|PROT_READ可讀可寫方式打開
     * @return MemoryFile
     */
    public static MemoryFile openMemoryFile(FileDescriptor fd, int length, int mode) {
        MemoryFile memoryFile = null;
        try {
            memoryFile = new MemoryFile("tem", length);
            memoryFile.close();
            Class<?> c = MemoryFile.class;
            Method native_mmap = null;
            Method[] ms = c.getDeclaredMethods();
            for (int i = 0; ms != null && i < ms.length; i++) {
                if (ms[i].getName().equals("native_mmap")) {
                    native_mmap = ms[i];
                }
            }

            ReflectUtil.setField("android.os.MemoryFile", memoryFile, "mFD", fd);
            ReflectUtil.setField("android.os.MemoryFile", memoryFile, "mLength", length);
            //address 在4.4中是int類型,在6.0中是long類型。
            long address = (Integer) ReflectUtil.invokeMethod(null, native_mmap, fd, length, mode);
            ReflectUtil.setField("android.os.MemoryFile", memoryFile, "mAddress", address);

            Log.d(TAG, "openMemoryFile: mFD"+fd.toString());
            Log.d(TAG, "openMemoryFile: mLength"+length);
            Log.d(TAG, "openMemoryFile: mAddress"+address);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return memoryFile;
    }

    /**
     * 獲取memoryFile的ParcelFileDescriptor
     *
     * @param memoryFile 描述一塊共享內存
     * @return ParcelFileDescriptor
     */
    public static ParcelFileDescriptor getParcelFileDescriptor(MemoryFile memoryFile) {
        if (memoryFile == null) {
            throw new IllegalArgumentException("memoryFile 不能爲空");
        }
        ParcelFileDescriptor pfd;
        FileDescriptor fd = getFileDescriptor(memoryFile);
        pfd = (ParcelFileDescriptor) ReflectUtil.getInstance("android.os.ParcelFileDescriptor", fd);
        return pfd;
    }

    /**
     * 獲取memoryFile的FileDescriptor
     *
     * @param memoryFile 描述一塊共享內存
     * @return 這塊共享內存對應的文件描述符
     */
    public static FileDescriptor getFileDescriptor(MemoryFile memoryFile) {
        if (memoryFile == null) {
            throw new IllegalArgumentException("memoryFile 不能爲空");
        }
        FileDescriptor fd;
        fd = (FileDescriptor) ReflectUtil.invoke("android.os.MemoryFile", memoryFile, "getFileDescriptor");
        return fd;
    }

}

package com.example.administrator.testgsensor;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectUtil {
    /**
     * 根據類名,參數實例化對象
     *
     * @param className 類的路徑全名
     * @param params    構造函數需要的參數
     * @return 返回T類型的一個對象
     */
    public static Object getInstance(String className, Object... params) {
        if (className == null || className.equals("")) {
            throw new IllegalArgumentException("className 不能爲空");
        }
        try {
            Class<?> c = Class.forName(className);
            if (params != null) {
                int plength = params.length;
                Class[] paramsTypes = new Class[plength];
                for (int i = 0; i < plength; i++) {
                    paramsTypes[i] = params[i].getClass();
                }
                Constructor constructor = c.getDeclaredConstructor(paramsTypes);
                constructor.setAccessible(true);
                return constructor.newInstance(params);
            }
            Constructor constructor = c.getDeclaredConstructor();
            constructor.setAccessible(true);
            return constructor.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 執行instance的方法
     *
     * @param className  類的全名
     * @param instance   對應的對象,爲null時執行類的靜態方法
     * @param methodName 方法名稱
     * @param params     參數
     */
    public static Object invoke(String className, Object instance, String methodName, Object... params) {
        if (className == null || className.equals("")) {
            throw new IllegalArgumentException("className 不能爲空");
        }
        if (methodName == null || methodName.equals("")) {
            throw new IllegalArgumentException("methodName不能爲空");
        }
        try {
            Class<?> c = Class.forName(className);
            if (params != null) {
                int plength = params.length;
                Class[] paramsTypes = new Class[plength];
                for (int i = 0; i < plength; i++) {
                    paramsTypes[i] = params[i].getClass();
                }
                Method method = c.getDeclaredMethod(methodName, paramsTypes);
                method.setAccessible(true);
                return method.invoke(instance, params);
            }
            Method method = c.getDeclaredMethod(methodName);
            method.setAccessible(true);
            return method.invoke(instance);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 執行指定的對方法
     *
     * @param instance 需要執行該方法的對象,爲空時,執行靜態方法
     * @param m        需要執行的方法對象
     * @param params   方法對應的參數
     * @return 方法m執行的返回值
     */
    public static Object invokeMethod(Object instance, Method m, Object... params) {
        if (m == null) {
            throw new IllegalArgumentException("method 不能爲空");
        }
        m.setAccessible(true);
        try {
            return m.invoke(instance, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 取得屬性值
     *
     * @param className 類的全名
     * @param fieldName 屬性名
     * @param instance  對應的對象,爲null時取靜態變量
     * @return 屬性對應的值
     */
    public static Object getField(String className, Object instance, String fieldName) {
        if (className == null || className.equals("")) {
            throw new IllegalArgumentException("className 不能爲空");
        }
        if (fieldName == null || fieldName.equals("")) {
            throw new IllegalArgumentException("fieldName 不能爲空");
        }
        try {
            Class c = Class.forName(className);
            Field field = c.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(instance);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 設置屬性
     *
     * @param className 類的全名
     * @param fieldName 屬性名
     * @param instance  對應的對象,爲null時改變的是靜態變量
     * @param value     值
     */
    public static void setField(String className, Object instance, String fieldName, Object value) {
        if (className == null || className.equals("")) {
            throw new IllegalArgumentException("className 不能爲空");
        }
        if (fieldName == null || fieldName.equals("")) {
            throw new IllegalArgumentException("fieldName 不能爲空");
        }
        try {
            Class<?> c = Class.forName(className);
            Field field = c.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(instance, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根據方法名,類名,參數獲取方法
     *
     * @param className  類名,全名稱
     * @param methodName 方法名
     * @param paramsType 參數類型列表
     * @return 方法對象
     */
    public static Method getMethod(String className, String methodName, Class... paramsType) {
        if (className == null || className.equals("")) {
            throw new IllegalArgumentException("className 不能爲空");
        }
        if (methodName == null || methodName.equals("")) {
            throw new IllegalArgumentException("methodName不能爲空");
        }
        try {
            Class<?> c = Class.forName(className);
            return c.getDeclaredMethod(methodName, paramsType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}

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