Move activity to foreground when screen is in off state

Posted By : Chandan Wadhwa | 22-Sep-2014

Sometimg there's a situation when we want to take the response from  activity when the screen is in off state. So there is a need to open the activity and automatically unlocking phone.

 

Implementation scenario -

 

1) In case of alarm app when phone screen is in off state although alarm app starts, phone screen unlocked automatically and activity comes to foreground.

 

2) In case when app response via shaking the phone and when phone screen is in off state, although we want to that activity will respond.

 

Step by step implementation is given below -

 

1) Add  android:showOnLockScreen="true" property to the target activity


Example:-

 

 

 

 

 
        
 
 

 

2) Override the onAttachedToWindow() method from activity class. This method is called when view is attach to window.

 

 

 @Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		
        Window window = getWindow();       	

        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON

                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED

                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON

                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD

                | WindowManager.LayoutParams.FLAG_FULLSCREEN
                
               
                
        		);
	super.onAttachedToWindow();

}

 

Activity will be reopen after 3 second when screen is in off state

 

 

 public class ScreenActivity extends Activity {
{
	protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			Handler handler = new Handler(); 
	    		handler.postDelayed(new Runnable() { 
	         	public void run() { 
	        	Intent intent=new 										Intent(getApplicationContext(),ScreenActivity.class);
	        	startActivity(intent);

	         } 
	    }, 3000);
}
 

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..