Android 学习笔记之一 Status Bar Notifications

来源:互联网 发布:一个域名绑定多个ip 编辑:程序博客网 时间:2024/05/29 09:14

 这是为什么呢?查询后得知:setLatestEventInfo该方法已被deprecate,不建议使用了。


     /*
     * @hide
     */
    public Notification(Context context, int icon, CharSequence tickerText, long when,
            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
    {
        this.when = when;
        this.icon = icon;
        this.tickerText = tickerText;
        setLatestEventInfo(context, contentTitle, contentText,
                PendingIntent.getActivity(context, 0, contentIntent, 0));
    }

    这个构造函数被hide,setLatestEventInfo方法也被deprecate,不建议使用,使用Notification.Builder即可。

    在4.0.3平台也就是API Level 15中,使用Notification的setLatestEventInfo()函数时,也会显示成setLatestEventInfo()效果,查看文档发现,在API Level 11中,该函数已经被替代,不推荐使用了。
 


    在不同的版本下Notification使用有一些不同,涉及到改成Builder的使用,现在网上大多数资料还是API Level 11版本前的用法介绍,如果不熟悉的话,会绕一些弯路。
 
    现在总结如下,希望对以后使用的程序员有所帮助。
 
    低于API Level 11版本,也就是Android 2.3.3以下的系统中,setLatestEventInfo()函数是唯一的实现方法。前面的有关属性设置这里就不再提了,网上资料很多。
Intent  intent = new Intent(this,MainActivity);  
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);  
notification.setLatestEventInfo(context, title, message, pendingIntent);          
manager.notify(id, notification);  

    高于API Level 11,低于API Level 16 (Android 4.1.2)版本的系统中,可使用Notification.Builder来构造函数。但要使用getNotification()来使notification实现。此时,前面版本在notification中设置的Flags,icon等属性都已经无效,要在builder里面设置。
Notification.Builder builder = new Notification.Builder(context)  
            .setAutoCancel(true)  
            .setContentTitle("title")  
            .setContentText("describe")  
            .setContentIntent(pendingIntent)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setWhen(System.currentTimeMillis())  
            .setOngoing(true);  
notification=builder.getNotification();  

    高于API Level 16的版本,就可以用Builder和build()函数来配套的方便使用notification了。
Notification notification = new Notification.Builder(context)    
         .setAutoCancel(true)    
         .setContentTitle("title")    
         .setContentText("describe")    
         .setContentIntent(pendingIntent)    
         .setSmallIcon(R.drawable.ic_launcher)    
         .setWhen(System.currentTimeMillis())    
         .build();   
 

    【注意点】:
    在构造notification的时候有很多种写法,但是要注意,用
Notification notification = new Notification();
这种构建方法的时候,一定要加上notification.icon这个设置,不然,程序虽然不会报错,但是会没有效果。 

    另外,补充下在实际android开发中遇到的一些警告以及解决方法:
1:Handler

// This Handler class should be static or leaks might occur: IncomingHandler
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

        };
    };
    
解决方法:

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });


2:SimpleDateFormat

    // To get local formatting use getDateInstance(), getDateTimeInstance(), or
    // getTimeInstance(), or use new SimpleDateFormat(String template, Locale
    // locale) with for example Locale.US for ASCII dates.
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
            "yyyy-MM-ddHH:mm:ss");
解决方法:

    SimpleDateFormat newSimpleDateFormat = new SimpleDateFormat(
            "yyyy年MM月dd日HH时mm分", Locale.getDefault());

3:new HashMap() 
    @SuppressLint("UseSparseArrays")
    public static Map CMD_MAP = new HashMap();

警告原因:Use new SparseArray(...) instead for better performance

4:"String".toUpperCase(); "String".toLowerCase();

     @SuppressLint("DefaultLocale")
    boolean  b = "String".toUpperCase().equals("STRING");
解决方法:
 boolean  b = "String".equalsIgnoreCase("STRING");
警告原因:Implicitly using the default locale is a common source of bugs: Use toUpperCase(Locale) instead



<1>简介

Android系统的状态栏(Status Bar)中有一个创新UI设计,这就是可以下拉的通知提示。当系统有一些消息要通知用户时,例如,收到短信、电子邮件、有未接来电时,都会把信息作为通知(Notification)发送给用户。

Status Bar 增加了一个图标到系统状态栏中,还有文本信息(可以不选),增加Notification信息到Notification窗口。你还可以安装Notification利用的声音,震动,设备上闪关灯来提醒用户。

 

   NotificationToast都可以起到通知、提醒的作用。但它们的实现原理和表现形式却完全不一样。

Toast其实相当于一个组件(Widget)。有些类似于没有按钮的对话框。而Notification是显示在屏幕上方状态栏中的信息。

Notification需要用NotificationManager来管理,而Toast只需要简单地创建Toast对象即可。

<2>步骤:

创建 status bar notification:

1。NotificationManager得到一个参考:

[java] view plain copy
  1. String ns = Context.NOTIFICATION_SERVICE;  
[java] view plain copy
  1. NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);  

或者

[java] view plain copy
  1. NotificationManager mNotificationManager  = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  

2。创建一个Notification对象。每一个Notification对应一个Notification对象。在这一步需要设置显示在屏幕上方状态栏的通知消息、通知消息前方的图像资源ID和发出通知的时间。一般为当前时间。


 

[java] view plain copy
  1. int icon = R.drawable.notification_icon; //显示在屏幕上方状态栏的图标  
