首页 > 代码库 > Android攻城狮Notification实现状态通知栏

Android攻城狮Notification实现状态通知栏

通知栏的实现
需要在配置文件中添加权限:
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE" />

 1 public class MainActivity extends ActionBarActivity implements OnClickListener {
 2     NotificationManager manager;
 3     int notification_ID;
 4 
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.fragment_main);
 9         manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
10         findViewById(R.id.butsend).setOnClickListener(this);
11         findViewById(R.id.butcancel).setOnClickListener(this);
12 
13     }
14 
15     @Override
16     public void onClick(View v) {
17         // TODO Auto-generated method stub
18         switch (v.getId()) {
19         case R.id.butsend:
20             sendNotification();
21             break;
22 
23         case R.id.butcancel:
24             manager.cancel(notification_ID);
25             break;
26 
27         }
28     }
29 
30     // 构造Notification并发送到通知栏
31     private void sendNotification() {
32         Intent intent = new Intent(this, MainActivity.class);
33         PendingIntent pintent = PendingIntent.getActivity(this, 0, intent, 0);
34         Builder builder = new Notification.Builder(this);
35         builder.setSmallIcon(R.drawable.ic_launcher);// 设置图标
36         builder.setTicker("hello");// 手机状态栏的提示
37         builder.setWhen(System.currentTimeMillis());// 设置时间
38         builder.setContentTitle("通知栏通知");// 设置标题
39         builder.setContentText("我来自,,Notification");// 设置通知内容
40         builder.setContentIntent(pintent);// 点击后的意图
41         // builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示声音
42         // builder.setDefaults(Notification.DEFAULT_LIGHTS);//指示灯 需要权限
43         // builder.setDefaults(Notification.DEFAULT_VIBRATE);//震动效果 需要权限
44         builder.setDefaults(Notification.DEFAULT_ALL);// 设置三种所有
45         Notification notification = builder.build();// 4.1以上 包括4.1
46 
47         manager.notify(notification_ID, notification);
48         // builder.getNotification();//4.1以下
49 
50     }
51 }

 

Android攻城狮Notification实现状态通知栏