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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Chandan Wadhwa
Chandan is an Android Apps developer with good experience in building native Android applications.