Laetan
Laetan

Reputation: 899

Receive event and intent while screen is off on Android

I need a service to handle event while the screen is off, like receiving delayed messages (with the Handler) and internet connection state change.

Is it possible for a service to get those signal without permanently using the PARTIAL_WAKE_LOCK, since I don't need the service to run all the time?

Upvotes: 3

Views: 845

Answers (2)

Jibran Khan
Jibran Khan

Reputation: 3256

You need BroadcastReceivers to receive different states. Refer to Android Documentation for more information

http://developer.android.com/reference/android/content/BroadcastReceiver.html

Also for example, you can refer here https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/ Some snippet from the example link provided

registerReceiver(
      new ConnectivityChangeReceiver(),
      new IntentFilter(
            ConnectivityManager.CONNECTIVITY_ACTION));

BroadcastReceiver implementation

public class ConnectivityChangeReceiver
               extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
      debugIntent(intent, "grokkingandroid");
   }

   private void debugIntent(Intent intent, String tag) {
      Log.v(tag, "action: " + intent.getAction());
      Log.v(tag, "component: " + intent.getComponent());
      Bundle extras = intent.getExtras();
      if (extras != null) {
         for (String key: extras.keySet()) {
            Log.v(tag, "key [" + key + "]: " +
               extras.get(key));
         }
      }
      else {
         Log.v(tag, "no extras");
      }
   }

}

As StenSoft suggested you can use AlarmManager for delayed messages or any other scheduling task. I have used the below example and its working

public class Alarm extends BroadcastReceiver 
{    
    @Override
    public void onReceive(Context context, Intent intent) 
    {   
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        // Put here YOUR code.
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

        wl.release();
    }

    public void SetAlarm(Context context)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
    }
}

Upvotes: 1

StenSoft
StenSoft

Reputation: 9609

For delayed messages, use alarm.

For internet connection changes on background, use WakefulBroadcastReceiver.

Upvotes: 1

Related Questions