gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:09:50 24 4
gpt4 key购买 nike

我希望我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com