標籤:android style http ar io color os sp java
Notification可以在螢幕最頂部的狀態列上顯示一個表徵圖通知,通知的同時可以播放聲音,以及震動提示使用者,點擊通知還可以返回指定的Activity.
今天例子的:
布局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>
java代碼:
package com.pocketdigi.Notification;
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;
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,"表徵圖邊的文字","標題","內容");
}
};
OnClickListener bt2lis=new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//showNotification(R.drawable.home,"表徵圖邊的文字","標題","內容");
nm.cancel(notification_id);
}
};
public void showNotification(int icon,String tickertext,String title,String content){
//設定一個唯一的ID,隨便設定
//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" />
<!-- 允許震動 -->
Android 狀態列通知Notification