【安卓笔记】在Notification中显示下载进度

效果:

【安卓笔记】在Notification中显示下载进度【安卓笔记】在Notification中显示下载进度

代码直接在上一篇AsyncTask示例中做修改,布局跟上次一样,这里不贴了。
MainActivity:
package com.example.asynctaskdemo4;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
    private static final String PATH = "http://h.hiphotos.baidu.com/image/w%3D2048/sign=d78504fa9d3df8dca63d8891f929738b/9f510fb30f2442a77e79f7a8d343ad4bd1130243.jpg";
    private Button but_down = null;
    private ImageView iv_show = null;
    private TextView tv_progress = null;
    private ProgressBar pb = null;
    private NotificationManager manager = null;
    private NotificationCompat.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        but_down = (Button) findViewById(R.id.but_down);
        iv_show = (ImageView) findViewById(R.id.iv_show);
        tv_progress = (TextView) findViewById(R.id.tv_progress);
        pb = (ProgressBar) findViewById(R.id.pb);
        
        manager = (NotificationManager) MainActivity.this.getSystemService(NOTIFICATION_SERVICE);
        but_down.setOnClickListener(this);
    }
    @Override
    public void onClick(View v)
    {
        if (R.id.but_down == v.getId())
        {
            new DownloadImageTask().execute(PATH);
        }
    }
    private class DownloadImageTask extends AsyncTask<String, Integer, Bitmap>
    {
        @Override
        protected void onPostExecute(Bitmap result)
        {
            if (result != null)
            {
                tv_progress.setVisibility(View.GONE);
                pb.setVisibility(View.GONE);
                
                iv_show.setImageBitmap(result);
                builder.setProgress(0,0,true);
                builder.setContentText("下载完成");
                Notification no = builder.build();
                no.flags = Notification.FLAG_AUTO_CANCEL;
                no.defaults = Notification.DEFAULT_SOUND;
                manager.notify(1, no);
            } else
            {
                builder.setProgress(0, 0, true);
                builder.setContentText("下载失败..");
                manager.notify(1,builder.build());
                tv_progress.setVisibility(View.GONE);
                pb.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this,"下载失败",0).show();
            }
        }
        @Override
        protected Bitmap doInBackground(String... params)
        {
            String path = params[0];
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(path);
            try
            {
                HttpResponse resp = client.execute(get);
                if(resp.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = resp.getEntity();
                    if(entity == null)
                    {
                        return null;
                    }
                    long total_length = entity.getContentLength();//获取文件总长
                    InputStream is = entity.getContent();
                    ByteArrayOutputStream bous = new ByteArrayOutputStream();
                    int len = 0;
                    byte[] buf = new byte[1024];
                    int current_len = 0;
                    int progress = 0;//当前下载进度
                    while((len = is.read(buf))!= -1)
                    {
                        current_len+=len;
                        bous.write(buf, 0, len);
                        progress = (int) ((current_len/(float)total_length)*100);
                        this.publishProgress(progress);
                    }
                    is.close();
                    byte[] data = bous.toByteArray();
                    Options opts = new Options();
                    opts.inSampleSize = 2;//简单起见直接指定缩放比例
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
                    return bitmap;
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onProgressUpdate(Integer... values)
        {
            tv_progress.setText("下载进度:"+values[0]);
            builder.setContentText("下载进度:"+values[0]+"%");
            builder.setProgress(100, values[0], false);
            Notification no = builder.build();
            no.flags = Notification.FLAG_NO_CLEAR;
            manager.notify(1,no);
            no = null;
        }
        @Override
        protected void onPreExecute()
        {
            tv_progress.setVisibility(View.VISIBLE);
            pb.setVisibility(View.VISIBLE);
            
            builder = new NotificationCompat.Builder(MainActivity.this);
            builder.setSmallIcon(R.drawable.down);
            builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.down));
            builder.setContentTitle("美女图片");
            PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this,MainActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pi);
            builder.setProgress(100, 0, false);
            manager.notify(1,builder.build());
        }
    }
}

这里使用的是v4包的NotificationCompat.Builder类来产生Notification实例,如果你直接new一个Notification,那应该自定义一个Notification样式,即在通知中加一个ProgressBar。
像这样:
Notification no = new Notification(icon, tickerText, when);
no.contentView.setProgressBar(viewId, max, progress, indeterminate);


【安卓笔记】在Notification中显示下载进度

上一篇:【Android进阶】android:configChanges属性总结


下一篇:Android 如何去除Launcher上默认的google search bar?