[java] view plain copy
  1. CharSequence tickerText = "Hello";     //显示在屏幕上方状态栏的通知消息  
[java] view plain copy
  1. long when = System.currentTimeMillis(); //发出通知的时间  
[java] view plain copy
  1. Notification notification = new Notification(icon, tickerText, when);  


 3。定义的信息和PendingIntent通知:

由于Notification可以与应用程序脱离。也就是说,即使应用程序被关闭,Notification仍然会显示在状态栏中。当应用程序再次启动后,又可以重新控制这些Notification。如清除或替换它们。因此,需要创建一个PendingIntent对象。该对象由Android系统负责维护,因此,在应用程序关闭后,该对象仍然不会被释放。
 使用Notification类的setLatestEventInfo方法设置Notification的详细信息。

[java] view plain copy
  1. Context context = getApplicationContext();  
[java] view plain copy
  1. CharSequence contentTitle = "My notification";   //Notification通知标题  
[java] view plain copy
  1. CharSequence contentText = "Hello World!";              //Notification通知内容  
[java] view plain copy
  1. Intent notificationIntent = new Intent(this, MyClass.class);   //跳转到MyClass.class  
[java] view plain copy
  1. PendingIntent contentIntent = PendingIntent.getActivity(this0, notificationIntent, 0);    //生成一个PendingIntent  
[java] view plain copy
  1. notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);  //很重要的方法  

4通过对NotificationManager通知:

使用NotificationManager类的notify方法显示Notification消息。在这一步需要指定标识Notification的唯一ID。这个ID必须相对于同一个NotificationManager对象是唯一的,否则就会覆盖相同IDNotificaiton()

[java] view plain copy
  1. private static final int HELLO_ID = 1;  
[java] view plain copy
  1. mNotificationManager.notify(HELLO_ID, notification);  

在这里要解释一下的是notify方法的第1个参数。这个参数实际上表示了NotificationID。是一个int类型的值。

为了使这个值唯一,可以使用res目录中的某些资源ID。例如,在上面的代码中使用了当前Notification显示的图像对应的资源IDR.drawable.icon)作为NotificationID。当然,读者也可以使用其他的值作为NotificationID值。

5。在显示Notification时还可以设置显示通知时的默认发声、震动和Light效果。要实现这个功能需要设置Notification类的defaults属性,代码如下:

   1  添加声音:

        你可以提醒用户提供了默认的通知声音(这是由用户定义)或应用程序特定的声音

        应用程序规定的声音:

[java] view plain copy
  1. notification.defaults = Notification.DEFAULT_SOUND;  

       自定义:使用一个不同的声音的Notification,通过一个Uri引用声音的位置。下面的例子使用一个保存到装置的SD卡已知的音频文件:

[java] view plain copy
  1. notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");  


    2 增加振动:

     你可以提醒用户提供了震动(这是由用户定义)或应用程序特定的振动模式
     应用程序规定的振动模式:

[java] view plain copy
  1. notification.defaults = Notification.DEFAULT_VIBRATE;  

    定义你自己的振动模式,通过一系列的长值:

[java] view plain copy
  1. long[] vibrate = {0,100,200,300};  
[java] view plain copy
  1. notification.vibrate = vibrate;  

       第一个值是等待要花费你多长时间(关闭)开始之前,第二个值是第一个振动的长度,三是下一个长度时,等等。花纹可只要你喜欢,但它不能被设定为重复。

      3添加灯光闪烁

      通知用户发出闪光LED灯,你可以继承默认t模式(如有),或定义自己的颜色和图案的灯。

      使用默认的灯光设置,加上DEFAULT_LIGHTS到defaults:

[java] view plain copy
  1. notification.defaults = Notification.DEFAULT_LIGHTS;  

 

<3>更多功能 (利用 Flag)
notification.flags = Notification.FLAG_AUTO_CANCEL; 

自动取消通知之后,这是选择通知窗口。

notification.flags = Notification.FLAG_INSISTENT; 

重复的声响,直到用户响应。

notification.flags = Notification.FLAG_NO_CLEAR;

表明通知不应该被“Clear notifications”按钮清除。这是特别有用,如果你的notification正在通知。


范例:

[java] view plain copy
  1. package xiaosi.notification;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.Notification;  
  5. import android.app.NotificationManager;  
  6. import android.app.PendingIntent;  
  7. import android.content.Intent;  
  8. import android.os.Bundle;  
  9.   
  10. public class NotificationActivity extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.           
  17.         NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  18.         Notification notification = new Notification(R.drawable.a,"你有短消息了",System.currentTimeMillis());  
  19.           
  20.         notification.flags = Notification.FLAG_AUTO_CANCEL;  
  21.           
  22.         Intent notificationIntent = new Intent();  
  23.         PendingIntent pedingIntent = PendingIntent.getActivity(this0, notificationIntent, 0);  
  24.         notification.setLatestEventInfo(this"你有短消息了""祝你新婚快乐", pedingIntent);  
  25.           
  26.         notificationManager.notify(R.drawable.a,notification);  
  27.     }  
  28. }  


 

[java] view plain copy
  1. package xiaosi.notification;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5.   
  6. public class MainActivity extends Activity{  
  7.     /** Called when the activity is first created. */  
  8.       
  9.     @Override  
  10.     public void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.main);  
  13.     }  
  14. }  


main.xml

[java] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/start"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="Notification演示"/>  
  12. </LinearLayout>  







0 0
原创粉丝点击