NotificationManager顾名思义,通知管理器,就是用来发通知的,打开手机可以看到最上层有一个状态条,那里可以显示信号强弱,电量,时间,还可以显示通知等等,比如说来电通知,短信通知,向下一拉,点击某条通知,就可以进入相应的应用了,比如短信,一点击某条短信通知,就进入短信阅读页面了。今天我们就来学习,如何发送通知。
理论:
public class
NotificationManager

extends Object
java.lang.Object
   ↳
android.app.NotificationManager
Class Overview

Class to notify the user of events that happen. This is how you tell the user that something has happened in the background.

Notifications can take different forms:

·         A persistent icon that goes in the status bar and is accessible through the launcher, (when the user selects it, a designated Intent can be launched),
·         Turning on or flashing LEDs on the device, or
·         Alerting the user by flashing the backlight, playing a sound, or vibrating.
Each of the notify methods takes an int id parameter and optionally a String tag parameter, which may be null. These parameters are used to form a pair (tag, id), or (null, id) if tag is unspecified. This pair identifies this notification from your app to the system, so that pair should be unique within your app. If you call one of the notify methods with a (tag, id) pair that is currently active and a new set of notification parameters, it will be updated. For example, if you pass a new status bar icon, the old icon in the status bar will be replaced with the new one. This is also the same tag and id you pass to the cancel(int) or cancel(String, int) method to clear this notification.

You do not instantiate this class directly; instead, retrieve it through getSystemService(String).

实践:

第一步、设计页面

通知页面:\res\layout\notification.xml

<?xml version="1.0" encoding="utf-8"?> 
 <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
  
    <Button android:id="@+id/btnSendNotification" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="52dp" android:text="@string/sendNotification"></Button>
 </RelativeLayout>

自定义通知格式:\res\layout\notificationview.xml

<?xml version="1.0" encoding="utf-8"?> 
 <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
     <ImageView android:layout_height="wrap_content" android:id="@+id/imgNotification" android:layout_width="wrap_content" android:src="@drawable/heart" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></ImageView>
     <TextView android:layout_height="wrap_content" android:id="@+id/tvNotification" android:text="TextView" android:layout_width="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/imgNotification"></TextView>
  </RelativeLayout>

 

第二步、设计Acitivity NotificationManagerActivity.java

