按下Android电源按钮

时间:2013-09-15 17:07:09

标签: android

我正在尝试创建一个可以在按下电源按钮时响应的应用程序。更具体地说,当按下2或3次时会响应它。

目前,我尝试了以下内容:

public class SMSKey extends BroadcastReceiver{

    static int countPowerOff = 0;
    private Activity activity = null;
    public SMSKey(Activity activity){
        this.activity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
            countPowerOff++;
        }else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
            if(countPowerOff == 2){
                Intent i = new Intent(activity, SMSOptions.class);
                activity.startActivity(i);
            }
        }
    }

}

并在我的清单

<receiver android:name=".SMSKey">
        <intent-filter >
            <action android:name="android.intent.action.SCREEN_OFF"/>
            <action android:name="android.intent.action.SCREEN_ON"/>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
            <action android:name="android.intent.action.ACTION_SHUTDOWN"/>
        </intent-filter>
    </receiver>

最后在我的 MainActivty.java

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
SMSKey mReceiver = new SMSKey(this);
registerReceiver(mReceiver, filter);

即使这样可行,但它仅在第一次起作用,当按下电源按钮时,它不会在第二次或第三次尝试时工作。为什么会这样 ??

另一个问题:正如您所看到的,我在MainActivity中使用此KeyPress事件,这意味着应用程序将始终处于打开状态。有没有其他方法可以实现这一点而无需进入MainActivity。

2 个答案:

答案 0 :(得分:2)

这甚至不是Android问题。收到3键后,您永远不会重置countPowerOff变量。即使已经这样做了,你必须考虑添加一个警报,在一些小的超时后将你的countPowerOff变量重置为零。它将允许您避免用户不打算与您的应用程序交互并只按下按钮的情况,但它仍然会被计算。

关于您的第二个问题,请尝试实施IntentService

答案 1 :(得分:0)

这是解决方案

public class MyReceiver extends BroadcastReceiver {
private static int countPowerOff = 0;

public MyReceiver (){

}

@Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){    
    Log.e("In on receive", "In Method:  ACTION_SCREEN_OFF");
    countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
    Log.e("In on receive", "In Method:  ACTION_SCREEN_ON");
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
    Log.e("In on receive", "In Method:  ACTION_USER_PRESENT");
    if (countPowerOff >= 2)
    {
        countPowerOff=0;
        Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
        Intent i = new Intent(context, About.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
    }
}
  }
 }