计算按下电源按钮的次数
Count the times that the power button is pressed
我是开发 Android 应用程序的新手,我想做的是创建一个可以读取按下电源按钮的时间的应用程序,以制作一个辅助功能应用程序。
也许如果我可以控制或计算 SCREEN_ON 和 SCREEN_OFF 事件,这可能会有所帮助。
我搜索了答案并找到了这个
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 找到了这个答案
希望对你有帮助
我是开发 Android 应用程序的新手,我想做的是创建一个可以读取按下电源按钮的时间的应用程序,以制作一个辅助功能应用程序。
也许如果我可以控制或计算 SCREEN_ON 和 SCREEN_OFF 事件,这可能会有所帮助。
我搜索了答案并找到了这个
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 找到了这个答案 希望对你有帮助