【问题标题】:PendingIntent and Notification IntentPendingIntent 和通知意图
【发布时间】:2013-10-15 14:38:18
【问题描述】:

我发现下面的代码是多余的。我在这里缺少一些基本的东西吗?有没有办法减少这里的重复代码。我可以使用 Intent 或 PendingIntent 对象吗,为什么同时使用?

    Intent updateUI = new Intent(SENDTOBACKGROUND_SERVICE);
    updateUI.putExtra("Signal", God.YELLOW);
    sendBroadcast(updateUI);

    Intent sendNotification = new Intent(DriverService.this, DriverHome.class);
    sendNotification.putExtra("Signal", God.YELLOW);

    PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, sendNotification, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification n = new NotificationCompat.Builder(DriverService.this)
            .setContentTitle("Attempting to update location")
            .setContentText("Cab @(last) " + currentLocationInText)
            .setSmallIcon(R.drawable.yellow).setContentIntent(pIntent).setAutoCancel(true)
            .build();

    ((NotificationManager) DriverService.this.getSystemService(NOTIFICATION_SERVICE)).notify("Taxeeta", R.id.cabLocation, n);

【问题讨论】:

  • PendingIntent 使您能够使用您的权限在另一个可能缺少此类权限的应用程序中运行您的代码。

标签: android android-intent android-pendingintent


【解决方案1】:

不,两者都需要。 PendingIntentIntent 的包装。如果没有 Intent 来包装,您就不能拥有 PendingIntent。而且您不能将Intent 放在Notification 中。当您想将Intent 移交给另一个组件时,您需要使用PendingIntent,以便其他组件可以在将来的某个时间为您发送Intent(作为一种“代理”) .

【讨论】:

    【解决方案2】:

    如文档中所述

    http://developer.android.com/reference/android/app/PendingIntent.html#getActivity%28android.content.Context,%20int,%20android.content.Intent,%20int%29

    “检索将启动新活动的 PendingIntent,例如调用 Context.startActivity(Intent)”,因此您需要 PendingIntent 和 Intent。

    【讨论】:

    • 为了感谢您的好回答,我还为您的另一个回答 +1。我接受了大卫的回答,因为他之前回答过。
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2012-11-15
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多