一、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-tw/n/195540.html