繁体   English   中英

按下 Android 电源按钮

[英]Android Power Button Pressed

我正在尝试创建一个可以在按下电源按钮时响应的应用程序。 更具体地说,它会在按下 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 的情况下实现这一点。

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

至于你的第二个问题,尝试实现一个IntentService

这是解决方案

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM