博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android开发学习之路--Notification之初体验
阅读量:5115 次
发布时间:2019-06-13

本文共 11525 字,大约阅读时间需要 38 分钟。

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

    首先新建NotificationTestproject,然后加入一个button,用来触发通知。然后编写代码例如以下:

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号,每个通知有其独特的通知号。不能反复。

    执行效果例如以下所看到的:

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

> <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。之后就能够达到我们的效果,执行并点击通知例如以下所看到的:

       

    如上所看到的收到了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,当下载完毕后又一次设置下内容。

执行结果例如以下:

     

    图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中加入权限:

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

    下载到手机执行后就能够观察效果。

      当然还能够控制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基本上就学到这里了。

转载于:https://www.cnblogs.com/claireyuancy/p/7039655.html

你可能感兴趣的文章
MVC3.0 如何点击点击一张图片连接到另一地址
查看>>
iOS中 点击按钮无响应
查看>>
redis 优缺点 使用场景
查看>>
002_关于six版本过低报cannot import name urllib_parse的问题
查看>>
dtcp格式定义
查看>>
列表、表格与媒体元素
查看>>
js转义html,反转义
查看>>
Educational Codeforces Round 39 A Partition
查看>>
上传文件
查看>>
原来数据库里的单引号是这么加进去的
查看>>
html5新特性:异步上传文件
查看>>
12.2日常
查看>>
12.3日常
查看>>
MAVEN项目的搭建
查看>>
EL表达式取整问题
查看>>
使用过滤器实现网站访问计数器的功能
查看>>
Lumia 800 7.10.8783.12
查看>>
面向对象的四大特征 封装 继承 多态 抽象
查看>>
XML的概述,.Dom4解析和SAX解析
查看>>
codefroces204A - Little Elephant and Interval 数位DP
查看>>