Service 启动Activity

我想我们一般在Service里想启动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的方法有什么不同之处虽然效果都是一样的,对开销会怎样,希望知道的朋友能和我分享。呵呵..
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值