0

目前我正在使用前台服务,我在其中注册 BATTERY_ACTION_CHANGED 并在接收广播时更新通知。

这在 android 9 上运行良好。但在 android 11(oneplus 7 pro)上,只要应用程序处于前台或电池优化关闭,它就可以正常工作。我看到了通知,但它永远不会更新。我想在关闭应用程序或关闭电池优化后我没有收到广播。

我在下面提供了我的代码。我感谢您的帮助。

清单.xml

 <service
        android:name=".BatteryTrackingService"
        android:enabled="true"
        android:exported="true"/>


    <receiver
        android:name=".BatteryBroadcast"
        android:enabled="true"
        android:exported="true"/>

    <activity
        android:name=".MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

BatteryTrackingService.java

@Override
public void onCreate() {

    Log.i("BatteryTrackingService", "onCreate: this context"+ this);

    notificationHandler = NotificationHandler.getInstance(this.getApplicationContext());

    batteryBroadcast = new BatteryBroadcast();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryBroadcast, intentFilter);
}

//Runs whenever we create object of this class.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    NotificationCompat.Builder builder =
            notificationHandler.getBatteryMonitoringNotificationBuilder();
    startForeground(notificationHandler.notificationID, builder.build());

    return START_STICKY;
}

BatteryBroadcast.java

@Override public void onReceive(Context context, Intent intent) {

    Log.i("Broadcast", "Context: " + context);

    Log.i("App Broadcsat", " Broadcast received.");
    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    int batteryPct = (int) (level * 100 / (float) scale);
    Log.i("Battery Broadcast", "Battery Percentage: " + batteryPct);

  

    NotificationHandler notificationHandler = NotificationHandler.getInstance(context.getApplicationContext());
    NotificationManager manager = notificationHandler.getNotificationManager();
    NotificationCompat.Builder builder =
            notificationHandler.getBatteryMonitoringNotificationBuilder();
    builder.setContentTitle("Battery Level: " + batteryPct + "%");
    manager.notify(notificationHandler.notificationID, builder.build());

    

}
4

0 回答 0