Co Koder Co Koder - 1 month ago 13
Android Question

Alarmmanager with pending Intent

The code snippet below....

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
///////////Do something////////////////////////
showtext.startScan();
//SEt Alarm
Intent intent = new Intent(this, TextReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager am=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+9000, pi);}


And my Receiver

TextReceiver extends BroadcastReceiver{

public void onReceive(Context context, Intent intent)
{
///Show text/////
}
}


The thing is that when I run the program after 9sn, I am getting an error that "The app stopped unexpextdly." . My goal is to show the text every 9sn
Why I get this error ?
What is the correct usage of alarmmanager in the main activity ?
OR Should I set alarm in the BroadcastReceiver ?
Which one does make sense am.setRepeating or am.set in terms of my goal ?

*Edit: How can I change my alarm code to run in the Broadcast Receiver ? *

Answer

//try this

AlarmManager am=(AlarmManager)getApplicationContext getSystemService(Context.ALARM_SERVICE);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, PendingIntent.FLAG_CANCEL_CURRENT);

  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),(9 * 1000), pendingIntent);
Comments