我想从服务启动前台通知。这是我的代码:
显现 :
<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>
广播接收器:
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "Charger connected (#)", Toast.LENGTH_SHORT).show();
Intent startIntent = new Intent(context, NotificationService.class);
startIntent.setAction("a_abhi_apps.batterychargenotifier.action.startforeground");
context.startService(startIntent);
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
Toast.makeText(context, "Charger disconnected (#)", Toast.LENGTH_SHORT).show();
stopIntent.setAction("a_abhi_apps.batterychargenotifier.action.stopforeground");
}
}
NotificationService.java:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.startforeground")) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Charging ")
.setContentText("Phone is charging");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// manager.notify(0, builder.build());
startForeground(0, builder.build());
} else if (intent.getAction().equals("a_abhi_apps.batterychargenotifier.action.stopforeground")) {
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
我已在清单中声明广播接收器,因为它接收到电源状态已更改。因此 MainActivity 中没有相关代码。
我在 NotificationService.java 中评论了这一行:
manager.notify(0, builder.build());
如果我删除评论,我会收到通知。但我想让它坚持通知空间,以便我可以使用该服务执行一些其他操作。
但我无法将其作为前台通知。