第十八章 Notification

建立Notification

1. 使用new Notification.Builder(Context)建立builder物件
2. 在由builder.build()產生Notification 物件
3. 取得NotificationManager manager
4. manager.notify(int, notification)發送通知

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Notification.Builder builder=new Notification.Builder(this);
        builder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("Thomas Notification")
                .setContentText("這是一個通告");
        Notification notification=builder.build();
        NotificationManager manager=
                (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, notification);
    }
}

設定Notification

上述的builder中, 是最基本的需求設定, 常有如下項目可設定
.setColor(Color) : API21 Lollipop才支援
.setDefaults(int) : int可以為

Noitifcation.DEFAULT_VIBRATE|
Notification.DEFAULT_SOUND|
Notification.DEFAULT_LIGHTS

若要產生震動, 請加入權限
<uses-permission android:name=”android:permission.VIBRATE” />

🔒 更多內容,請登入會員繼續閱讀。

立即登入

發佈留言

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