首页 > 解决方案 > 带有“startForeground(..) 的服务仅在应用程序处于后台时才需要显示通知

问题描述

我对实施服务有一点问题。即使应用程序在后台,即使用户正确杀死应用程序,我也会运行服务。我在互联网上搜索并通过启动服务“前台”查看,服务不会杀死甚至用户杀死应用程序。然后我编写了一个代码,它运行完美,但唯一的问题是当我通过单击应用程序中的按钮启动服务时,即使用户在前台,通知也会立即显示,并且只有在我停止服务时才会发出通知。
我希望仅当用户转到后台而不是前台时才显示此通知。我分享我的代码,请帮助我解决这个问题。
这是服务类:

public class LocationUpdateService extends Service {

private Handler handler;
private Runnable test;

// Constants
private static final int ID_SERVICE = 101;

@Override
public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(false)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
    }
}

@RequiresApi(Build.VERSION_CODES.O)
private String createNotificationChannel(NotificationManager notificationManager){
    String channelId = "my_service_channelid";
    String channelName = "My Foreground Service";
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    // omitted the LED color
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handler = new Handler();
    test = new Runnable() {
        @Override
        public void run() {
            /* GET LOCATION UPDATES */
            Log.i("testApp", "Running...");
            /* GET LOCATION UPDATES */
            handler.postDelayed(test, 2000);
        }
    };
    handler.postDelayed(test, 0);
   
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    handler.removeCallbacks(test);
}

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

}

从一个活动我开始这样的服务:

 Intent intent = new Intent(HomeActivity.this, LocationUpdateService.class);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        startForegroundService(intent);
                    } else {
                        startService(intent);
                    }

对于停止服务,我使用此行:

stopService(new Intent(this, LocationUpdateService.class));

标签: androidandroid-servicebackground-process

解决方案


推荐阅读