Android Notification通知简单使用DEMO

今天学习了一下Notification的简单使用方法,在这里记录一下完整的例子,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package home.xiao.pustapp;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

private static int messageNum = 0;
NotificationManager notificationManager;
Notification notification;
private Bitmap icon;
int ID = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}

private void init() {
// 获取通知服务
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 注册监听器
findViewById(R.id.btnSend).setOnClickListener(listener);

icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
}

private void showNotify() {
notification = new NotificationCompat.Builder(MainActivity.this)
.setLargeIcon(icon)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("发现新的订单")//setTicker("设置消息提示时在状态栏显示的信息")
.setContentTitle("发现新的订单")//setContentTitle("设置消息标题")
.setContentText("内容")//setContentText("设置消息内容")
.setNumber(++messageNum)
.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
.build();
notificationManager.notify(ID, notification);
}

View.OnClickListener listener = new View.OnClickListener() {//创建监听对象
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSend:
showNotify();
break;
default:
break;
}
}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}