Android IPC通信方式及其實現

一、Bundle

Bundle是Android系統中最基礎的IPC通信方式,可以在Activity之間傳遞數據。可以向Bundle中存放各種基本數據類型,如字符串、整型、布爾值等,也可以存放複雜的Parcelable對象。

示例代碼如下:

“`
//Activity1將數據存入Bundle並啟動Activity2
Bundle bundle = new Bundle();
bundle.putInt(“intData”, 1);
bundle.putString(“stringData”, “hello”);
MyParcelableObject parcelableObject = new MyParcelableObject();
bundle.putParcelable(“parcelableData”, parcelableObject);
Intent intent = new Intent(this, Activity2.class);
intent.putExtras(bundle);
startActivity(intent);

//Activity2從Intent中獲取數據
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
int intData = bundle.getInt(“intData”);
String stringData = bundle.getString(“stringData”);
MyParcelableObject parcelableObject = bundle.getParcelable(“parcelableData”);
“`

二、AIDL

AIDL全名為Android Interface Definition Language,是Android系統中遠程服務通信的一種方式,支持進程間的方法調用。通過AIDL,我們可以定義接口,並用一個服務向外提供這個接口,其他進程通過綁定服務可以獲取到該接口的代理對象,進而進行方法調用。

示例代碼如下:

MyInterface.aidl文件定義

“`
interface MyInterface {
void sendData(in String data);
String getData();
}
“`

MyInterfaceImpl.java實現

“`
public class MyInterfaceImpl extends MyInterface.Stub {
private String mData;

@Override
public void sendData(String data) {
mData = data;
}

@Override
public String getData() {
return mData;
}
}
“`

MyService.java服務定義

“`
public class MyService extends Service {
private MyInterfaceImpl mBinder = new MyInterfaceImpl();

@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
“`

Activity中調用遠程接口

“`
private MyInterface mInterface;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mInterface = MyInterface.Stub.asInterface(service);
}

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

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}

private void sendDataToRemoteService(String data) {
try {
mInterface.sendData(data);
} catch (RemoteException e) {
e.printStackTrace();
}
}

private String getDataFromRemoteService() {
try {
return mInterface.getData();
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
“`

三、Messenger

Messenger是AIDL的一種簡化版,它是Google提供的一種輕量級IPC方式,通過Handler實現進程間的通訊。Messenger是基於AIDL實現的,但對於進程間傳輸數據,只能使用Bundle類型。

示例代碼如下:

MyService.java定義Messenger

“`
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SEND_DATA:
Bundle bundle = msg.getData();
String data = bundle.getString(“data”);
mData = data;
Messenger clientMessenger = msg.replyTo;
Message replyMsg = Message.obtain(null, MSG_REPLY_DATA);
replyMsg.getData().putString(“reply_data”, “reply ” + mData);
try {
clientMessenger.send(replyMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
private Messenger mMessenger = new Messenger(new MyHandler());
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
“`

Activity中與遠程進程通訊

“`
private Messenger mMessenger;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MyService.class);
Messenger messenger = new Messenger(new MyHandler());
intent.putExtra(“messenger”, messenger);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}

private void sendDataToRemoteService(String data) {
Message msg = Message.obtain(null, MSG_SEND_DATA);
Bundle bundle = new Bundle();
bundle.putString(“data”, data);
msg.setData(bundle);
msg.replyTo = mMessenger;
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REPLY_DATA:
String replyData = msg.getData().getString(“reply_data”);
break;
default:
super.handleMessage(msg);
}
}
};

private Messenger mClientMessenger = new Messenger(mHandler);

private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMessenger = new Messenger(service);
}

@Override
public void onServiceDisconnected(ComponentName name) {
mMessenger = null;
}
};
“`

四、ContentProvider

ContentProvider是Android系統中數據共享的一種方式,由一個進程提供數據,其他進程通過URI訪問數據。可以用它在不同應用程序之間共享數據,而且還可以保證數據的完整性和安全性。

示例代碼如下:

MyContentProvider.java

