【问题标题】:Run task when show notification显示通知时运行任务
【发布时间】:2017-06-06 17:02:57
【问题描述】:

(对不起我的英语)

我的第一个项目需要帮助,我必须在周五完成学习课程...

我正在尝试创建一个应用程序,该应用程序将显示一个通知,其中包含添加提醒的表中的描述。我对显示下一个描述的机制有疑问。显示通知后,我对应用程序进行了描述。不幸的是,当应用程序关闭时,这不起作用。

public void onReceive(Context context, Intent intent) {
    ScheduleNotification.completeWakefulIntent(intent);

    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    descToShow = d1;

    DataBaseHandler dbh = new DataBaseHandler(context);
    dbh.open();
    dbh.DeleteRow(descToShow);
    dbh.close();


    Toast.makeText(context, descToShow, Toast.LENGTH_LONG).show();

    //notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.icon);
    builder.setContentTitle(descToShow);
    builder.setContentText(descToShow); //--description event--
    builder.setAutoCancel(false).build();

    //from android dev:
    Intent resultIntent = new Intent(context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    stackBuilder.addParentStack(MainActivity.class);

    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT );
    builder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1, builder.build());
    PendingIntent notifyPIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    builder.setContentIntent(notifyPIntent);
}

有什么想法吗?

我的github上的所有代码:https://github.com/azernax/dForget

【问题讨论】:

  • 不要为每个值使用单独的SharedPreferences - 一个可以容纳所有值。相关值应存储在一个文件中

标签: android background notifications task


【解决方案1】:

问题是当MainActivity 不在内存中时,您使用MainActivity 中的静态字段(因此您获得默认值而不是onCreate() 中设置的值)。正确的解决方案是再次加载数据(在您的情况下来自SharedPreferences)。

我希望这对你有帮助。如果您有任何问题,请发表评论

【讨论】:

  • 感谢帮助解决我的 SharedPreferences 问题。但我有新问题:(例如,当我创建 2 个通知时,第一个通知不显示,只是无限循环中显示第二个通知...你能帮我吗?当前代码在我的 github 上。
  • 您需要在 NotificationBuilder 中设置通知 ID - 在您的情况下,为 d1、d2 和 d3 设置 ID 1、2 和 3 是一个合理的想法
猜你喜欢
  • 1970-01-01
  • 2017-06-07
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多