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