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
-------------------------------------------
SleepModeCheckActivity.java
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; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // initialize receiver IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mReceiver = new ScreenReceiver(); registerReceiver(mReceiver, filter); } @Override protected void onDestroy() { // unregister receiver this.unregisterReceiver(mReceiver); super.onDestroy(); } }
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 { @Override 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.."); } } }
AndroidManifest.xml
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