2017-07-25 86 views
1

我正在創建一個應用程序,該應用程序在wordpress網站發佈新帖子後立即顯示通知。從android服務創建實時通知

現在,我在wordpress網站上發佈帖子後立即生成通知。

但40-45分鐘後應用進行了墜毀,並與下面的錯誤後臺就會被殺死 -

the error that showed after the app crashes

我已經嘗試了許多解決方案都沒有它的工作。
我不想使用firebase進行通知。

我必須從wordpress實時獲取數據,然後創建通知。

這是用於產生通知以下代碼: -

私人無效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(); 
} 
+1

好像你在後臺創建多個線程來獲取新的崗位這麼多對象的OutOfMemoryError可能發生!由於內存不足,會發生此錯誤!你在什麼時間間隔檢查新帖子? –

+0

這是我正在寫的代碼 – aditya1508

+0

發佈您的當前代碼! –

回答

1

您從計時器創建請求隊列,所以每5秒。在您執行的代碼中,您始終創建一個新的請求隊列。這不起作用,你應該保持requestQueue作爲最終的全局變量,並在你的構造函數中只創建一次。

public class NotifierService extends Service { 
    private final RequestQueue rQueue; 

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

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

,因爲你是製造一種不正確的垃圾回收

+0

中使用了報警管理器,所以在這裏我只需要將請求添加到隊列中! rQueue = Volley.newRequestQueue(NotifierService.this);這行只能寫一次。對? – aditya1508

+0

它給出一個空指針異常無法實例化服務.NotifierService:java.lang.NullPointerException:試圖調用虛擬方法'java.io.File android.content.Context.getCacheDir()'對一個空對象引用 – aditya1508