我试图在屏幕关闭(锁定)时关闭WiFi,并在屏幕打开(解锁)时再次打开它。
我创建了一个BroadcastReceiver;在清单中放入以下代码:
<receiver android:name="MyIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.USER_PRESENT" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>这是MyIntentReceiver类
package org.androidpeople.boot;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyIntentReceiver extends BroadcastReceiver {
// Called when boot completes
public static boolean startup;
@Override
public void onReceive(Context context, Intent intent) {
// Set what activity should launch after boot completes
System.out.println("Intent Action: " + intent.getAction());
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
System.out.println("locked : ACTION_SCREEN_OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
System.out.println("not locked : ACTION_SCREEN_ON ");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
System.out.println("User Unlocking it ");
}
else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
// this to indicate that program is running
// automaticlly not manually by user
startup = true;
System.out.println("Automatic BOOT at StartUp");
Intent startupBootIntent = new Intent(context, LaunchActivity.class);
startupBootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupBootIntent);
}
}
}结果是- ACTION_SCREEN_ON和ACTION_SCREEN_OFF都没有触发!USER_PRESENT和BOOT_COMPLETED工作得很好,但另一个不行。我使用的是模拟器,而不是真正的设备--这会导致问题吗?
有什么帮助吗?我需要捕捉屏幕的打开和关闭,以便启用/禁用WiFi以节省电池。
提前感谢
发布于 2011-09-10 03:49:46
您不能通过XML捕获这些意图(我忘记为什么了)。但是,您可以使用Service在其onStartCommand()中注册BroadcastReceiver成员,并在其onDestroy()中注销该成员。这将要求服务在后台持续运行,或者只要您需要,就在后台运行,因此一定要探索替代路线。
您可以在Service类中定义BroadcastReceiver,如下所示:
private final class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//stuff
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//other stuff
}
}
}对于一个稍微复杂的示例,但展示了BroadcastReceiver和Service是如何交互的,请参见我的应用程序ElectricSleep中的CheckForScreenBugAccelerometerService。
发布于 2011-12-01 02:05:10
要捕获SCREEN_OFF和SCREEN_ON操作(可能还有其他操作),您必须通过代码配置BroadcastReceiver,而不是通过清单。
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenStateBroadcastReceiver();
registerReceiver(mReceiver, intentFilter);它经过测试,工作正常。
https://stackoverflow.com/questions/7366631
复制相似问题