2012年6月7日星期四

使用通知生成器 (Notification.Builder) 創建通知 (Notification)

Android 3.0, API Level 11, 提供新的 android.app.Notification.Builder 類. 用於更容易創建通知(Notification).

實例:

通知生成器 (Notification.Builder)


package com.Android3NotificationBuilder;

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.widget.Button;

public class Android3NotificationBuilderActivity extends Activity {
 
 Button buttonCreateNotification;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buttonCreateNotification = (Button)findViewById(R.id.createnotification);
        buttonCreateNotification.setOnClickListener(
          new Button.OnClickListener(){

     @Override
     public void onClick(View arg0) {
      createNotification(getBaseContext());
      
     }}
          );
        
    }
    
    private void createNotification(Context context){
     NotificationManager notificationManager 
      = (NotificationManager)context.getSystemService(
        Context.NOTIFICATION_SERVICE);
     
     Notification.Builder builder = new Notification.Builder(context);
     Intent intent = new Intent(context, Android3NotificationBuilderActivity.class);
     PendingIntent pendingIntent 
      = PendingIntent.getActivity(context, 0, intent, 0);
     
     long[] vibratepattern = {100, 400, 500, 400};
     
     builder
     .setSmallIcon(R.drawable.ic_launcher)
     .setContentTitle("標題")
     .setContentText("文字")
     .setContentInfo("信息")
     .setTicker("票")
     .setLights(0xFFFFFFFF, 1000, 1000)
     .setVibrate(vibratepattern)
     .setContentIntent(pendingIntent)
     .setAutoCancel(false);
     
     Notification notification = builder.getNotification();
     notificationManager.notify(R.drawable.ic_launcher, notification);
    }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/createnotification"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="創建通知(Notification)" />

</LinearLayout>



因為這個例子創建的通知會產生震動, 因此需要修改 AndroidManifest.xml, 添加 "android.permission.VIBRATE" 許可.

沒有留言:

發佈留言