Android 使用定时器自动更新通知

标签 android timer notifications

我希望我的 Activity 每 5 分钟刷新一次,然后根据刷新的值显示通知。我已经有了一个刷新按钮,它工作正常。但是当我尝试在通知出现在计时器中之前激活刷新按钮时。我的应用程序崩溃了。

这是我的代码

//创建

            if(ordercounter>0) //ordercounter is the updated value
            {

             MyTimerTask myTask = new MyTimerTask();

                Timer myTimer = new Timer();
                myTimer.schedule(myTask, 1, 300000);
            }

//定时器

class MyTimerTask extends TimerTask {
    public void run() {

        refresh.performClick(); // this line is the cause of error pls help
        generateNotification(getApplicationContext(), "You have "+ ordercounter+ " pending orders!");
    }
}

private void generateNotification(Context context, String message) {

    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    String appname = context.getResources().getString(R.string.app_name);
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification;
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, Admin.class), 0);


        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context);
        notification = builder.setContentIntent(contentIntent)
                .setSmallIcon(icon).setTicker(appname).setWhen(0)
                .setAutoCancel(true).setContentTitle(appname)
                .setContentText(message).build();

        notificationManager.notify((int) when, notification);




}

//我的刷新按钮

refresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             Intent intent = getIntent();
             intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                finish();
                startActivity(intent);

        }
    });

最佳答案

我认为您应该使用 AlarmManager 并将其设置为每 5 分钟激活一次:

Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            millisecondsToFirstActivation,
            millisecondsForRepeatingSchedule, alarmIntent);

您创建一个将显示通知的广播接收器

public class MyAlarmReceiver extends BroadcastReceiver {

    @Override 
    public void onReceive(Context context, Intent intent) {
        displayNotification();
    } 
} 

您可以在这里找到更多信息: http://developer.android.com/training/scheduling/alarms.html

关于Android 使用定时器自动更新通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165595/

相关文章:

android - 权限被拒绝,同时在 Android SD 卡中写入图像文件

Android:当 EditText 是子级时如何使布局可点击

javascript - 如何在输入字段 keyup 事件上添加等待计时器?

notifications - Toastr:如何防止鼠标悬停时粘性 toast 淡出?

android - 使用 AlarmManager 设置重复通知 - Android

ruby-on-rails - 我对在 Rails 中创建通知系统的看法

c# - Xamarin.Android 设备要求

java - 取消选中android中的单选按钮

c - 这个 "alarm"错误是什么意思?

javascript - 一页上有多个 JavaScript 计时器