我希望我的活动刷新,然后每5分钟根据刷新的值显示通知。我已经有一个刷新按钮,它工作正常。但是当我在计时器中出现通知之前尝试激活刷新按钮时。我的应用程序崩溃了。
这是我的代码
// OnCreate中
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);
}
});
答案 0 :(得分:2)
我认为您应该使用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