我想我们一般在Service里想启动Activity一定会这样写:
这样写就会报错的:
03-11 02:37:09.737: ERROR/AndroidRuntime(7881): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
提示要加上FLAG_ACTIVITY_NEW_TASK,所以加上 intentv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一行就可以了。
但若看的源码够的话,还会发现有另外一种方法在Service里面启动Activity的另外一种方法:通过PendingIntent,下面就以Tag中TagView(Activity)和TagService为例子:
TagView里启动TagService并且把待会在TagService里面启动的Activity用Pending将其封装好并且传给TagService:
通过pending.send(this, 0, result);启动了对应的Activity.
这里也是PendingIntent的用法之一。
我不太明白这两种启动Activity的方法有什么不同之处虽然效果都是一样的,对开销会怎样,希望知道的朋友能和我分享。呵呵..
Intent intentv = new Intent(Intent.ACTION_VIEW);
intentv.setData(uri);
intentv.putExtra("keepTitle", true);
startActivity(intentv);
这样写就会报错的:
03-11 02:37:09.737: ERROR/AndroidRuntime(7881): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
提示要加上FLAG_ACTIVITY_NEW_TASK,所以加上 intentv.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这一行就可以了。
但若看的源码够的话,还会发现有另外一种方法在Service里面启动Activity的另外一种方法:通过PendingIntent,下面就以Tag中TagView(Activity)和TagService为例子:
TagView里启动TagService并且把待会在TagService里面启动的Activity用Pending将其封装好并且传给TagService:
TagService.saveMessages(this, msgs, false, getPendingIntent());private PendingIntent getPendingIntent() {
Intent callback = new Intent();
callback.setClass(this, TagViewer.class);
callback.setAction(Intent.ACTION_VIEW);
callback.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
callback.putExtra(EXTRA_KEEP_TITLE, true);
return PendingIntent.getActivity(this, 0, callback, PendingIntent.FLAG_CANCEL_CURRENT);
}
public static void saveMessages(Context context, NdefMessage[] msgs, boolean starred,
PendingIntent pending) {
Intent intent = new Intent(context, TagService.class);
intent.putExtra(TagService.EXTRA_SAVE_MSGS, msgs);
intent.putExtra(TagService.EXTRA_STARRED, starred);
intent.putExtra(TagService.EXTRA_PENDING_INTENT, pending);
context.startService(intent);
}
@Override
public void onHandleIntent(Intent intent) {
if (intent.hasExtra(EXTRA_SAVE_MSGS)) {
Parcelable[] msgs = intent.getParcelableArrayExtra(EXTRA_SAVE_MSGS);
NdefMessage msg = (NdefMessage) msgs[0];
ContentValues values = NdefMessages.toValues(this, msg, false, System.currentTimeMillis());
Uri uri = getContentResolver().insert(NdefMessages.CONTENT_URI, values);
if (intent.hasExtra(EXTRA_PENDING_INTENT)) {
Intent result = new Intent();
result.setData(uri);
PendingIntent pending = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_INTENT);
try {
pending.send(this, 0, result);
} catch (CanceledException e) {
if (DEBUG) Log.d(TAG, "Pending intent was canceled.");
}
}
return;
}
.....
}
通过pending.send(this, 0, result);启动了对应的Activity.
这里也是PendingIntent的用法之一。
我不太明白这两种启动Activity的方法有什么不同之处虽然效果都是一样的,对开销会怎样,希望知道的朋友能和我分享。呵呵..