0

Here is the current code for NotificationService.class:

package com.mypack.appname;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.webkit.WebView;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class NotificationService extends Service {

Timer timer;
TimerTask timerTask;
String TAG = "Timers";
int Your_X_SECS = 5;


@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e(TAG, "onStartCommand");
    super.onStartCommand(intent, flags, startId);

    startTimer();

    return START_STICKY;
}


@Override
public void onCreate() {
    Log.e(TAG, "onCreate");


}

@Override
public void onDestroy() {
    Log.e(TAG, "onDestroy");
    stoptimertask();
    super.onDestroy();


}

//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
public android.content.Context ant;

public void startTimer() {
    //set a new Timer
    timer = new Timer();
    ant = this;

    //initialize the TimerTask's job
    timerTask = new TimerTask() {
        public void run() {

            //use a handler to run a toast that shows the current timestamp
            handler.post(new Runnable() {
                public void run() {

                    //TODO CALL NOTIFICATION FUNC

                    new GetUrlContentTask().execute("some url here");
                }
            });
        }
    };

    //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
    timer.schedule(timerTask, 5000, Your_X_SECS * 1000); //
    //timer.schedule(timerTask, 5000,1000); //
}

public void stoptimertask() {
    //stop the timer, if it's not already null
    if (timer != null) {
        timer.cancel();
        timer = null;
    }
}

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String content = "", line;
            while ((line = rd.readLine()) != null) {
                content += line + "\n";
            }

            if(Objects.equals(content,"{\"nocomments\":true"))
                return content;

            JSONObject o = new JSONObject(content);
            String m_id = o.getString("id");
            JSONArray a = o.getJSONArray("comments");
            int le = a.length();

            SharedPreferences settings = getApplicationContext().getSharedPreferences("prefnameaga", 0);
            int lele = settings.getInt(m_id, 0);

            if(lele != le)
            {
                SharedPreferences.Editor editor = settings.edit();
                editor.putInt(m_id, le);
                editor.apply();

                JSONObject la = a.getJSONObject(le-1);
                String data = la.getString("data");

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

                NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "IMACHANNE");
                builder.setSmallIcon(R.drawable.ic_launcher_foreground);
                builder.setContentTitle("New comment for the post");
                builder.setContentText(data);
                builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
                builder.setAutoCancel(true);
                builder.setContentIntent(pendingIntent);

                NotificationManagerCompat ntf = NotificationManagerCompat.from(getApplicationContext());
                ntf.notify(1, builder.build());
            }



  
            return content;
        }
        catch(Exception ex)
        {
            return "error";
        }
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
        // displayMessage(result);

    }
}

}

Earlier, in void Run() there was code for showing "hello world" notification only. In MainActivity I wrote to start the service when onStop() is called. Notification has been arriving when the user switched to antoher app (not closing current), but when user closed the app, notificaion didn't come. I fixed that adding android:stopWithTask="false" to service in manifest.

Now I added some new features, and the code is as You see it above. For some reason, now I am facing that issue again: when the app is switched notification is showed absolutely correctly: http request is made succusesfully, all is good. But when the app is closed - nothing is happening.

What mistake did I do, and how to fix it?

1 Answers1

0

This answer helped me to solve my problem (yet I still don’t know why it worked earlier) with some modification: in my notification service class I removed all from onCreate and in onDestroy I removed part for service restarting, because I need to service run only when the app is closed or killed.

  • There might be two reason 1. You were using a device which is lower than VERSION_CODES.O And, 2. Maybe, in new updates of android-studio lot of things were deprecated(not workable on every device). –  Mar 05 '21 at 12:05
  • 1
    @Istiak, unfortunately I test on the same device with Android 8.1, and seems my Android Studio haven’t been updated too – Thawbkisavv Mar 05 '21 at 13:27