0

I'm new in developing Android apps, what I want to do is create an application which can read the times that the power button was pressed, to make an accessibility app.

Maybe if I can control or count the SCREEN_ON and SCREEN_OFF events this could be helpful.

Bruno
  • 3,872
  • 4
  • 20
  • 37
Marcos
  • 11
  • 2
  • Check this link: https://stackoverflow.com/questions/30029978/how-to-detect-device-power-button-press-twice-in-android-programmatically – Neha Mehta Oct 16 '18 at 07:07
  • SCREEN_ON and SCREEN_OFF receiver may not properly work, because the screen turns off automatically too. – kuber singh Oct 16 '18 at 07:12

1 Answers1

0

I searched for the answer and found this

MainActivity.java

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        MyReceiver mReceiver = new MyReceiver (this);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}  

Receiver.java

 public class MyReceiver extends BroadcastReceiver {
    static int countPowerOff=0;
    private Activity activity=null;
    public MyReceiver (Activity activity)
    {
    this.activity=activity;
    }
    @Override
    public void onReceive(Context context, Intent intent) {

      Log.v("onReceive", "Power button is pressed.");

      Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
             .show();

     if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) 
{
    countPowerOff++;    
} 
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) 
{
      if(countPowerOff==5)
      {
          Intent i =new Intent(activity,NewActivity.class);
          activity.startActivity(i);
       }
    }

}  

I found this answer from here hope it helps

Kevin Kurien
  • 812
  • 6
  • 14