gpt4 book ai didi

java - 来自 JSON 的通知服务

转载 作者:太空宇宙 更新时间:2023-11-04 11:54:00 35 4
gpt4 key购买 nike

如何发出通知?如何查看新闻日期并有新闻时显示通知?服务可以从 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;
}
}

最佳答案

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

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

因此,您可以尝试在 AsyncTask 中添加公共(public)属性,如下所示。

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 中,您需要检查 boolean 值并相应地创建通知。

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

更新

来自评论

Maybe somehow it is necessary to check the date of the publication of news, verify it with the current date and display a notice .. So you need to show the notice only when there is news

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

关于java - 来自 JSON 的通知服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522953/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com