Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alarmmanager with pending Intent

Tags:

android

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 unexpectedly". Why I get this error?

My goal is to show the text every 9sn. What is the correct usage of AlarmManager in the main activity
OR Should I set alarm in the BroadcastReceiver ? Which one does makes 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 ? **

like image 867
Co Koder Avatar asked Jan 17 '23 08:01

Co Koder


1 Answers

//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);
like image 183
Padma Kumar Avatar answered Jan 27 '23 05:01

Padma Kumar