neo73
neo73

Reputation: 464

Creating a real time notification from android service

I am creating an application which shows the notification as soon as I post a new post on wordpress site.

Now the notification is generated as soon as I put a post on the wordpress site.

But after 40-45 minutes the app gets crashed and gets killed in the background with the following error:-

the error that showed after the app crashes

I have tried many solutions none of it worked.
I don't want to use firebase for the notification.

I have to fetch the data in real time from the wordpress and then create the notification.

This is the following code for generating the notification:-

private void setupNotificationListener(){

    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            flag=1;
            //System.out.println(flag);
            gson = new Gson();
            list = (List) gson.fromJson(s, List.class);
            postTitle = new String[list.size()];
            postContent=new String[list.size()];

            System.out.println("shiv class:"+list.size());
            for(int i=0;i<list.size();++i) {
                mapPost = (Map<String, Object>) list.get(i);
                mapTitle = (Map<String, Object>) mapPost.get("title");
                postTitle[i] = (String) mapTitle.get("rendered");
                mapContent = (Map<String, Object>) mapPost.get("content");
                postContent[i] = (String) mapContent.get("rendered");
            }
            if(!alreadyNotified(postTitle[0])){
                Log.d("not notified","");
                createNotif(postContent[0],postTitle[0]);
                saveNotificationKey(postTitle[0]);
            }else{
                System.out.print("already notified");
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Log.d("Error","Error");
        }
    });

    rQueue = Volley.newRequestQueue(NotifierService.this);
    rQueue.add(request);
    NotifierService.getInstance().getRequestQueue().getCache().clear();
}

Upvotes: 1

Views: 676

Answers (1)

luckyhandler
luckyhandler

Reputation: 11329

You create the requestQueue from a timer, so every 5 seconds. And within your executed code you create always a new request queue. This won't work you should keep the requestQueue as final global variable and create it only once in your constructor.

public class NotifierService extends Service {
    private final RequestQueue rQueue;

    NotifierService() {
        this.rQueue = Volley.newRequestQueue(this);
    }

    private void setupNotificationListener() {
        // do your request handling
    }
}

The OutOfMemoryError might occur because you create so many objects which are not correctly garbage collected

Upvotes: 1

Related Questions