JSON的通知服务

时间:2017-01-07 15:18:11

标签: java android json service notifications

如何发出通知? 有新闻时如何查看新闻日期并显示通知? 服务是否可以从[ { "keys": ["ctrl+6"], "command": "next_view" }, { "keys": ["ctrl+4"], "command": "prev_view" } ] 获取SharedPref,然后检查然后发出通知或不通知?

Fragment代码:

TabFragment1.class

通知服务代码:

@Override
protected void onPostExecute(StringBuilder stringBuilder) {

    try {
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());
        JSONArray array = jsonObject.getJSONArray("articles");
        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            String title = object.getString("title");
            String desc = object.getString("description");
            String imageUrl = object.getString("urlToImage");
            String articleUrl = object.getString("url");
            String newsdata = object.getString("publishedAt");

            sPref = getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
            SharedPreferences.Editor ed = sPref.edit();
            ed.putString(SAVED_TEXT, newsdata);
            ed.commit();
            Toast.makeText(getActivity(), "Text saved", Toast.LENGTH_SHORT).show();
            News news = new News(title, desc, imageUrl, articleUrl);
            myAdapter.addNews(news);

            myAdapter.notifyDataSetChanged();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

Service可以阅读SharedPreference并可以发出通知。

如果我理解正确,您需要在onPostExecute课程的MyAsynk函数中创建通知。

因此,您可以尝试在此AsyncTask中添加公共属性。

class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {

    public boolean showNotification;

    // .. Other functions
}

现在在UpdateTimerTask

if(datanews != checker){
    asynk = new MyAsynk();
    asynk.showNotification = true;
    asynk.execute();
} else {
    asynk = new MyAsynk();
    asynk.showNotification = false;
    asynk.execute();
}

现在在onPostExecute类的MyAsynk中,您需要检查布尔值并相应地创建通知。

@Override
protected void onPostExecute(StringBuilder stringBuilder) {
    try {
        JSONObject jsonObject = new JSONObject(stringBuilder.toString());
        JSONArray array = jsonObject.getJSONArray("articles");
        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            String title = object.getString("title");
            String desc = object.getString("description");
            String newsdata = object.getString("publishedAt");
            datanews = newsdata;
            titlenotif = title;
            destnotif = desc;
        }

        // Create notification here on demand
        if(showNotification) createNotification(getApplicationContext);
    }
    catch (Exception e){e.printStackTrace();}
}

<强>更新

来自评论

  

也许某种程度上有必要检查出版日期   新闻,用当前日期验证并显示通知..所以你   只有在有新闻时才需要出示通知

如果您计划仅从客户端跟踪新消息,则可能需要进行大量编码,包括保留本地存储空间并每次检查新消息是否到达。我想你需要在服务器端实现。当收到新消息时,会向您发送推送通知。服务器应该处理同步和其他机制。