第五十讲:Android之Nothfication(三)

勤能补拙是良训,一分辛劳一分才。

本讲内容:通知 Notification 和 通知管理器 NotificationManager

我们通过一个例子实现一个可更新进度的通知,代码的讲解都写在注释里了

下面是res/layout/activity_main.xml 布局文件:

<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="com.example.text1.MainActivity$PlaceholderFragment" >
	<Button
	    android:id="@+id/download"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="download"
	    android:onClick="download"/>
	<Button
	    android:id="@+id/cancel"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="cancel"
	    android:onClick="cancel"/>
	<!-- 为了使示例中的Java代码看起来结构更加清晰,我们将按钮的点击事件都定义在布局文件中。 -->
</LinearLayout>

下面是带进度的通知布局/res/layout/download_notification_layout.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="match_parent"
    android:padding="3dp">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:src="@drawable/ic_launcher"/>
    <TextView
        android:id="@+id/fileName"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/imageView"
        android:layout_alignBottom="@id/imageView"
        android:gravity="center_vertical"
        android:textColor="#0f0"/>
    <TextView
        android:id="@+id/rate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/imageView"
        android:layout_alignRight="@id/imageView"
        android:gravity="center"
        android:text="0%"
        android:textColor="#0f0"/>
    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/fileName"
        android:layout_alignLeft="@id/fileName"
        android:max="100"
        android:progress="0"/>
</RelativeLayout>

下面是MainActivity.java主界面文件:

public class MainActivity extends Activity {
	private Notification notification;
	private NotificationManager notificationManager;
	private static final int NOTIFY_ID=0;
	private boolean flag;
	private Context context=this;

	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				int rate=msg.arg1;
				if(rate<100){
					 // 更新进度
                    RemoteViews contentView = notification.contentView;
                    contentView.setTextViewText(R.id.rate, rate + "%");
                    contentView.setProgressBar(R.id.progress, 100, rate, false);
				}else{
					// 下载完毕后变换通知形式
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.contentView = null;
                    Intent intent = new Intent(context, NotifyActivity.class);
                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
                    notification.setLatestEventInfo(context, "下载完成", "文件已下载完毕", contentIntent);
				}
				 // 最后别忘了通知一下,否则不会更新
                notificationManager.notify(NOTIFY_ID, notification);
				break;

			case 0:
				 // 取消通知
                notificationManager.cancel(NOTIFY_ID);
                break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	public void download(View view){
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  

        int icon = R.drawable.ic_launcher;
        CharSequence tickerText = "开始下载";
        long when = System.currentTimeMillis();
        notification = new Notification(icon, tickerText, when);
     // 放置在"正在运行"栏目中
        notification.flags = Notification.FLAG_ONGOING_EVENT;  

        //点击通知时不跳转
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, getIntent(), 0); 

        RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.download_notification_layout);
        contentView.setTextViewText(R.id.fileName, "AngryBird.apk");
        // 指定个性化视图
        notification.contentView = contentView;
        // 指定内容意图
       notification.contentIntent = contentIntent; 

        notificationManager.notify(NOTIFY_ID, notification);  

        new Thread() {
            public void run() {
                startDownload();
            };
        }.start();
	}
	 public void cancel(View view) {
	        flag = true; // 在控制下载线程时使用了flag这个boolean值标志变量,对于线程的控制更好一些
	    }
	 private void startDownload() {
	        flag = false;
	        int rate = 0;
	        while (!flag && rate < 100) {
	            try {
	                // 模拟下载进度
	                Thread.sleep(500);
	                rate = rate + 5;
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            }
	            Message msg = handler.obtainMessage();
	            msg.what = 1;
	            msg.arg1 = rate;
	            handler.sendMessage(msg);
	        }
	        if (flag) {
	            Message msg = handler.obtainMessage();
	            msg.what = 0;
	            handler.sendMessage(msg);
	        }
	    }
}

上面涉及到线程和handler类,后面章节我们会深入讲解

下面是运行结果:

本讲就到这里,Take your time and enjoy it

时间: 2024-07-30 08:25:13

第五十讲:Android之Nothfication(三)的相关文章

Android笔记(五十) Android中的JSON数据

JSON是什么: JSON是轻量级的文本数据交换格式 JSON独立于语言和平台 JSON具有自我描述性,更容易理解 JSON语法: 数据在名称/值对中 数据由逗号分割 大括号表示对象 中括号表示数组 JSON使用: MainActivity.java package cn.lixyz.jsontest.activity; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import ja

