Skip to content
Advertisement

Android Foreground service without notification – how to?

I have created foreground service for notifications in my application. It’s working fine, the problem is to start the foreground service we need foreground notification which tell that your application is running like this. I don’t want this notification. How I can remove that notification without killing the service.

This is how I’m starting the foreground service.

@Override
public void onCreate() {
    super.onCreate();
    stopForeground(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(serviceChannel);
    }
    Intent stopSelf = new Intent(this, Notification_Service.class);
    stopSelf.setAction("ACTION_STOP_SERVICE");
    PendingIntent pStopSelf = PendingIntent
            .getService(this, 0, stopSelf
                    , PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    NotificationCompat.Action action =
            new NotificationCompat.Action.Builder(
                    0, "Close", pStopSelf
            ).build();
    Notification notification = notificationBuilder
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle("Ask Question")
            .setContentText("Ask Question is running")
            .addAction(action)
            .setPriority(Notification.PRIORITY_MIN)
            .build();
    notificationManager.notify(1, notification);
    startForeground(1, notification);
    notificationManager.cancel(1);
    SharedPreferences settings = getSharedPreferences("Session", MODE_PRIVATE);
    id = settings.getString("id", null);
    apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
    handler.postDelayed(new Runnable() {
        public void run() {
            startMyOwnForeground();
            handler.postDelayed(this, delay);
        }
    }, delay);
}

private void startMyOwnForeground() {
    Log.e("", "service running");
    get_notification();
}

Retrofit call to get notification:

  private void get_notification() {
        Call<ArrayList> call = apiInterface.getnotification(ApiClient.pin, id);
        call.enqueue(new Callback<ArrayList>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call<ArrayList> call, Response<ArrayList> response) {
                if (response.body() != null) {
                    for (int i = 0; i < response.body().size(); i = i + 1) {
                        ArrayList<String> getdata = (ArrayList<String>) response.body().get(i);
                        String[] data = getdata.toArray(new String[0]);
                        if (data[5].equals("0")) {
                            switch (data[4]) {
                                case "comment":
                                    send_comment_notification(data[1], data[2], data[3], data[0]);
                                    break;
                                case "question":
                                    send_question_notification(data[3], data[0], data[1]);
                                    break;
                                case "answer":
                                    send_answer_notification(data[3], data[0], data[1]);
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrayList> call, Throwable t) {

            }
        });
    }

Answer

Here is the implementation of Karsten Planz

You should either use the WorkManager API to implement a background sync mechanism. Then you can use the NotificationBuilder to create a “local” notifiction.

Start the Task in your main activity by this:

  WorkRequest uploadWorkRequest =
                new OneTimeWorkRequest.Builder(NotificationWorker.class)
                        .build();
        WorkManager
                .getInstance(MainActivity.this)
                .enqueue(uploadWorkRequest);

Now Create a class NotificationWorker and extends Worker. Place your startMyOwnForeground in doWork by returning Result.retry(), this will make a recursive function.

public class NotificationWorker extends Worker {

    Context  context;
  
    public NotificationWorker(
            @NonNull Context context,
            @NonNull WorkerParameters params) {
        super(context, params);
        this.context=context;
    }

    @Override
    public Result doWork() {
        startMyOwnForeground();
        return Result.retry();
    }
    private void startMyOwnForeground() {
        Log.e("", "service running");
        get_notification();
    }

    private void get_notification() {
        Call<ArrayList> call = apiInterface.getnotification(ApiClient.pin, id);
        call.enqueue(new Callback<ArrayList>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call<ArrayList> call, Response<ArrayList> response) {
                if (response.body() != null) {
                    for (int i = 0; i < response.body().size(); i = i + 1) {
                        ArrayList<String> getdata = (ArrayList<String>) response.body().get(i);
                        String[] data = getdata.toArray(new String[0]);
                        if (data[5].equals("0")) {
                            switch (data[4]) {
                                case "comment":
                                    send_comment_notification(data[1], data[2], data[3], data[0]);
                                    break;
                                case "question":
                                    send_question_notification(data[3], data[0], data[1]);
                                    break;
                                case "answer":
                                    send_answer_notification(data[3], data[0], data[1]);
                                    break;
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrayList> call, Throwable t) {

            }
        });
    }
}
Advertisement