Android - Count Power button clicks and Start Activity

前端 未结 2 1118
误落风尘
误落风尘 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: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;
            }
        }
    

提交回复
热议问题