计算按下电源按钮的次数

时间:2018-10-16 07:03:12

标签: java android button screen

我是开发Android应用程序的新手,我想做的是创建一个应用程序,该应用程序可以读取按下电源按钮的时间,以制作可访问性应用程序。

也许我可以控制或计数SCREEN_ON和SCREEN_OFF事件,这可能会有所帮助。

1 个答案:

答案 0 :(得分:0)

我搜索了答案并找到了

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

}  

我从here找到了这个答案 希望对您有帮助