android第三更(下载附件,通知栏显示进度)

我们在开发中经常需要从服务器下载文件,下载的内容可能有交换的信息,缓存的图片,程序更新包等。我们使用URLConnection来实现下载。先看几行代码:

  URL url=new URL(urls);
             HttpURLConnection conn=(HttpURLConnection) url.openConnection();//建立连接
             conn.setConnectTimeout(5000);//设置等待时间
             fileSize =conn.getContentLength();//获取文件的长度
             InputStream is=conn.getInputStream();//获取输入流
              FileOutputStream fos=new FileOutputStream(file);
             byte[] buffer =new byte[1024];
             int len=0;
             while((len=is.read(buffer))!=-1){//将文件下载到指定目录中
                 fos.write(buffer,0,len);
                 downloadSize += len;//获取当前下载的长度
                 Message msg=new Message();
                 Log.i(TAG,downloadSize+"    "+fileSize);
//               msg.what=1;
                 msg.what= downloadSize * 100 / fileSize;
                 Log.i("downloadSize",msg.what+"");
                 handler.sendMessage(msg);//向handle进行传值
             }
             fos.flush();
             fos.close();
             is.close();

下载文件很简单,主要是和通知栏建立联系 这就需要用到Handle 通过Handle可以对通知栏进行刷新,并且还可以传递下载进度。
DownActivity.java 主程序
DownUtil .java 设置、刷新通知栏进度
FileDownloadThread .java 下载附件

在DownActivity中我们只需要设置下载文件的文件名、存储地址和下载地址就可以

DownActivity.java

public class DownActivity extends Activity {
    Button btn;
    public String downloadDir;//文件的存储路径
    public String downloadUrl;//文件的下载地址
    private String fileName;//下载文件名
    Down down;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 
        //从网上随便找的一个APK下载地址
        downloadUrl = "http://activitymo.homelink.com.cn/download/homelink/android/Android_homelinkfanstong1.apk";
         down = new Down(DownActivity.this);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                download();
            }
        });


    }
    /**
     * 下载附件
     */
    public void download(){

        downloadDir= Environment.getExternalStorageDirectory()+"/taotao/attach";
        File file=new File(downloadDir);
        //如果文件夹不存在 则重建
        if(!file.exists()){
            file.mkdirs();
        }
        //返回最后一个“/”后一个字符的位置int值
        int filestart=downloadUrl.lastIndexOf("/");
        //截取()之后的字符
        fileName=downloadUrl.substring(filestart+1);
//        downloadProgressBar.setVisibility(View.VISIBLE);
//        downloadProgressBar.setProgress(0);

        down.downloadTask(downloadUrl,  downloadDir, fileName);
    }
}

接下来就是通知栏下载进度条、通知栏刷新这个放在一个工具类中
DownUtil .java

public class DownUtil {

    private String fileName;//下载文件名
    private String paths;//文件地址
    private Context context;

    public DownUtil(Context context){
        this.context = context;
    }

