Android开发学习之路--Notification之初体验

    一般当我们收到短信啊,微信啊,或者有些app的提醒,我们都会在通知栏收到一天简单的消息,然后点击消息进入到app里面,其实android中有专门的Notification的类可以完成这个工作,这里就实现下这个功能。

    首先新建NotificationTest工程,然后添加一个按钮,用来触发通知,然后编写代码如下:

package com.example.jared.notificationtest;

import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button sendNotificationBtn;

    private int mId = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotificationBtn = (Button)findViewById(R.id.sendNotification);
        sendNotificationBtn.setOnClickListener(new myOnClickListener());
    }

    private class myOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.sendNotification:
                    setSendNotificationBtn();
                    break;
                default:
                    break;
            }
        }
    }

    public void setSendNotificationBtn () {
        NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("My Notification")
                .setContentText("Hello Notification");
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(mId, notification.build());
    }
}

    这里了用了NotificatonCompat.Builder来创建一个简单的Notification,setSmallIcon是指定其中的图标,setContentTitle方法是指定标题,setContentText指定内容,然后通过getSystemService获取通知的管理类,通过notify方法发送通知,其中mId是一个id号,每一个通知有其独特的通知号,不能重复。

    运行效果如下所示:

Android开发学习之路--Notification之初体验_第1张图片

    接着我们来实现点击通知后跳转到对应的Activity中,然后消除这条通知。再创建一个Activity,布局如下:

<?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"
    tools:context="com.example.jared.notificationtest.Notification">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="欢迎点击通知事件!"
        android:layout_margin="20dp"
        android:textSize="20dp"/>
</LinearLayout>

    这里就一个textview用来显示下信息,接着编写代码如下:

package com.example.jared.notificationtest;

import android.app.NotificationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Notification extends AppCompatActivity {

    private int mId = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(mId);
    }
}
    这里进入到Activity后就把通知清除掉,接着就是修改MainActivity代码:

package com.example.jared.notificationtest;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button sendNotificationBtn;

    private int mId = 1;
    private int numMessage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotificationBtn = (Button)findViewById(R.id.sendNotification);
        sendNotificationBtn.setOnClickListener(new myOnClickListener());
    }

    private class myOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.sendNotification:
                    setSendNotificationBtn();
                    break;
                default:
                    break;
            }
        }
    }

    public void setSendNotificationBtn () {
        NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("My Notification")
                .setContentText("Hello Notification")
                .setNumber(++numMessage);

        Intent intent = new Intent(this, Notification.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(mId, notification.build());
    }
}

    这里又添加了setNumber方法,主要是显示来了几条通知,比如微信中就需要知道,然后实例化了一个intent,再实例化一个pendingIntent,获取activity,在NotificationCompat.Builder里setContentIntent,之后就可以达到我们的效果,运行并点击通知如下所示:

Android开发学习之路--Notification之初体验_第2张图片       Android开发学习之路--Notification之初体验_第3张图片

    如上所示收到了6条通知,然后点击后通知也消除了。

    一般在下载歌曲啊,图片啊的时候,会有进度条表示下载的过程,这里来模拟实现下这个功能,修改MainAcitivy代码如下:

package com.example.jared.notificationtest;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button sendNotificationBtn;

    private int mId = 1;
    private int numMessage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotificationBtn = (Button)findViewById(R.id.sendNotification);
        sendNotificationBtn.setOnClickListener(new myOnClickListener());
    }

    private class myOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.sendNotification:
                    setSendNotificationBtn();
                    break;
                default:
                    break;
            }
        }
    }

    public void setSendNotificationBtn () {
         final NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Music Download")
                .setContentText("burning.mp3")
                .setNumber(++numMessage);

        Intent intent = new Intent(this, Notification.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setContentIntent(pendingIntent);

        final NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        new Thread(
                new Runnable(){
                    @Override
                    public void run() {
                        for(int cnt=0; cnt<=100; cnt++){
                            notification.setProgress(100, cnt, false);
                            manager.notify(mId, notification.build());
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                Log.d(TAG, "Sleep failure");
                            }
                        }
                        notification.setContentText("Download complete");
                        notification.setProgress(0, 0, false);
                        manager.notify(mId, notification.build());
                    }
                }
        ).start();
    }
}

    这里通过setProgress方法来实现,这里开了一个Thread,当下载完成后重新设置下内容。运行结果如下:

Android开发学习之路--Notification之初体验_第4张图片     Android开发学习之路--Notification之初体验_第5张图片

    图1显示进度条在走,图2完成了下载功能。

    一般收到通知,手机都会有一段声音,加上震动,那么接下来来实现这个功能。上图,如果下载完成后,就放一段音乐并且震动,修改代码如下:

package com.example.jared.notificationtest;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private Button sendNotificationBtn;

    private int mId = 1;
    private int numMessage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotificationBtn = (Button)findViewById(R.id.sendNotification);
        sendNotificationBtn.setOnClickListener(new myOnClickListener());
    }

    private class myOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.sendNotification:
                    setSendNotificationBtn();
                    break;
                default:
                    break;
            }
        }
    }

    public void setSendNotificationBtn () {
         final NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Music Download")
                .setContentText("burning.mp3")
                .setNumber(++numMessage);

        Intent intent = new Intent(this, Notification.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setContentIntent(pendingIntent);

        final NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        new Thread(
                new Runnable(){
                    @Override
                    public void run() {
                        for(int cnt=0; cnt<=100; cnt++){
                            notification.setProgress(100, cnt, false);
                            manager.notify(mId, notification.build());
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                Log.d(TAG, "Sleep failure");
                            }
                        }
                        notification.setContentText("Download complete");
                        notification.setProgress(0, 0, false);
                        Uri soundUri = Uri.fromFile(new File("/system/media/audio/animationsounds/bootSound.ogg"));
                        notification.setSound(soundUri);
                        long[] vibrates = {0, 1000, 1000, 1000};
                        notification.setVibrate(vibrates);
                        manager.notify(mId, notification.build());
                    }
                }
        ).start();
    }
}

    这里加上了setSound和setVibrate方法,并且需要在AndroidManifest中添加权限:

<uses-permission android:name="android.permission.VIBRATE"/>

    这里的歌曲名是通过adb shell查看系统的存在的音乐:

Android开发学习之路--Notification之初体验_第6张图片

    下载到手机运行后就可以观察效果。

      当然还可以控制led灯,不知为啥led灯的效果一直没有,网上翻阅很多资料也没找到问题所在,若有朋友知道,麻烦告知一二不甚感激。

 notification.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                        long[] vibrates = {0, 1000, 1000, 1000};
                        notification.setVibrate(vibrates);
                        notification.setLights(Color.GREEN, 1000, 1000);
    关于Notification基本上就学到这里了。


你可能感兴趣的:(Android开发学习之路--Notification之初体验)