Zeigt beim Vordergrunddienst ein kleines Symbol im Status anstelle eines weißen Punkts an
Posted: 11 Jan 2025, 11:45
Ich schreibe Vordergrunddienstcode und setze „setSmallIcon“. Wenn es ausgeführt wird, konnte das Symbol nicht in der Statusleiste angezeigt werden. Was ich möchte, ist das erste und zweite Bild wie unten:


und unten ist nicht das, was ich want:

Ich habe den Foregroundservice-Code unten geschrieben:
unten ist MainActivity.java:
und ich habe Berechtigungscode in manifest.xml geschrieben, einschließlich:post_notification und foreground, mehrere Tage alt. Ich habe Erfolg, aber gestern habe ich versehentlich Code gelöscht und konnte den Code, den ich geschrieben habe, nicht finden .


und unten ist nicht das, was ich want:

Ich habe den Foregroundservice-Code unten geschrieben:
Code: Select all
public class MyForegroundService extends Service {
private static final String CHANNEL_ID = "MyForegroundServiceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("My Foreground Service")
.setContentText("Running...")
.setSmallIcon(R.drawable.ic_launcher_foreground) // 使用默认图标
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
Code: Select all
Intent serviceIntent = new Intent(this, MyForegroundService.class);
startForegroundService(serviceIntent);