Android的Notification的简介-android学习之旅(四十一)

时间:2022-02-01 05:03:27

Notification简介

Notification位于手机饿最上面,用于显示手机的各种信息,包括网络状态,电池状态,时间等。

属性方法介绍

Android的Notification的简介-android学习之旅(四十一)

代码示例

package peng.liu.test;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TabHost;

public class MainActivity extends Activity {
    static final int NOTIFICATION__ID = 0X123;
    NotificationManager nm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    }
    public void send(View view){
        Intent intent = new Intent(MainActivity.this,MainActivity2.class);
        PendingIntent pi = PendingIntent.getActivity(MainActivity.this,0,intent,0);
        Notification notification = new Notification.Builder(this).setAutoCancel(true)
                .setTicker("新消息")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("new message")
                .setContentText("hello world")
                .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS)
                .setWhen(System.currentTimeMillis())
                .setContentIntent(pi)
                .build();
        nm.notify(NOTIFICATION__ID,notification);
    }
    public void dev(View view){
        nm.cancel(NOTIFICATION__ID);
    }
}
<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:onClick="send"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button2"
        android:onClick="dev"/>

</LinearLayout>