I am trying to turn off WiFi when the screen is off (locked), and turn it on again when the screen is on (unlocked).
I made BroadcastReceiver ; enter this code:
<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>
and this is the class 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); } } }
And the result is that both ACTION_SCREEN_ON and ACTION_SCREEN_OFF never fired! USER_PRESENT and BOOT_COMPLETED worked fine, while the other BOOT_COMPLETED not. I use an emulator, not a real device - can this cause a problem?
Any help? I need to turn on and off the screen to enable / disable WiFi to save battery power.
Thanks in advance
user935143
source share