I have a little bit issue for implement service. I make a service to run even when app is in background and even when user proper kill app. I search on internet and see by start service "foreground", service not kill even user kill the app. Then I write a code and it work perfect but the only issue is when I start service by click a button in app the notification immediately show even user is in foreground and that notification only go when I stop service.
I want this notification show only when user go to background not in foreground. I share my code, please help me to solve this issue.
Here is the service class:
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;
}
}
And from an activity I start service like this:
Intent intent = new Intent(HomeActivity.this, LocationUpdateService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
For stop service I use this line:
stopService(new Intent(this, LocationUpdateService.class));