技術學習記錄

[Android]Notification推播通知

當LINE收到好友發出的訊息,或是收到Email,在螢幕的上方或是系統的通知清單顯示一個提示方塊。

這個訊息方塊就叫做推播通知。

如何建立通知

這裡以按下APP上的按鈕發出推播通知做為示範

1.首先在佈局文件中放入一個按鈕,如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button" />

</LinearLayout>

2.接著在Activity中加入按鈕,以及OnClickListener和推播通知元件,如下:

public class MainActivity extends Activity {

    int ID_NOTIFICATION = 0x00;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                showNotification();
            }
        });
    }

    private void showNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_shoeisha)));
        PendingIntent contentIntent = PendingIntent.getActivity(this, ID_NOTIFICATION, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 宣告Notification物件
        Notification.Builder notification = new Notification.Builder(this);
        // 設定時間戳記
        notification.setWhen(System.currentTimeMillis());
        // 設定Intent
        notification.setContentIntent(contentIntent);
        // 設定圖示
        notification.setSmallIcon(android.R.drawable.stat_notify_chat);
        // 設定文字
        notification.setTicker("我是內容");
        // 設定標題
        notification.setContentTitle("我是標題");
        // 設定提示(指示燈、提示音、震動)
        notification.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
        // 點選後自動清除
        notification.setAutoCancel(true);
        Notification notification = notification.build();

        // 顯示通知
        notificationManager.notify(ID_NOTIFICATION_SAMPLE_ACTIVITY, notification);
    }
}

以上是生成推播通知的示範

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *