Android 狀態欄通知Notification

Notification能夠在屏幕最頂部的狀態欄上顯示一個圖標通知,通知的同時能夠播放聲音,以及振動提示用戶,點擊通知還能夠返回指定的Activity.
  今天例子的效果圖: java

佈局main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/bt1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="Notification測試"
/>
<Button android:id="@+id/bt2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="清除Notification"
/>
</LinearLayout> android

java代碼:
package com.pocketdigi.Notification; app

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; ide

public class main extends Activity {
/** Called when the activity is first created. */
int notification_id=19172439;
NotificationManager nm;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Button bt1=(Button)findViewById(R.id.bt1);
bt1.setOnClickListener(bt1lis);
Button bt2=(Button)findViewById(R.id.bt2);
bt2.setOnClickListener(bt2lis); 佈局

}
OnClickListener bt1lis=new OnClickListener(){ 測試

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showNotification(R.drawable.home,"圖標邊的文字","標題","內容");
} this

};
OnClickListener bt2lis=new OnClickListener(){ xml

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//showNotification(R.drawable.home,"圖標邊的文字","標題","內容");
nm.cancel(notification_id);
} utf-8

};
public void showNotification(int icon,String tickertext,String title,String content){
//設置一個惟一的ID,隨便設置 ci

//Notification管理器
Notification notification=new Notification(icon,tickertext,System.currentTimeMillis());
//後面的參數分別是顯示在頂部通知欄的小圖標,小圖標旁的文字(短暫顯示,自動消失)系統當前時間(不明白這個有什麼用)
notification.defaults=Notification.DEFAULT_ALL; 
//這是設置通知是否同時播放聲音或振動,聲音爲Notification.DEFAULT_SOUND
//振動爲Notification.DEFAULT_VIBRATE;
//Light爲Notification.DEFAULT_LIGHTS,在個人Milestone上好像沒什麼反應
//所有爲Notification.DEFAULT_ALL
//若是是振動或者所有,必須在AndroidManifest.xml加入振動權限
PendingIntent pt=PendingIntent.getActivity(this, 0, new Intent(this,main.class), 0);
//點擊通知後的動做,這裏是轉回main 這個Acticity
notification.setLatestEventInfo(this,title,content,pt);
nm.notify(notification_id, notification);

}
}

AndroidManifest.xml加入權限: <uses-permission android:name="android.permission.VIBRATE" />  <!-- 容許振動 --> 

相關文章
相關標籤/搜索