【问题标题】:How to receive extras from pendingintent?如何从pendingintent接收额外的?
【发布时间】:2015-04-16 16:35:03
【问题描述】:

我有一个启动通知的服务:

public class Notify extends Service{
@Override
public void onCreate() {

        Intent resultIntent = new Intent(this, Main.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Notification noti_builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setContentTitle("Title")
            .setContentText("Text")
            .setSound(uri)
            .setContentIntent(pIntent)
            .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        noti_builder.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, noti_builder);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

服务在此处的其他类中启动:

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent intent = new Intent(AddAlarm.this, Notify.class);
intent.putExtra("id", ID);
AlarmManager manager = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(AddAlarm.this, 0, intent, 0);
manager.set(AlarmManager.RTC_WAKEUP, notifyDate.getTimeInMillis(), pendingIntent);

我想在服务中获得额外服务。任何建议如何做到这一点?谢谢。

【问题讨论】:

    标签: android android-intent android-pendingintent


    【解决方案1】:

    在 Notify 类中,将代码从 onCreate 方法移动到具有以下签名的 onStartCommand 方法

    onStartCommand (Intent intent, int flags, int startId)
    

    然后您可以从传递到方法中的意图访问额外内容。

    【讨论】:

    • 谢谢,它有效。我可以再问一个问题吗?使用此代码,我收到的通知很少,而不是一个。我在哪里犯错了?我应该将pendingintent标志更改为其他东西吗?
    • 您收到多少通知?它们是重复的吗?或者您是否尝试“覆盖”现有通知(如果存在)?谢谢。
    • 执行此代码后,我通常会收到 3 个或更多 (5-6) 个通知。都是重复的。我只通过单击按钮执行此代码一次。我已经注意到的是,当我完全重新启动应用程序(从主页按钮菜单中删除并重新启动它)应用程序启动后立即显示重复通知。当我将其更改为 onStartCommand 而不是 onCreate 时,重复显示应用程序崩溃。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2023-03-27
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多