I am working an android project. I want to send a notification to users when users are in app or killed the app. So, I use service and broadcastreceiver classes.
When I try to send a notification, it succeeds in both (App is running or killed). But when I reopen the app after getting it killed, the app crashes (Android 8.1 and later versions). I get this error:
"Context.startForegroundService() did not then call Service.startForeground()"
I added permission for FOREGROUND_SERVICE in AndroidManifest. As a result of my research, I tried many ways but I could not reach a solution. I follow this solutions but doesn't work. I'd appreciate it if you could show me what I can do. You can find my classes below.
My Base Class:
Intent GoService;
private PushService mPushService;
Context context;
public Context getCtx() {
return context ;
}
…
context = this;
mPushService = new PushService(getCtx());
GoService = new Intent(getCtx(),mPushService.getClass());
if (!isServiceRunning (mPushService.getClass())) {
startService(GoService);
}
…
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isServiceRunning?", true+"");
return true;
}
}
Log.i ("isServiceRunning?", false+"");
return false;
}
@Override
protected void onDestroy() {
stopService(GoService);
Log.i("MAINACT", "onDestroy!");
super.onDestroy();
}
My Service Class:
public class PushService extends Service {
public NotificationCompat.Builder builder;
private RequestQueue mQueue;
final Handler handler = new Handler();
public PushService (Context applicationContext) {
super();
Log.i("Service", "Here!");
}
public PushService () {
}
@Override
public void onCreate() {
super.onCreate();
handler.postDelayed(new Runnable() {
public void run() {
JSONParse();
handler.postDelayed(this, 5000);
}
}, 0);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}}}
My Receiver Class:
public class PushServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, PushService.class));
} else {
context.startService(new Intent(context, PushService.class));
}
}