Reputation: 95
i want my activity to refresh then display notification based on refreshed values every 5 minutes. I already got a refresh button and it's working fine. but when i try to activate the refresh button before the notification appears in the timer. my app just crashes.
Here are my codes
//Oncreate
if(ordercounter>0) //ordercounter is the updated value
{
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 1, 300000);
}
//Timer
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);
}
// My refresh button
refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
Upvotes: 1
Views: 917
Reputation: 2337
I think you should use an AlarmManager and set it to be activated every 5 minutes:
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
millisecondsToFirstActivation,
millisecondsForRepeatingSchedule, alarmIntent);
The you create a broadcast receiver that is going to display the notification
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
displayNotification();
}
}
you can find more info here: http://developer.android.com/training/scheduling/alarms.html
Upvotes: 2