Detecting whether screen is locked or not in Android

Posted By : Chandan Wadhwa | 22-Sep-2014

 

 

Sometimes there are requirements when an app wants to control the action when the screen is in either on or off state . Just to clear the situation i am providing an example :-

 

In case when screen is in off state we can disable the backgrounds process perform by the activity just to reduce process load and again start the process when screen comes to on state.

 

We can control all these by creating a broadcast receiver which continuously check for the screen's off and on state.

 

Code to explain the concept is given below :-

 

 

1) Register the receiver in the AndroidManifest file

 

<receiver android:name="ScreenOnOffReceiver" ></receiver>

 

2) Define the “ScreenOnOffReceiver” class which detect whether screen is in on state or off state

 

 

 public class ScreenOnOffReceiver extends BroadcastReceiver {

		@Override	
		public void onReceive(Context context, Intent intent)
			{
		            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
			            {    
		                  Log.v("Screen mode", "Screen is in off State”); 
					//Your logic comes here whatever you want perform when screen is in off state			                  			            }
			      else
				if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
			            {
			            Log.v("Screen mode"," Screen is in on State”); 
			            //Your logic comes here whatever you want perform when screen is in on state	      
			
			            }
			}
}

 

3)IntentFilter to add actions

 

 

 

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_screen);
		 IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);

		 filter.addAction(Intent.ACTION_SCREEN_OFF);
		
  }

 

4) Instantiating the “ScreenReceiver” class and register broaadcast receiver

 

 

 

 	 ScreenOnOffReceiver  onoffReceiver = new ScreenOnOffReceiver();
	 registerReceiver(onoffReceiver, filter);
 

Thanks

 

About Author

Author Image
Chandan Wadhwa

Chandan is an Android Apps developer with good experience in building native Android applications.

Request for Proposal

Name is required

Comment is required

Sending message..