【问题标题】:Notification Service from JSON来自 JSON 的通知服务
【发布时间】:2017-01-07 15:18:11
【问题描述】:

如何通知? 如何查看新闻的日期并在有新闻时显示通知? 服务是否可以从Fragment 获取 SharedPref 并检查然后发出通知?

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();
    }
}

通知服务代码:

public class Notification extends Service {
    String datanews;
    String titlenotif;
    String destnotif;
    MyAsynk asynk;
    final String SAVED_TEXT = "saved_text";
    String checker;
    SharedPreferences sPref;

    @Override
    public void onCreate() {
        super.onCreate();
        Timer timer = new Timer();
        timer.schedule(new UpdateTimeTask(), 0, 1800000); //тикаем каждые 30 мinute без задержки 1800000
    }

    class UpdateTimeTask extends TimerTask {
        public void run() {
            sPref = getSharedPreferences("MyPref",MODE_PRIVATE);
            String savedText = sPref.getString(SAVED_TEXT, "");
            checker = sPref.getString(savedText, "0");

            if(datanews != checker){
                asynk = new MyAsynk();
                asynk.execute();
                createNotification(getApplicationContext());//пушим уведомление
            } else {
                asynk = new MyAsynk();
                asynk.execute();
            }
        }
    }

    class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
        @Override
        protected StringBuilder doInBackground(Void... voids) {
            StringBuilder stringBuilder = new StringBuilder();
            String key = "0aa2713d5a1a4aad9a914c9294f6a22b";
            try {
                URL url = new URL("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=" + key);
                URLConnection uc = url.openConnection();
                uc.connect();
                BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
                int ch;
                while ((ch = in.read()) != -1) {
                    stringBuilder.append((char) ch);
                }
            } catch (Exception e) {e.printStackTrace();}

            return stringBuilder;
        }

        @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;
                }
            }
            catch (Exception e){e.printStackTrace();}
        }
    }

    private void createNotification(Context context) {
        NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder ncBuilder = new NotificationCompat.Builder(context);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
        ncBuilder.setVibrate(new long[]{500});
        ncBuilder.setLights(Color.WHITE, 3000, 3000);
        ncBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        ncBuilder.setContentIntent(pIntent);
        ncBuilder.setContentTitle(titlenotif + "");
        ncBuilder.setContentText(destnotif + "");
        ncBuilder.setTicker("You have news!");
        ncBuilder.setSmallIcon(R.drawable.news_icon);
        ncBuilder.setAutoCancel(true);
        manager.notify((int)System.currentTimeMillis(),ncBuilder.build());
    }
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

【问题讨论】:

    标签: java android json service notifications


    【解决方案1】:

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

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

    因此,您可以尝试像这样在 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();
    }
    

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

    @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();}
    }
    

    更新

    来自评论

    也许有必要检查出版日期 新闻,用当前日期验证它并显示通知..所以你 有新闻时才需要显示通知

    如果您打算仅从客户端跟踪新消息,则可能需要进行大量编码,包括保留本地存储以及每次是否有新消息到达时检查。我猜你需要在这里有一个服务器端实现。当收到新消息时,它将向您发送推送通知。服务器应处理同步和其他机制。

    【讨论】:

    • 它会显示一个通知,但不会停止我只想在有新闻时通知用户..
    • 也许有必要检查新闻发布的日期,与当前日期验证并显示通知..所以只有在有新闻时才需要显示通知
    • 请查看更新后的答案,如果答案有帮助,请点赞。
    • oh thx.. 我无法通过使用计时器来按我的意愿发出通知,该计时器将检查新闻日期并在日期更改时发出通知
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多