Android基础教程:下载管理中Notification的使用
Android基础教程:下载管理中Notification的使用
点击下载按钮,通知用户下载任务已添加到下载列表中布局文件如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:background="@drawable/page"
- android:layout_height="wrap_content" android:orientation="vertical">
- <Button android:id="@+id/down"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载文件"/>
- <Button android:id="@+id/newdown"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="新建下载任务"/>
- </LinearLayout>
- package com.cloay.down.activity;
- import java.util.HashMap;
- import android.app.Activity;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import com.cloay.down.R;
- import com.cloay.down.service.MainService;
- import com.cloay.down.utils.Task;
- /**
- * 模拟下载网页上的下载按钮
- * DownloadActivity.java
- * @author cloay
- * 2011-11-18
- */
- public class DownloadActivity extends Activity {
- private Button download;
- private Button newdownload;
- private NotificationManager notificationManager;
- private PendingIntent pendingIntent;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Intent intent = new Intent("com.cloay.down.service.MainService");
- this.startService(intent);
- notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- Intent intent1 = new Intent(this, DownLoadManager.class);
- pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_ONE_SHOT);
- download = (Button) findViewById(R.id.down);
- download.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- startLoadTask("http://taoke.youkk.net/Mine.mp3");
- }
- });
- newdownload = (Button) findViewById(R.id.newdown);
- newdownload.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- startLoadTask("http://mp3.jayie.com/38.mp3");
- }
- });
- }
- private void startLoadTask(String url) {
- //使用service后台下载
- HashMap<String, String> parm = new HashMap<String, String>();
- parm.put("url", url);
- Task task = new Task(Task.LOAD_FILE, parm);
- MainService.newTask(task);
- Notification notification = new Notification();
- notification.icon = R.drawable.download_notification;
- notification.tickerText = "下载任务已添加到下载列表中,点击查看!";
- notification.defaults = Notification.DEFAULT_SOUND;
- notification.setLatestEventInfo(DownloadActivity.this, "下载任务已启动", "下载任务已添加到下载列表中!", pendingIntent);
- notificationManager.notify(0, notification);
- }
- }
评论暂时关闭