“`
public class MyContentProvider extends ContentProvider {
private MyDatabaseHelper mDbHelper;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(“com.example”, “table1”, 1);
sUriMatcher.addURI(“com.example”, “table1/#”, 2);
}
@Override
public boolean onCreate() {
mDbHelper = new MyDatabaseHelper(getContext());
return true;
}
@Nullable
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor cursor;
switch (sUriMatcher.match(uri)) {
case 1:
cursor = db.query(“table1”, projection, selection, selectionArgs, null, null, sortOrder);
break;
case 2:
String id = uri.getPathSegments().get(1);
cursor = db.query(“table1”, projection, “_id = ?”, new String[]{id}, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException(“Unknown URI: ” + uri);
}
return cursor;
}
@Nullable
@Override
public String getType(Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
long rowId = db.insert(“table1”, null, values);
if (rowId > 0) {
Uri insertUri = ContentUris.withAppendedId(uri, rowId);
getContext().getContentResolver().notifyChange(insertUri, null);
return insertUri;
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case 1:
count = db.delete(“table1”, selection, selectionArgs);
break;
case 2:
String id = uri.getPathSegments().get(1);
count = db.delete(“table1”, “_id = ?”, new String[]{id});
break;
default:
throw new IllegalArgumentException(“Unknown URI: ” + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case 1:
count = db.update(“table1”, values, selection, selectionArgs);
break;
case 2:
String id = uri.getPathSegments().get(1);
count = db.update(“table1”, values, “_id = ?”, new String[]{id});
break;
default:
throw new IllegalArgumentException(“Unknown URI: ” + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
“`

Activity中訪問數據

“`
private void accessData() {
Uri uri = Uri.parse(“content://com.example/table1”);
String[] projection = {“_id”, “name”, “description”};
Cursor cursor = getContentResolver().query(uri, projection, null, null,null);
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
String description = cursor.getString(2);
}
cursor.close();
}
“`

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/195540.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-02 20:35
下一篇 2024-12-02 20:35

相關推薦

  • Python緩存圖片的處理方式

    本文將從多個方面詳細闡述Python緩存圖片的處理方式,包括緩存原理、緩存框架、緩存策略、緩存更新和緩存清除等方面。 一、緩存原理 緩存是一種提高應用程序性能的技術,在網絡應用中流…

    編程 2025-04-29
  • Python在線編輯器的優勢與實現方式

    Python在線編輯器是Python語言愛好者的重要工具之一,它可以讓用戶方便快捷的在線編碼、調試和分享代碼,無需在本地安裝Python環境。本文將從多個方面對Python在線編輯…

    編程 2025-04-28
  • Android ViewPager和ScrollView滑動衝突問題

    Android開發中,ViewPager和ScrollView是兩個常用的控件。但是當它們同時使用時,可能會發生滑動衝突的問題。本文將從多個方面介紹解決Android ViewPa…

    編程 2025-04-28
  • Android如何點擊其他區域收起軟鍵盤

    在Android應用中,當輸入框獲取焦點彈出軟鍵盤後,我們希望能夠點擊其他區域使軟鍵盤消失,以提升用戶體驗。本篇文章將說明如何實現這一功能。 一、獲取焦點並顯示軟鍵盤 在Andro…

    編程 2025-04-28
  • Java表單提交方式

    Java表單提交有兩種方式,分別是get和post。下面我們將從以下幾個方面詳細闡述這兩種方式。 一、get方式 1、什麼是get方式 在get方式下,表單的數據會以查詢字符串的形…

    編程 2025-04-27
  • 跨域通信浮標——實現客戶端之間的跨域通信

    本文將介紹跨域通信浮標的使用方法,該浮標可以實現客戶端之間的跨域通信,解決了瀏覽器同源策略的限制,讓開發者能夠更加方便地進行跨域通信。 一、浮標的原理 跨域通信浮標的原理是基於浮動…

    編程 2025-04-27
  • 用Pythonic的方式編寫高效代碼

    Pythonic是一種編程哲學,它強調Python編程風格的簡單、清晰、優雅和明確。Python應該描述為一種語言而不是一種編程語言。Pythonic的編程方式不僅可以使我們在編碼…

    編程 2025-04-27
  • Java多版本支持實現方式

    本文將從以下幾個方面闡述如何實現Java多版本支持,並給出可行的代碼示例。 一、多版本Java環境概述 Java是一門跨平台的編程語言,但是在不同的應用場景下,可能需要使用不同版本…

    編程 2025-04-27
  • SpringBoot Get方式請求傳參用法介紹

    本文將從以下多個方面對SpringBoot Get方式請求傳參做詳細的闡述,包括URL傳參、路徑傳參、請求頭傳參、請求體傳參等,幫助讀者更加深入地了解Get請求方式下傳參的相關知識…

    編程 2025-04-27
  • 通信專業Python和Java的開發技巧

    本文旨在介紹通信專業Python和Java的開發技巧,為讀者提供實用且可操作的思路和方法。 一、Python在通信領域中的應用 Python是一種優秀的程序設計語言,因其易學易用、…

    編程 2025-04-27

發表回復

登錄後才能評論