4

My app has a service that add a floating button to WindowManager.

I want to remove my floating button from WindowManager When user press the power key and turn screen off. So when user turn screen on my floating button does not conceal (mask) android pattern screen lock.

I add following code to my Service but it doesn't work !

Should I add any permission or my service must run in background?!

public class Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) 
        {
            try{
                // Remove Floating Button from Window Manager
                MyWindowManager.removeView(floating_btn);
                // Stop Service
                stopSelf();
            }
            catch (Exception e)
            {
                //Log Error
            }   
        } 
    }

}
Jessica
  • 685
  • 1
  • 9
  • 23

2 Answers2

1

Normally you would declare a receiver in your manifest. Something like this

<receiver android:name="com.whatever.client.Receiver"
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF" />
    </intent-filter>
</receiver>

For some reason (not sure why), you don't seem to be able to do this for SCREEN_OFF or SCREEN_ON. So you have to register it programmatically.

As a test, I made a simple app.

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    startService(new Intent(context, MyService.class));
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(receiver, filter);
    }
}

With a simple service.

public class MyService extends IntentService {
    public MyService() {
        super("MyService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e("MyService", "Screen was turned off!");
    }
}
mpkuth
  • 6,994
  • 2
  • 27
  • 44
0

I've got the same problem and I'm working on it now. In your case it didn't work because 1) your "stopSelf()" have to in class extended by Service, not by BroadcastReceiver. 2) if you want to remove a view from window manager you have to somehow pass(the information of view) that view from that method where you'd declared it to method where you want to remove that view

S.Drumble3
  • 59
  • 10