本文主要是介绍【总结】Android攻城狮之Notification,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Android攻城狮之Notification
目录
- Android攻城狮之Notification
- Notification简介
- 获取NotificationMananger
- AlertDialog实例
Notification简介
Notification是显示在手机状态栏的消息(手机状态栏位于手机最顶端),代表一种全局效果的通知。
获取NotificationMananger
显示通知栏: notify(id,notification);
取消通知栏: cancle(id);
构造Notification并设置显示内容
通知栏通知可以设置声音提示,指示灯,以及震动效果。
AlertDialog实例
public class MainActivity extends Activity implements DialogInterface.OnClickListener{NotificationManager manager;int notification_ID;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);findViewById(R.id.btn_send).setOnClickListener(this);findViewById(R.id.btn_cancle).setOnClickListener(this);}@Overrideprivate void OnClick(View view){switch (view.getId()){case R.id.btn_send:sendNotification();break;case R.id.btn_cancle:manager.cancel(notification_ID);break;}/*** 构造notification并发送到通知栏*/private void sendNotification(){Intent intent = new Intent(this, MainActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,0);Notification.Builder builder = new Notification.Builder(this);builder.setSmallIcon(R.drawable.ic_launcher);//设置图标builder.setTicker("Hello");//手机状态栏的提示builder.setWhen(System.currentTimeMillis());//设置时间builder.setContentTitle("通知栏通知");//设置标题builder.setContentText("我来自NotificationDemo");//设置内容builder.setContentIntent(pendingIntent);//点击后的意图builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示音builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置提示灯builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动
// builder.setDefaults(Notification.DEFAULT_ALL);//等同于上面三行代码Notification notification = builder.build();//需要API level 16
// builder.getNotification();//API level低于16时使用manager.notify(notification_ID, notification);}
同时要进行权限的设置,在AndroidManifest.xml
文件中添加以下权限
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE" />
最后效果如下:
这篇关于【总结】Android攻城狮之Notification的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!