我想将数据从应用程序 A 发送到应用程序 B。我可以使用两种方法来解决这个问题。
一种方法是使用startService()
. 我把数据放入一个Intent
,通过startService()
发送数据。应用程序 B 获取数据并将其写入数据库。
第二种方法是使用aContentProvider
将数据写入应用程序B 的数据库。因为要发送的数据太多,所以我使用子线程来写数据。
他们都工作正常。请帮我判断哪种方法更好。
意图方法:
private ExecutorService mSingleThreadExecutor = Executors.newSingleThreadExecutor();
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,
"onStartCommand #" + this.toString() + " #"
+ intent.getIntExtra(EXTRA_APP_CODE, -1) + " #"
+ SystemClock.elapsedRealtime());
recordDataOfIntent(intent);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
private void recordDataOfIntent(Intent intent) {
int dataType = intent.getIntExtra(EXTRA_DATA_TYPE, -1);
switch (dataType) {
case DataConstants.APP_START: {
mSingleThreadExecutor.execute(getRecordAppStartRunnable(intent));
break;
}
case DataConstants.USER_ACTION: {
mSingleThreadExecutor.execute(getRecordUserActionRunnable(intent));
break;
}
case DataConstants.PAGE_VISIT: {
mSingleThreadExecutor.execute(getRecordPageVisitRunnable(intent));
break;
}
case DataConstants.EVENT: {
mSingleThreadExecutor.execute(getRecordEventRunnable(intent));
break;
}
case DataConstants.KV_EVENT: {
mSingleThreadExecutor.execute(getRecordKVEventRunnable(intent));
break;
}
case DataConstants.EXCEPTION: {
mSingleThreadExecutor.execute(getRecordExceptionRunnable(intent));
break;
}
default: {
break;
}
}
}
内容提供者方法:
private ExecutorService mSingleThreadExecutor = Executors.newSingleThreadExecutor();
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
return 0;
}
@Override
public String getType(Uri arg0) {
int option = mUriMatcher.match(arg0);
switch (option) {
case URI_TABLE_EVENT_CODE: {
return URI_TABLE_EVENT_TYPE;
}
default: {
throw new IllegalArgumentException("Unknown URI: " + arg0);
}
}
}
@Override
public Uri insert(Uri arg0, final ContentValues arg1) {
Log.e(TAG, "insert");
int option = mUriMatcher.match(arg0);
switch (option) {
case URI_TABLE_EVENT_CODE: {
Runnable runnable = new Runnable() {
@Override
public void run() {
DBUtil.addKVEventInfo(mDatabase, arg1);
}
};
mSingleThreadExecutor.execute(runnable);
break;
}
default: {
break;
}
}
return getEventTableUri();
}
@Override
public boolean onCreate() {
Log.e(TAG, "onCreate");
mDatabase = DBUtil.initDatabase(getContext());
mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mUriMatcher.addURI(AUTHORITY, TABLE_EVENT, URI_TABLE_EVENT_CODE);
return true;
}