(五十八)android坐标系统

一.首先明确一下 android 中的坐标系统 : 屏幕的左上角是坐标系统原点(0,0) 原点向右延伸是X轴正方向,原点向下延伸是Y轴正方向

hiho一下 第五十四周 题目1 : 连通性&#183;三

题目1 : 连通性·三 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 暑假到了!!小Hi和小Ho为了体验生活,来到了住在大草原的约翰家.今天一大早,约翰因为有事要出去,就拜托小Hi和小Ho忙帮放牧. 约翰家一共有N个草场,每个草场有容量为W[i]的牧草,N个草场之间有M条单向的路径. 小Hi和小Ho需要将牛羊群赶到草场上,当他们吃完一个草场牧草后,继续前往其他草场.当没有可以到达的草场或是能够到达的草场都已经被吃光了之后,小hi和小Ho就把牛羊群赶回家. 一开始小

第三百五十八节,Python分布式爬虫打造搜索引擎Scrapy精讲—将bloomfilter(布隆过滤器)集成到scrapy-redis中

第三百五十八节,Python分布式爬虫打造搜索引擎Scrapy精讲-将bloomfilter(布隆过滤器)集成到scrapy-redis中,判断URL是否重复 布隆过滤器(Bloom Filter)详解 基本概念 如果想判断一个元素是不是在一个集合里,一般想到的是将所有元素保存起来,然后通过比较确定.链表,树等等数据结构都是这种思路. 但是随着集合中元素的增加,我们需要的存储空间越来越大,检索速度也越来越慢.不过世界上还有一种叫作散列表(又叫哈希表,Hash table)的数据结构.它可以通过一

第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy分布式爬虫要点

第三百五十六节,Python分布式爬虫打造搜索引擎Scrapy精讲-scrapy分布式爬虫要点 1.分布式爬虫原理 2.分布式爬虫优点 3.分布式爬虫需要解决的问题

第三百五十五节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy信号详解

第三百五十五节,Python分布式爬虫打造搜索引擎Scrapy精讲-scrapy信号详解 信号一般使用信号分发器dispatcher.connect(),来设置信号,和信号触发函数,当捕获到信号时执行一个函数 dispatcher.connect()信号分发器,第一个参数信号触发函数,第二个参数是触发信号, signals.engine_started当Scrapy引擎启动爬取时发送该信号.该信号支持返回deferreds.signals.engine_stopped当Scrapy引擎停止时发送

第三百五十三节,Python分布式爬虫打造搜索引擎Scrapy精讲—scrapy的暂停与重启

第三百五十三节,Python分布式爬虫打造搜索引擎Scrapy精讲-scrapy的暂停与重启 scrapy的每一个爬虫,暂停时可以记录暂停状态以及爬取了哪些url,重启时可以从暂停状态开始爬取过的URL不在爬取 实现暂停与重启记录状态 1.首先cd进入到scrapy项目里 2.在scrapy项目里创建保存记录信息的文件夹 3.执行命令: scrapy crawl 爬虫名称 -s JOBDIR=保存记录信息的路径 如:scrapy crawl cnblogs -s JOBDIR=zant/001

第三百五十四节,Python分布式爬虫打造搜索引擎Scrapy精讲—数据收集(Stats Collection)

第三百五十四节,Python分布式爬虫打造搜索引擎Scrapy精讲-数据收集(Stats Collection) Scrapy提供了方便的收集数据的机制.数据以key/value方式存储,值大多是计数值. 该机制叫做数据收集器(Stats Collector),可以通过 Crawler API 的属性 stats 来使用无论数据收集(stats collection)开启或者关闭,数据收集器永远都是可用的. 因此您可以import进自己的模块并使用其API(增加值或者设置新的状态键(stat k

【笔记】得到-《梁宁&#183;产品思维三十讲》

ps:偶然从[得到]上听到梁宁的<产品思维三十讲],感觉很棒,抽时间听完了所有的课程,特整理笔记如下. 01发刊词|产品能力是每个人的底层能力 产品能力就是训练一个人:判断信息,抓住要点,整合有限的资源,把自己的价值打包成一个产品向世界交付,并且获得回报. 通过这30讲,希望拥有三个东西: 1.一双眼睛.发现痛点.找到破局点的敏锐之眼: 2.一双手.动手优化,着手改变的行动之手: 3.一颗心.洞察人性的同理心,懂得自己与用户,懂得产品上每个细节给到人的满足感.确认感和依赖感. 02案例:用户体验