android - 按下电源键时从 WindowManager 中删除 float 按钮

标签 android service window-managers

我的应用程序有一项服务可以向 WindowManager 添加 float 按钮。

我想在用户按下电源键并关闭屏幕时从 WindowManager 中删除我的 float 按钮。因此,当用户在我的 float 按钮上打开屏幕时,不会隐藏(屏蔽)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在你的 list 中。像这样

<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 - 按下电源键时从 WindowManager 中删除 float 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27533985/

相关文章:

android - GreenRobot EventBus 错误 : No subscribers registered for event

android - 我是否必须知道卡的 AID 是什么才能使用 Android HCE 进行卡仿真?

用于暂停/恢复另一个音乐播放器应用程序的音乐的 Android 应用程序

symfony - 不存在的服务 "request_stack"

window-managers - 在 Enlightenment 窗口管理器中编程

linux - 我应该使用哪个窗口管理器作为示例?

linux - 构建窗口管理器

Android:将值从容器 Activity 传递到其 fragment

android - Firebase 身份验证 - 没有来自谷歌登录提供商的电子邮件

linux - Service 和 Systemctl 的区别