Tuesday, January 24, 2012

check Phone is in Sleep or Normal Mode for Android

In this tutorial we will learn how to check whether our Android mobile is in Sleep or Idle(normal) mode.

We will use Broadcast Receiver and Intents to get notify when our device goes Sleep or Idle mode.

okay! so let's try this small app

App Name: SleepModeCheck
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: SleepModeCheckActivity


package com.rdc;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class SleepModeCheckActivity extends Activity {

 BroadcastReceiver mReceiver = null;

 public void onCreate(Bundle savedInstanceState) {

  // initialize receiver
  IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
  mReceiver = new ScreenReceiver();
  registerReceiver(mReceiver, filter);

 protected void onDestroy() {
  // unregister receiver

ScreenReceiver.java (Broadcast Receiver)
package com.rdc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {
  if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
   // do whatever you need to do here
   Log.v("Debug", "Mobile is in slepp mode..");

  } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
   // and do whatever you need to do here
   Log.v("Debug", "Mobile is in normal mode..");





Run App with Real Device or Emulator

And Switch the Sleep/Normal mode using power Button ... and see Log cat you will get message

whether device is in sleep or Idle mode via Receiver.

You can download the complete source code zip file here : SleepModeCheck

I'd love to hear your thoughts! 

No comments:

Post a Comment