    Handler handler=new Handler(){

        public void handleMessage(android.os.Message msg) {
            //当收到更新视图消息时,计算以完成下载百分比,同时个in关心进度条信息
            //通知栏功能的实现
            String ns = Context.NOTIFICATION_SERVICE;

            //初始化通知管理
            NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(ns);
            //创建Notification对象
            Notification notification = new Notification();
            int progress = msg.what;
            if (progress == -1) {
                notification.contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
                notification.contentView.setProgressBar(R.id.ProgressBar01, 100, progress, false);
                notification.contentView.setTextViewText(R.id.TextView01, "下载失败");
                notification.contentView.setTextViewText(R.id.TextView03, progress + "%");
                notification.contentView.setTextViewText(R.id.TextView02, fileName+"下载");
                notification.icon = R.mipmap.ic_launcher;
                mNotificationManager.notify(1, notification);
            } else {
                if (progress <= 100) {
                    notification.contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
                    notification.contentView.setProgressBar(R.id.ProgressBar01, 100, progress, false);
                    notification.contentView.setTextViewText(R.id.TextView03, progress + "%");
                    notification.contentView.setTextViewText(R.id.TextView02, fileName+"下载");
                    notification.icon = R.mipmap.ic_launcher_icon;
                    mNotificationManager.notify(1, notification);
                }
                if (progress == 100) {
                    //定义通知栏展现的内容信息
                    notification.icon = R.mipmap.ic_launcher_icon;
                    notification.tickerText = fileName+"下载完成";
                    notification.defaults = Notification.DEFAULT_VIBRATE;

                    //定义下拉通知栏时要展现的内容信息
//                    Context context = getApplicationContext();
                    CharSequence contentTitle = fileName+"下载完成";
                    CharSequence contentText = "淘淘:" + fileName;
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;
                    Intent notificationIntent = AndroidFileUtil.openFile(new File(paths));
                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

                    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

                    //用mNotificationManager的notify方法通知用户生成标题栏消息通知
                    mNotificationManager.notify(1, notification);

                }
            }
        }
    };
    /**
     * 线程下载开始
     *
     * **/

        public void downloadTask(String urlStr,String dirPath,String fileName){
            this.fileName = fileName;
            Message msg = new Message();
            msg.what = 0;
            handler.sendMessage(msg);
                paths=dirPath+fileName;
                File file=new File(dirPath + fileName);
            //如果文件已存在 则先删除 后下载
            if(file.exists()){
                file.delete();
            }
            //启动线程,文件
                    FileDownloadThread fdt=new FileDownloadThread(urlStr,file,handler);
                    fdt.setName("thread");
                    fdt.start();
        }
    }

最后就是下载文件的工具类
FileDownloadThread .java
/**
* 下载文件
* @author Administrator
*
*/
public class FileDownloadThread extends Thread {

private static final int BUFFER_SIZE = 1024;
private static final String TAG = "FileDownloadThread";
private String urls;
private File file;
private int curPosition;
private int fileSize;
 //用于标识当前线程是否下载完成  
private boolean finished=false;  
private int downloadSize=0;
private Handler handler;
/**
 * 
 * @param url 下载地址
 * @param file 
 */
public FileDownloadThread(String urls,File file,Handler handler){
    this.urls=urls;
    this.file=file;  
    this.handler = handler;
}
@Override
public void run() {
    // TODO Auto-generated method stub


     try {
         URL url=new URL(urls);
         HttpURLConnection conn=(HttpURLConnection) url.openConnection();
         conn.setConnectTimeout(5000);
         fileSize =conn.getContentLength();
         InputStream is=conn.getInputStream();//获取输入流
         Log.i("file",file+"");
         FileOutputStream fos=new FileOutputStream(file);
         byte[] buffer =new byte[1024];
         int len=0;
         while((len=is.read(buffer))!=-1){
             fos.write(buffer,0,len);
             downloadSize += len;
             Message msg=new Message();
             Log.i(TAG,downloadSize+"    "+fileSize);

// msg.what=1;
msg.what= downloadSize * 100 / fileSize;
Log.i(“downloadSize”,msg.what+”“);
handler.sendMessage(msg);
}
fos.flush();
fos.close();
is.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

    }  

}
xml文件我就写通知栏的布局
notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <RelativeLayout
        android:id="@+id/relayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:paddingRight="10dp"
            android:src="@mipmap/ic_launcher" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/relayout"
        android:layout_alignTop="@+id/relayout"
        android:layout_marginRight="10dp"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:layout_toRightOf="@+id/relayout"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="正在下载 ..."
            android:textSize="18sp" >
        </TextView>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/TextView02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="文件名。。。。" >
            </TextView>

            <TextView
                android:id="@+id/TextView03"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:text="0%" >
            </TextView>
        </RelativeLayout>

        <ProgressBar
            android:id="@+id/ProgressBar01"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >
        </ProgressBar>
    </LinearLayout>

</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值