@Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this,"Start Service",Toast.LENGTH_SHORT).show(); Intent notificationIntent = new Intent(this, MainActivity.class); notificationIntent.setAction(MainActivity.MAIN_ACTION); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); RemoteViews notificationView = new RemoteViews(this.getPackageName(),R.layout.notification); Intent buttonCloseIntent = new Intent(this, NotificationCloseButtonHandler.class); buttonCloseIntent.putExtra("action", "close"); PendingIntent buttonClosePendingIntent = pendingIntent.getBroadcast(this, 0, buttonCloseIntent, 0); notificationView.setOnClickPendingIntent(R.id.notification_button_close, buttonClosePendingIntent); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); Notification notification = new NotificationCompat.Builder(this) .setContentTitle("Test") .setTicker("Test") .setContentText("Test") .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon( Bitmap.createScaledBitmap(icon, 128, 128, false)) .setContent(notificationView) .setOngoing(true).build(); startForeground(101, notification); return START_STICKY; }
References
https://questdot.com/android-foreground-service/
https://stackoverflow.com/questions/24479860/foreground-service-to-prevent-process-kill