我从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);
}
}
答案 0 :(得分:1)
在api成功内调用您的通知代码,看看
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pushnotifications);
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);
showNotification(notiftext)
} catch (Exception e) {
e.printStackTrace();
Log.d("log","PUSH CATCG"+e);
}
}
这是在成功调用api后显示通知的方法。
public void showNotification(String message){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background) // notification icon
.setContentTitle("Notification!") // title for notification
.setContentText(message); // message for notification
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager.notify().
mNotificationManager.notify(001, mBuilder.build());
}
希望它将对您有帮助!