android - 具有 PendingIntent 的全局广播或本地广播

标签 android broadcast android-pendingintent localbroadcastmanager

我在 IntentService 中运行后台任务。我在通知栏中显示进度(使用 NotificationManager),如果有人点击该通知,我想取消任务。

我通过广播服务成功实现了它。但是,我在想是否可以对 localBroadcast 做同样的事情。

如果我将“registerReceiver”更改为“LocalBroadcastManager.getInstance(this).registerReceiver”,代码将不起作用。你能告诉我为什么我不能使用带有 pendingintent 的 localbroadcast 吗?

谢谢,

目前我的代码是:

boolean isCancelled;
Context context;

NotificationManager mNotifyManager;
NotificationCompat.Builder mBuilder;
int mId = 2;
protected void onHandleIntent(Intent intent) {
    isCancelled = false;
    context = getApplicationContext();
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.migrationdesk.mylibman.MyServiceClass.STOP");
    registerReceiver(receiver, filter);
    getNotification();
    mainTask(); // THIS IS SOME BACKGROUND TASK
}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
                if(action.equals("com.migrationdesk.mylibman.MyServiceClass.STOP")){
                    isCancelled = true;
                }

    }
};

protected void getNotification() {
    Intent newintent = new Intent();
    newintent.setAction("com.migrationdesk.mylibman.MyServiceClass.STOP");
    PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, newintent, 0);
    mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(context);
    mBuilder.setContentTitle("Cover Download")
                .setContentText("In progress")
                .setContentIntent(pIntent)
                .setSmallIcon(R.drawable.ic_launcher);
}

最佳答案

However, I was thinking is it possible to do the same with localBroadcast.

那是不可能的。 PendingIntent 仅适用于常规广播,并且管理通知栏的代码无论如何都不在您的进程中。

关于android - 具有 PendingIntent 的全局广播或本地广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908104/

相关文章:

android - 添加行数据时出现 IllegalArgumentException

java - UDP 广播上下文中的 'wildcard address' 是什么?

android - 广播和 Intent 过滤器

apache-spark - 我可以在 sparkConf 中为不同的 sql 设置不同的 autoBroadcastJoinThreshold 值吗?

android - 来自多个通知的启动 Activity 会覆盖之前的 Intent

android - 小部件发送多种类型的 Intent

android - View中 "getScrollX and getScrollY"是什么意思

android - 使用按钮更改属性 use_flash true/false

android - 在 Android 的 TTS 中无延迟地处理多种语言

android - 两个带有 PendingIntents 的按钮 - Widget