从 android 服务创建实时通知 [英] Creating a real time notification from android service
问题描述
我正在创建一个应用程序,它会在我在 wordpress 网站上发布新帖子时立即显示通知.
I am creating an application which shows the notification as soon as I post a new post on wordpress site.
现在,只要我在 wordpress 网站上发帖,就会生成通知.
Now the notification is generated as soon as I put a post on the wordpress site.
但在 40-45 分钟后,应用程序崩溃并在后台被杀死,并出现以下错误:-
But after 40-45 minutes the app gets crashed and gets killed in the background with the following error:-
我尝试了很多解决方案都没有奏效.
我不想将 firebase
用于通知.
I have tried many solutions none of it worked.
I don't want to use firebase
for the notification.
我必须从 wordpress 实时获取数据,然后创建通知.
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(){
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();
}
推荐答案
您从计时器创建 requestQueue,因此每 5 秒一次.在您执行的代码中,您始终会创建一个新的请求队列.这行不通,您应该将 requestQueue 作为最终全局变量并在构造函数中仅创建一次.
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
}
}
OutOfMemoryError 可能是因为你创建了太多没有被正确垃圾回收的对象
The OutOfMemoryError might occur because you create so many objects which are not correctly garbage collected
这篇关于从 android 服务创建实时通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!