android第三更(下载附件,通知栏显示进度)
来源:互联网 发布:有淘宝就能贷款的软件 编辑:程序博客网 时间:2024/05/22 15:22
我们在开发中经常需要从服务器下载文件,下载的内容可能有交换的信息,缓存的图片,程序更新包等。我们使用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;}@Overridepublic 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>
- android第三更(下载附件,通知栏显示进度)
- android 通知栏显示下载进度
- 通知栏显示下载进度
- android 下载应用 通知栏显示进度 下完之后点击安装 (很实用)
- NotificationDownLoad 通知栏显示下载进度
- android文件下载及自定义通知显示下载进度
- android文件下载及自定义通知显示下载进度
- Android下载,在通知栏更新进度
- Android——下载apk文件,并在通知栏显示下载进度
- Android 自动更新 后代通知栏显示进度
- android实现下载图片在(Notification)通知栏上显示进度。
- 通过服务来下载APK,并在通知栏显示下载进度(两种方式)
- 下载apk,并将进度显示在通知栏
- android+https网址屏蔽证书+IntentService+NotifyManager通知栏+下载apk文件+在通知栏显示下载进度+完成之后提示安装
- Android FTPUtils工具在通知栏notification显示进度
- Android 简单实现app通知栏更新及显示进度
- Android 通过蒲公英pgyer的接口 Service 实现带进度下载App 通知栏显示 在线更新 自动更新Demo
- Android 通过蒲公英pgyer的接口 Service 实现带进度下载App 通知栏显示 在线更新 自动更新Demo
- c++引用与指针的区别(着重理解)
- 【Spring】Spring MVC Controller 参数中文乱码
- Struts 2 creating own interceptor
- cocos2dx+lua 3.5创建项目并移植到androdi
- gradle错误“Could not resolve all dependencies for configuration”
- android第三更(下载附件,通知栏显示进度)
- 复合类型与const关键字
- 智能指针用法
- DelegatingRequestProcessor作用
- iOS利用AFNetworking(AFN) 实现图片上传
- eclipse配置maven环境简记
- 嵌入式裸机编程,对内存管理的一些见解
- android gps开发必备资料
- MySQL中用户权限、库权限、表权限的控制