Android - Count Power button clicks and Start Activity

旧时模样 提交于 2019-11-28 11:50:28
Sino Raj

Try this,

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);
       }
    }

}

And,

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;
        }
    }

Try this to get power button event

 @Override

 public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {

    return true;
}

return super.dispatchKeyEvent(event);
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!