Android简易实战教程--第三十七话《NotifiCation》

来源:互联网 发布:安卓收费软件 编辑:程序博客网 时间:2024/05/17 08:54

通知的使用,无疑是Android系统的亮点之一;就连IOS在5.0开始也引入了类似通知的技巧。可见它的实用性。

今天这个小案例,就学习一下通知的基本使用,API是使用最新的API,4.3以前创建通知的API已经过时。

首先定义个布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <Button        android:id="@+id/show"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginLeft="22dp"        android:text="开启通知" />    <Button        android:id="@+id/cancel"        android:layout_marginLeft="22dp"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="关闭通知" /></LinearLayout>

布局很简单,一个按钮用于开启通知,一个用于关闭通知。

接着就是通知的业务:

package com.example.notification;import android.app.Activity;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.support.v4.app.NotificationCompat;import android.support.v4.app.NotificationCompat.Builder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Button btShow;private Button btCancel;private NotificationManager manager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btShow = (Button) findViewById(R.id.show);btCancel = (Button) findViewById(R.id.cancel);/**获取通知对象*/manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);btShow.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 展示通知showNotificationNewAPI();}});btCancel.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 关闭通知cancelNotification();}});}/**新API展示通知*/public void showNotificationNewAPI(){NotificationCompat.Builder builder = new Builder(getApplicationContext());//真正的意图Intent intent = new Intent(this, DemoActivity.class);//延迟意图,用于启动活动、服务、发送广播等。携带真正的意图对象PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);builder.setSmallIcon(R.drawable.notification_music_playing)//设置通知显示的图标.setTicker("ticker")//设置通知刚刚展示时候瞬间展示的通知信息.setWhen(System.currentTimeMillis())//设置通知何时出现,System.currentTimeMillis()表示当前时间显示/**以上三种方式必须设置,少一项都不会展示通知*/.setOngoing(true)//设置滑动通知不可删除.setContentTitle("这是通知标题").setContentText("我是通知的内容").setContentIntent(pendingIntent);//开启通知,第一个参数类似代表该通知的id,标记为1manager.notify(1, builder.build());}/**取消通知*/public void cancelNotification(){//1表示我要取消标记的通知manager.cancel(1);}}

值得一提的就是showNotificationNewAPI()里面创建通知的方式。

对于详细的解释,已经在代码中注明了,相信1分钟搞定~

好啦,运行看看创建的通知的样子吧:

这样的通知还是平凡的一笔,下一篇小案例就针对通知在实际开发中使用,完成自定义的通知,让我们的通知布局“靓起来”。

欢迎关注本博客,不定义更新简单有趣的小文章哦~

1 0