如何检测设备是否正在从后台充电

问题描述 投票:0回答:2

我在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
2个回答
0
投票
您可以运行WorkManager使其每15分钟运行一次(最小为每15分钟运行一次)注册接收器,检查它是否正在充电注销接收者

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

<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.
        }
    }   
    }
© www.soinside.com 2019 - 2024. All rights reserved.