How to call WakefulBroadcastReceiver

4.4k views Asked by At

I have read lot about WakefulBroadcastReceiver... but didn't get anywhere about how to even call this from main activity. whenever I search how to call WakefulBroadcastReceiver the result always shows me how to call IntentService from WakefulBroadcastReceiver...

Well to call IntentService we write the code "startService()" in activity or in WakefulBroadcastReceiver... to call BroadcastReceiver we write

AlarmManager am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
      PendingIntent.getBroadcast(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT));

But I don't find anywhere how to call WakefulBroadcastReceiver... please help..

1

There are 1 answers

2
rafsanahmad007 On BEST ANSWER

android.support.v4.content.WakefulBroadcastReceiver is a helper class that receives a device wakeful event.

you shouldoverride onReceive() method where you can call a service or perform your task.

WakefulBroadcastReceiver uses wake lock, so you must provide WAKE_LOCK permission in AndroidManifest.xml. WakefulBroadcastReceiver is implemented as

public class AlarmReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        MainActivity.getTextView2().setText("Enough Rest. Do Work Now!");
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
        ringtone.play();
    }
} 

in menifest add

 <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

call AlarmReceiver like this:

    Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent  pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);

also add receiver tag in manifest:

<receiver android:name=".AlarmReceiver"/>

For full working sample see this link:http://www.concretepage.com/android/android-alarm-clock-tutorial-to-schedule-and-cancel-alarmmanager-pendingintent-and-wakefulbroadcastreceiver-example