【发布时间】:2019-01-07 09:13:48
【问题描述】:
我从我的 Api 获得了一个文本,我想将其显示为通知。我该怎么做?这是我拥有通知代码和获取 json 对象的代码的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pushnotifications);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText("Hello word"); // message for notification
Notification mNotificationManager = mBuilder.build();
NotificationManagerCompat.from(this).notify(0,mNotificationManager);
URL obj = null;
try {
obj = new URL("https://gekon.technologypark.cz/api/v1/notification/demo/8");
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ApiSecret", LoginInfo.ApiSecret);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null)
sb.append(output);
JSONObject jsonObj = new JSONObject(sb.toString());
String notifText=(String) jsonObj.get("data");
Log.d("log","PUSH NANI"+notifText);
} catch (Exception e) {
e.printStackTrace();
Log.d("log","PUSH CATCG"+e);
}
}
【问题讨论】:
-
如果你在android 8及以上的设备上测试你需要配置通知通道。
-
@KaranMer 我知道,但我正在 android 7 上测试它
-
您需要在
notify()中使用随机 id,因为使用重复的 id 会覆盖您的通知
标签: android json api notifications