• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Android app stop after running in background by using foreground service?

In my app I have used foreground service for getting location it works fine for some interval. When the app is in the background, then location not received and the app gets killed without showing any error log. App works fine in some devices.here is my code Start service from Activiy :

startServiceIntent = new Intent(this, MyLocationService.class);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

ContextCompat.startForegroundService(this, startServiceIntent);
} else {

startService(startServiceIntent);
}

MyLocationService:
override
public int onStartCommand(Intent intent, int flags, int startId) {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID,"Channel",NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(serviceChannel);

Intent notificationIntent = new Intent(this, HomeActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("My App")
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();

startForeground(1, notification);
}
return START_NOT_STICKY;
}
 
Last edited by a moderator:

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones