其他分享
首页 > 其他分享> > android – 按下电源键后从WindowManager中删除浮动按钮

android – 按下电源键后从WindowManager中删除浮动按钮

作者:互联网

我的应用程序有一个向WindowManager添加浮动按钮的服务.

我想从WindowManager中删除我的浮动按钮当用户按下电源键并关闭屏幕时.所以当用户在我的浮动按钮上打开屏幕时不会隐藏(掩码)android模式屏幕锁定.

我将以下代码添加到我的服务中,但它不起作用!

我应该添加任何权限还是我的服务必须在后台运行?!

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

}

解决方法:

通常,您会在清单中声明receiver.像这样的东西

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

标签:android,service,window-managers
来源: https://codeday.me/bug/20190708/1402539.html