当按下电源按钮2次或多次但是它不起作用时,我使用此代码启动活动
这是我的MyReceiver.java
代码:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
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);
}
}
}
}
manifest file
:
<receiver android:name="MyReceiver" android:enabled="true"/>
答案 0 :(得分:1)
您创建了一个接收器,但没有注册它。
在您的活动的接收器的oncreate方法注册表中
@Override
protected void onCreate() {
// initialize receiver
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
final BroadcastReceiver mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
反正。您不需要电源按钮事件的广播接收器..
您可以使用此代码
int i = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_POWER)
{
i++;
if(i == 2)
{
// Do something you want
}
}
return super.onKeyDown(keyCode, event);
}
答案 1 :(得分:1)
尝试将接收器声明为
<receiver android:name="MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" >
</action>
<action android:name="android.intent.action.SCREEN_ON">
</action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED">
</action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED">
</action>
<action android:name="android.intent.action.ACTION_SHUTDOWN">
</action>
</intent-filter>
</receiver>