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?