如何製作通知服務,通知用戶有關新消息的一些信息?來自JSON的Android通知服務
我從JSON
API(https://newsapi.org/)向我的應用程序收到消息,並希望如果有任何他沒有看到的新故事可以顯示用戶通知。
如何製作通知服務,通知用戶有關新消息的一些信息?來自JSON的Android通知服務
我從JSON
API(https://newsapi.org/)向我的應用程序收到消息,並希望如果有任何他沒有看到的新故事可以顯示用戶通知。
是很容易使用火力services.Follow這裏我腳步的Android創建推送通知:
String token = FirebaseInstanceId.getInstance().getToken();
。看我的代碼 那公測.. `公共類通知服務擴展{ 字符串datanews; String titlenotif; String destnotif; MyAsynk asynk;
@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() {
asynk = new MyAsynk();
asynk.execute();
createNotification(getApplicationContext());//пушим уведомление
}
}
class MyAsynk extends AsyncTask<Void,Void,StringBuilder> {
@Override
//работа в бекграунде
protected StringBuilder doInBackground(Void... voids) {
StringBuilder stringBuilder = new StringBuilder();
String key = "YOUR_KEY";
try {
URL url = new URL("YOUR_URL_HERE" + 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) {
}
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){
}
}
}
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;
}
}`
具有u在android系統(GCM或FCM) –
@ShanmugapriyaD檢查推送通知的概念,是對的。你應該用廣播接收器一起使用GCM或FCM的推送通知。 – Radhey