Android - Count Power button clicks and Start Activity

前端 未结 2 1111
误落风尘
误落风尘 2020-12-10 22:38

I used the below code, but didnt find the solution.

MyReceiver.java:

    import android.content.BroadcastReceiver;
    import androi         


        
相关标签:
2条回答
  • 2020-12-10 23:16

    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);
     }
    
    0 讨论(0)
  • 2020-12-10 23:22

    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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题