结合官方文档:
https://developer.android.com/index.html
https://developer.android.com/reference/android/app/NotificationManager.html
https://developer.android.com/reference/android/app/Notification.html
调用需要2个最基本的元素
1、NotificationManager:是状态栏通知管理类,负责发送和清除通知
2、Notification:具体的状态栏通知对象,设置内容包含标题、文字、图片等
使用场景:用户成功登录之后,通知栏提示消息
需要改造的代码:
/**
* 发送网络请求不能在主线程,需要新开一个线程
*/
Runnable requestAPI = new Runnable() {
@Override
public void run() {
Form form = new Form().add("user_name",login_username.getText().toString())
.add("user_pass",login_pwd.getText().toString());
try {
Request request = Bridge.post("http://192.168.15.138/user.php").body(form).request();
Response response = request.response();
if (response.isSuccess()){
// 服务器响应的数据转json
JSONObject jsonObject = response.asJsonObject();
Looper.prepare(); //创建消息队列
// 对话框
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("登录结果");
builder.setMessage(jsonObject.get("message").toString());
builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss(); // 关闭对话框
}
});
// 如果登录成功
if (jsonObject.get("status").toString().equals("success")){
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notice = new NotificationCompat.Builder(LoginActivity.this);
notice.setTicker("欢迎回来");
notice.setContentTitle("今日登录奖励");
notice.setContentText("5积分,更多请点击");
notice.setDefaults(Notification.DEFAULT_SOUND); //声音
//notice.setSmallIcon() //设置小图标
//notice.setLargeIcon() //设置大图标
notice.setNumber(3);
notificationManager.notify(123,notice.build());
}else{
builder.show(); // 不要忘记最后展示对话框
}
Looper.loop(); //进入消息循环
}else{
// http请求失败
}
} catch (BridgeException e) {
e.printStackTrace();
}catch (JSONException e) {
e.printStackTrace();
}
}
};