【问题标题】:How do I detect if device is charging from background如何检测设备是否从后台充电
【发布时间】:2020-03-01 23:20:52
【问题描述】:

我在 Android 的开发者说明中进行了详尽的搜索,但无法找到如何在插入设备时执行特定操作,以及在拔出设备时执行其他操作。

我已尝试设置如下所示的广播接收器,但它不会运行:

    <receiver android:name=".PowerConnectionReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
        </intent-filter>
    </receiver>

我了解到,从 API 26 起,您将无法再接收清单中注册的某些广播,必须动态注册它们。

我需要在后台运行它,但不知道怎么做?这篇2019年更新的文章(api 26之后)暗示我应该可以做到。

充电状态可以像插入设备一样轻松更改,因此监控充电状态的变化并相应地更改刷新率非常重要。

每当设备连接或断开电源时,BatteryManager 都会广播一个操作。接收这些事件很重要即使您的应用没有运行,特别是因为这些事件会影响您启动应用的频率以启动后台更新,因此您应该在清单中注册一个 BroadcastReceiver 以监听这两个事件通过在意图过滤器中定义 ACTION_POWER_CONNECTED 和 ACTION_POWER_DISCONNECTED。

我的最终目标是在插入或拔出设备时调用广播接收器。

我将如何实施?

【问题讨论】:

  • 你需要通过代码注册这个接收器
  • 但这不允许我从后台获取意图。它只会让活动的意图是活着的。

标签: java android broadcastreceiver


【解决方案1】:

实现这一点的最佳方法是让服务在后台运行,这样您就可以在用户不使用应用的情况下接收来自 android 的广播。

首先在清单文件中注册服务。

<Service android:name=".serviceName"/>

现在创建与上面清单中注册的名称相同的类,该类必须扩展 Service。

    public class BackgroundService extends Service {
        private static final int NOTIF_ID = 1;
        private static final String NOTIF_CHANNEL_ID = "AppNameBackgroundService";

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId){

            //Add broadcast receiver for plugging in and out here
            ChargeDetection chargeDetector = new ChargeDetection(); //This is the name of the class at the bottom of this code.

            IntentFilter filter = new IntentFilter();
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            filter.addAction(Intent.ACTION_POWER_CONNECTED);
            filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
            this.registerReceiver(chargeDetector, filter);

            startForeground();

            return super.onStartCommand(intent, flags, startId);
        }

        private void startForeground() {
            createNotificationChannel();
            Intent notificationIntent = new Intent(this, MainActivity.class);

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                    notificationIntent, 0);

            startForeground(NOTIF_ID, new NotificationCompat.Builder(this,
                    NOTIF_CHANNEL_ID) // don't forget create a notification channel first
                    .setOngoing(true)
                    .setSmallIcon(R.mipmap.final_icon)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("Background service is running")
                    .setContentIntent(pendingIntent)
                    .build());
        }

        private void createNotificationChannel() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel serviceChannel = new NotificationChannel(
                        NOTIF_CHANNEL_ID,
                        "Foreground Service Channel",
                        NotificationManager.IMPORTANCE_DEFAULT
                );
                NotificationManager manager = getSystemService(NotificationManager.class);
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

    class ChargeDetection extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Now check if user is charging here. This will only run when device is either plugged in or unplugged.
        }
    }   
    }

【讨论】:

    【解决方案2】:

    你需要通过代码注册这个接收器

    您可以运行 WorkManager 每 15 分钟运行一次(最少每 15 分钟运行一次) 注册接收器,检查是否在充电 注销接收者

    【讨论】:

    • 我的问题是应用程序需要在充电时打开请勿打扰,tasker似乎能够有效地做到这一点,我不确定他们如何管理这个post api 26。文章还暗示你可以从后台做到这一点,这不是真的吗?
    • tasker 被定义为系统应用?
    • 只需为 WorkManager 设置约束:setRequiresCharging(true)。它在设备充电时运行。
    猜你喜欢
    • 2015-12-11
    • 2014-06-18
    • 2011-07-02
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    相关资源
    最近更新 更多