通知(Notification)入門

通知(Notification)的簡單實現

先貼出代碼,不理解的代碼基本都有註釋。
首先貼出佈局文件activity_main.xml的代碼,很簡單就是一個觸發按鈕,點擊按鈕顯示通知。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
<Button
    android:id="@+id/send_notice"
    android:text="Send notice"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

再是邏輯代碼MainActivity.java

package com.example.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener{
    private Button sendNotice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_notice:
                NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);//創建一個NotificationManager對通知進行管理
                Notification.Builder builder = new Notification.Builder(this);
                builder.setContentInfo("補充內容");
                builder.setContentText("主內容區");
                builder.setContentTitle("通知標題");
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setTicker("新消息");
                builder.setWhen(System.currentTimeMillis());//指定通知被創建的時間
                Notification notification = builder.build();
                manager.notify(1, notification);//第一個參數設置id
                break;
            default:
                break;
        }
    }
}

值得一提的是以下方法在sdk22可以使用。但sdk23中已經不能使用
Notification notification = new Notification(R.mipmap.ic_launcher,”this is ticker text”,System.currentTimeMillis());//創建的這個對象用於存儲通知所需的各種信息。第一個參數指定通知的圖標,第二個指定通知的內容,第三個指定通知被創建的時間
notification.setLatestEventInfo(this,”thisis content title”,”this is content text”,null);//對佈局進行設定第一個參數context上下文第二個參數指定通知標題的內容,第三個參數用於指定通知的正文內容

那麼sdk23使用的是什麼方法來實現的呢?
答案是使用 Notification.Builder

Notification.Builder builder = new Notification.Builder(this);
builder.setContentInfo(“補充內容”);
builder.setContentText(“主內容區”);
builder.setContentTitle(“通知標題”);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setTicker(“新消息”);

這只是一個簡單的demo實現通知功能,還沒有加入跳轉等複雜功能,在後續的章節中爲大家繼續介紹。

發佈了26 篇原創文章 · 獲贊 2 · 訪問量 9147
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章