Android学习之Notification的简单使用
阅读原文时间:2021年04月20日阅读:2

这次来谈谈notification,notification一般用在电话,短信,邮件,闹钟铃声等,在手机的状态栏上就会出现一个小图标,提示用户处理这个快讯,这时手从上方滑动状态栏就可以展开并处理这个快讯。

废话不多说,上程序:

1 主界面布局

<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"
    tools:context=".NotificationAct" >

    <Button 
        android:id="@+id/btn_1"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="较老方法"
        />

    <Button 
        android:id="@+id/btn_2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="官方推荐"
        />

    <Button 
        android:id="@+id/btn_3"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="自定义"
        />

</LinearLayout>

效果图如下:

2 主程序代码

package com.example.notificationact;

import android.os.Bundle;
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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;

public class NotificationAct extends Activity {

    private Button btn_1 = null;
    private Button btn_2 = null;
    private Button btn_3 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_notification);

        buildBtn();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.act_notification, menu);
        return true;
    }

    public void buildBtn() {
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);
        btn_3 = (Button) findViewById(R.id.btn_3);

        btn_1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showNotification("今天下雪", "很大的雪", "不适合出行",
                        R.drawable.ic_launcher, R.drawable.ic_launcher);
            }
        });

        btn_2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showNotificationByNotificationCompat();
            }
        });

        btn_3.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showMusicPlayerNotification("天天动听", R.drawable.appwidget_icon,
                        R.drawable.appwidget_icon, R.drawable.appwidget_icon,
                        "蝴蝶", "胡彦斌");
            }
        });
    }

    /**
     * 较老的方法
     * @param tickerText
     * @param contentTitle
     * @param contentText
     * @param id
     * @param resId
     */
    public void showNotification(String tickerText, String contentTitle,
            String contentText, int id, int resId) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Notification notification = new Notification(resId, tickerText,
                System.currentTimeMillis());
        notification.defaults = Notification.DEFAULT_VIBRATE;// 使用默认的震动

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                getIntent(), 0);

        notification.setLatestEventInfo(this, contentTitle, contentText,
                contentIntent);

        notificationManager.notify(id, notification);
    }

    /**
     * 使用官方推荐方法
     */
    public void showNotificationByNotificationCompat() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher_mail);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setLargeIcon(bitmap)
                .setSmallIcon(R.drawable.ic_menu_compose_normal_holo_light)
                .setContentTitle("您有5封邮件").setContentText("baidu@gmail.com")
                .setContentInfo("12").setWhen(System.currentTimeMillis())
                .setAutoCancel(false);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(this, NotificationAct.class);

        // The stack builder object will contain an artificial back stack for
        // the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(NotificationAct.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // mId allows you to update the notification later on.
        mNotificationManager.notify(1, mBuilder.build());
    }

    /**
     * 自定义的notification,仿天天动听
     * 
     * @param tickerText
     * @param id
     * @param resId
     * @param photoId
     * @param songName
     * @param singerName
     */
    public void showMusicPlayerNotification(String tickerText, int id,
            int resId, int photoId, String songName, String singerName) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Notification notification = new Notification(resId, tickerText,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                getIntent(), 0);

        // 自定义界面
        RemoteViews remoteView = new RemoteViews(getPackageName(),
                R.layout.notification);
        remoteView.setTextViewText(R.id.tv_song_name, songName);
        remoteView.setTextViewText(R.id.tv_singer_name, singerName);
        remoteView.setImageViewResource(R.id.iv_singer_photo,
                R.drawable.appwidget_icon);
        notification.contentView = remoteView;

        notificationManager.notify(id, notification);
    }


}

其中第三个函数 showMusicPlayerNotification( )为自定义View的Notification,其XML布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="64dp" >

    <ImageView
        android:id="@+id/iv_singer_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/appwidget_icon" />

    <LinearLayout
        android:id="@+id/ll_song_operation"
        android:layout_width="96dp"
        android:layout_height="fill_parent"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:gravity="center"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/nc_previoussong_pressed" />

        <Button
            android:id="@+id/btn_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/nc_pause_pressed" />

        <Button
            android:id="@+id/btn_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/nc_nextsong_pressed" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_song_detail"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginLeft="5dp"
        android:layout_toLeftOf="@id/ll_song_operation"
        android:layout_toRightOf="@id/iv_singer_photo"
        android:gravity="center_vertical"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_song_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:ellipsize="end"
            android:text="蝴蝶"
            android:textColor="#000000"
            android:textSize="18sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_singer_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="胡彦斌"
            android:textColor="#696969"
            android:textSize="13sp" />
    </LinearLayout>

</RelativeLayout>

最终运行程序,效果图如下:

3 结语

上面所述是使用notification的基本用法,其中showNotificationByNotificationCompat()函数中的setWhen()方法不起作用,我也不知道为啥,有知道的童鞋请不吝赐教。关于官方推荐的请参考developer.android.com-Notification

对于Notification的更高级的用法,等到仔细研究后再进行补充~