Remove floating button from WindowManager when power key is pressed

My application has a service that adds a floating button to the WindowManager.

I want to remove my floating button from WindowManager. When the user presses the power key and turns off the screen. Therefore, when the user rotates the screen on my floating button, it does not hide the Android masking screen lock.

I am adding the following code to my service, but it does not work!

Should I add any permission or should my service run in the 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
            }   
        } 
    }

}
+4
source share
2 answers

Usually you declare a receiver in your manifest. Something like that

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

- ( , ) , , SCREEN_OFF SCREEN_ON. .

.

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

.

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

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.e("MyService", "Screen was turned off!");
    }
}
+1

, . , 1) "stopSelf()" , , BroadcastReceiver. 2) , - ( ), , ,

0

Source: https://habr.com/ru/post/1568047/


All Articles