• 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:
Back
Top Bottom