/**
  *
  */
 package Test.HelloWorld;
  
 import android.app.Activity;
 import android.app.Notification;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.RemoteViews;
  
 /**
  * @author zhuzhifei
  *
  */
 public class NotificationManagerActivity extends Activity {
  
        private Button btnSendNotification;
        int order = 0;
  
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                 // TODO Auto-generated method stub
                 super.onCreate(savedInstanceState);
                 setContentView(R.layout.notification);
                 btnSendNotification = (Button) findViewById(R.id.btnSendNotification);
                 btnSendNotification.setOnClickListener(new OnClickListener() {
                           @Override
                           public void onClick(View v) {
                                    order++;
                                    //调用系统通知
                                    sendNotification(order);
                                    //调用自定义的通知
                                    order++;
                                    sendDefineNotification(order);
                           }
                 });
  
        }
     //使用系统自带页面布局的通知
        private void sendNotification(int order) {
                 // 创建一个NotificationManager的引用
                 String ns = Context.NOTIFICATION_SERVICE;
                 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
                 // 定义Notification的各种属性
                 int icon = R.drawable.icon; // 通知图标
                 CharSequence tickerText = "Hello" + order; // 状态栏显示的通知文本提示
                 long when = System.currentTimeMillis(); // 通知产生的时间,会在通知信息里显示
                 // 用上面的属性初始化Nofification
                 Notification notification = new Notification(icon, tickerText, when);
                 if (order % 5 == 0)// 5的倍数消息,就显示正在运行Ongoing的那个栏目,其余的显示在通知Notifications栏目
                 {
                           notification.flags |= Notification.FLAG_ONGOING_EVENT;
                 }
                
                 /*
                  *
                  * 添加声音 notification.defaults |=Notification.DEFAULT_SOUND; 或者使用以下几种方式
                  * notification.sound =
                  * Uri.parse("file:///sdcard/notification/ringer.mp3");
                  * notification.sound =
                  * Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
                  * 如果想要让声音持续重复直到用户对通知做出反应,则可以在notification的flags字段增加"FLAG_INSISTENT"
                  * 如果notification的defaults字段包括了"DEFAULT_SOUND"属性,则这个属性将覆盖sound字段中定义的声音
                  */
                  notification.defaults |=Notification.DEFAULT_SOUND;
                 /*
                  *
                  * 添加振动
                  *
                  * notification.defaults |= Notification.DEFAULT_VIBRATE;
                  *
                  * 或者可以定义自己的振动模式: long数组可以定义成想要的任何长度
                  *
                  * 如果notification的defaults字段包括了"DEFAULT_VIBRATE",则这个属性将覆盖vibrate字段中定义的振动
                  */
                 long[] vibrate = { 0, 100, 200, 300 }; // 0毫秒后开始振动,振动100毫秒后停止,再过200毫秒后再次振动300毫秒
                 notification.vibrate = vibrate;
  
                 /*
                  *
                  * 添加LED灯提醒 notification.defaults |= Notification.DEFAULT_LIGHTS;
                  * 或者可以自己的LED提醒模式:
                  */
                 notification.ledARGB = 0xff00ff00;
                 notification.ledOnMS = 3000; // 亮的时间
                 notification.ledOffMS = 1000; // 灭的时间
                 notification.flags |= Notification.FLAG_SHOW_LIGHTS;
                
                 /*
                  *
                  * 更多的特征属性
                  *
                  * notification.flags |= FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知,如果不设置,ongoing和自定义的通知的点击后不会消失
                  * notification.flags |= FLAG_INSISTENT; //重复发出声音,直到用户响应此通知
                  * notification.flags |= FLAG_ONGOING_EVENT;
                  * //将此通知放到通知栏的"Ongoing"即"正在运行"组中
                  * notification.flags |= FLAG_NO_CLEAR; //表明在点击了通知栏中的"清除通知"后,此通知不清除,
                  * //经常与FLAG_ONGOING_EVENT一起使用
                  * notification.number = 1; //number字段表示此通知代表的当前事件数量,它将覆盖在状态栏图标的顶部
                  * //如果要使用此字段,必须从1开始
                  * notification.iconLevel = ; //
                  */
  
                 // 设置通知的事件消息
  
                 Context context = getApplicationContext(); // 上下文
                 CharSequence contentTitle = "My Notification" + order; // 通知栏标题
                 CharSequence contentText = "Hello World!" + order; // 通知栏内容
                 Intent notificationIntent = new Intent(this, HelloWorldActivity.class); // 点击该通知后要跳转的Activity
                 PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                                    notificationIntent, 0);
                 notification.setLatestEventInfo(context, contentTitle, contentText,
                                    contentIntent);
                 // 把Notification传递给NotificationManager
                 mNotificationManager.notify(order, notification);
  
        }
        //使用自定义页面布局的通知
        private void sendDefineNotification(int order)
        {
                 //创建一个NotificationManager的引用
                 String ns = Context.NOTIFICATION_SERVICE;
                 NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
                 //定义Notification的各种属性
                 int icon = R.drawable.icon; //通知图标
                 CharSequence tickerText = "Hello"; //状态栏显示的通知文本提示
                 long when = System.currentTimeMillis(); //通知产生的时间,会在通知信息里显示
                 //用上面的属性初始化Nofification
                 Notification notification = new Notification(icon,tickerText,when);
                 RemoteViews contentView = new RemoteViews(getPackageName(),R.layout.notificationview);
                 contentView.setImageViewResource(R.id.imgNotification, R.drawable.heart);
                 contentView.setTextViewText(R.id.tvNotification, "这里是自定义通知"+order);
                 notification.contentView = contentView;
                 Intent notificationIntent = new Intent(this,HelloWorldActivity.class);
                 PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
                 notification.contentIntent = contentIntent;
                 //把Notification传递给NotificationManager
                 mNotificationManager.notify(order,notification);
  
        }
       
  
 }

 

第三步、AndroidManifest.xml添加Acitivity

<activity android:name=".NotificationManagerActivity">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
       </activity>

第四步、运行效果

 

 

Android 通知如何长时振动_android

Android 通知如何长时振动_Android 通知如何长时振动_02