详解Android中Notification的使用方法

2019-12-10 19:38:24于丽
易采站长站为您分析Android中Notification的使用方法,最典型的应用就是未看短信和未接来电的显示,还有QQ微信,想要深入了解Notification的朋友可以参考本文  

      在消息通知的时候,我们经常用到两个控件Notification和Toast。特别是重要的和需要长时间显示的信息,用Notification最合适不过了。他可以在顶部显示一个图标以标示有了新的通知,当我们拉下通知栏的时候,可以看到详细的通知内容。
      最典型的应用就是未看短信和未接来电的显示,还有QQ微信,我们一看就知道有一个未接来电或者未看短信,收到QQ离线信息。同样,我们也可以自定义一个Notification来定义我们自己的程序想要传达的信息。

Notification我把他分为两种,一种是默认的显示方式,另一种是自定义的,今天为大家讲述默认的显示方式:
1、程序框架结构图如下

详解Android中Notification的使用方法

2、布局文件 main.xml 源码如下

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android" 
 android:orientation="vertical" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 > 
<TextView  
 android:layout_width="fill_parent"  
 android:layout_height="wrap_content"  
 android:gravity="center" 
 android:textColor="#EEE" 
 android:textStyle="bold" 
 android:textSize="25sp" 
 android:text="NotificationDemo实例" /> 
<Button 
 android:id="@+id/btnSend" 
 android:text="send notification" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:layout_gravity="center"/>  
</LinearLayout> 

3、MainActivity.java源码如下:

package com.andyidea.notification; 
 
import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
 
public class MainActivity extends Activity { 
 private Button btnSend; 
  
 //定义BroadcastReceiver的action 
 private static final String NotificationDemo_Action = "com.andyidea.notification.NotificationDemo_Action"; 
  
 /** Called when the activity is first created. */ 
 @Override 
 public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.main); 
   
  btnSend = (Button)findViewById(R.id.btnSend); 
  btnSend.setOnClickListener(new View.OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    Intent intent = new Intent(); 
    intent.setAction(NotificationDemo_Action); 
    sendBroadcast(intent); 
   } 
  }); 
 } 
  
}