Android开发学习
Android开发中,通常需要有一个自动更新客户端的功能,这个就需要弄一个下载apk文件的功能,下载完后提示更新
新建布局文件:activity_main.xml,代码内容:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/btnDownloadInstallApk" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="点击下载" /> <TextView android:id="@+id/Path" android:layout_width="fill_parent" android:layout_height="wrap_content" ></TextView> </LinearLayout>
实现的MainActivity.java代码如下:
package com.zhengdecai.filedownload; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * 对文件进行下载,并判断是否是apk安装包文件,提示安装 * * @author 郑德才 * */ public class MainActivity extends Activity { int fileSize; int downLoadFileSize; String fileEx, fileNa, filename; private ProgressDialog mpDialog; public String apkUrl = "https://www.zhengdecai.com/phone/Www_Zhdc.apk"; //更新文件路径 /** Called when the activity is first created. */ String downloadPath = Environment.getExternalStorageDirectory().getPath() + "/download_cache/"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnDownloadInstallApk = (Button) findViewById(R.id.btnDownloadInstallApk); File file1 = new File(downloadPath); if (!file1.exists()) { file1.mkdir(); } TextView txtPath = (TextView) findViewById(R.id.Path); txtPath.setText(downloadPath); filename = apkUrl.substring(apkUrl .lastIndexOf("/") + 1); File isFile = new File(downloadPath + filename); if(isFile.exists()){ Toast.makeText(MainActivity.this, "文件已经存在: " + downloadPath + filename, Toast.LENGTH_LONG).show(); } btnDownloadInstallApk.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mpDialog = new ProgressDialog(MainActivity.this); mpDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置风格为长进度条 mpDialog.setTitle("提示");// 设置标题 29 // mpDialog.setIcon(R.drawable.icon);//设置图标 mpDialog.setMessage("正在下载中,请稍后"); mpDialog.setIndeterminate(false);// 设置进度条是否为不明确 false 就是不设置为不明确 mpDialog.setCancelable(true);// 设置进度条是否可以按退回键取消 mpDialog.setProgress(0); mpDialog.incrementProgressBy(1); // 增加和减少进度,这个属性必须的 mpDialog.setButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //installApk(downloadPath + filename);// 下载完毕安装 FileInfo.openFile(downloadPath + filename); dialog.cancel(); } }); mpDialog.show(); // Looper.prepare(); new Thread() { public void run() { URL url = null; try { url = new URL(apkUrl); HttpURLConnection con = (HttpURLConnection) url .openConnection(); InputStream in = con.getInputStream(); fileSize = con.getContentLength(); File fileOut = new File(downloadPath + filename); FileOutputStream out = new FileOutputStream(fileOut); byte[] bytes = new byte[1024]; downLoadFileSize = 0; sendMsg(0); int c; while ((c = in.read(bytes)) != -1) { out.write(bytes, 0, c); downLoadFileSize += c; sendMsg(1);// 更新进度条 } in.close(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } sendMsg(2);// 下载完成 try { } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } }); } private final Handler handler = new Handler(Looper.getMainLooper()) { public void handleMessage(Message msg) { if (!Thread.currentThread().isInterrupted()) { switch (msg.what) { case 0: mpDialog.setMax(100); break; case 1: int result = downLoadFileSize * 100 / fileSize; mpDialog.setProgress(result); break; case 2: mpDialog.setMessage("文件下载完成"); break; case -1: String error = msg.getData().getString("error"); mpDialog.setMessage(error); break; default: break; } } super.handleMessage(msg); } }; private void sendMsg(int flag) { Message msg = new Message(); msg.what = flag; handler.sendMessage(msg); } /** * 安装apk * */ private void installApk(String filename) { File file = new File(filename); Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); String type = "application/vnd.android.package-archive"; intent.setDataAndType(Uri.fromFile(file), type); startActivity(intent); // 判断apk是否安装过 PackageInfo pm; try { pm = getPackageManager().getPackageInfo("com.ha.minifetion", 0); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
FileInfo类文件:
package com.zhengdecai.filedownload; import java.io.File; import android.content.Intent; import android.net.Uri; public class FileInfo { public static Intent openFile(String filePath){ File file = new File(filePath); if(!file.exists()) return null; /* 取得扩展名 */ String end=file.getName().substring(file.getName().lastIndexOf(".") + 1,file.getName().length()).toLowerCase(); /* 依扩展名的类型决定MimeType */ if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")|| end.equals("xmf")||end.equals("ogg")||end.equals("wav")){ return getAudioFileIntent(filePath); }else if(end.equals("3gp")||end.equals("mp4")){ return getAudioFileIntent(filePath); }else if(end.equals("jpg")||end.equals("gif")||end.equals("png")|| end.equals("jpeg")||end.equals("bmp")){ return getImageFileIntent(filePath); }else if(end.equals("apk")){ return getApkFileIntent(filePath); }else if(end.equals("ppt")){ return getPptFileIntent(filePath); }else if(end.equals("xls")){ return getExcelFileIntent(filePath); }else if(end.equals("doc")){ return getWordFileIntent(filePath); }else if(end.equals("pdf")){ return getPdfFileIntent(filePath); }else if(end.equals("chm")){ return getChmFileIntent(filePath); }else if(end.equals("txt")){ return getTextFileIntent(filePath,false); }else{ return getAllIntent(filePath); } } //Android获取一个用于打开APK文件的intent public static Intent getAllIntent( String param ) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri,"*/*"); return intent; } //Android获取一个用于打开APK文件的intent public static Intent getApkFileIntent( String param ) { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri,"application/vnd.android.package-archive"); return intent; } //Android获取一个用于打开VIDEO文件的intent public static Intent getVideoFileIntent( String param ) { Intent intent = new Intent("android.intent.action.VIEW"); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("oneshot", 0); intent.putExtra("configchange", 0); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "video/*"); return intent; } //Android获取一个用于打开AUDIO文件的intent public static Intent getAudioFileIntent( String param ){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("oneshot", 0); intent.putExtra("configchange", 0); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "audio/*"); return intent; } //Android获取一个用于打开Html文件的intent public static Intent getHtmlFileIntent( String param ){ Uri uri = Uri.parse(param ).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param ).build(); Intent intent = new Intent("android.intent.action.VIEW"); intent.setDataAndType(uri, "text/html"); return intent; } //Android获取一个用于打开图片文件的intent public static Intent getImageFileIntent( String param ) { Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "image/*"); return intent; } //Android获取一个用于打开PPT文件的intent public static Intent getPptFileIntent( String param ){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); return intent; } //Android获取一个用于打开Excel文件的intent public static Intent getExcelFileIntent( String param ){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "application/vnd.ms-excel"); return intent; } //Android获取一个用于打开Word文件的intent public static Intent getWordFileIntent( String param ){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "application/msword"); return intent; } //Android获取一个用于打开CHM文件的intent public static Intent getChmFileIntent( String param ){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "application/x-chm"); return intent; } //Android获取一个用于打开文本文件的intent public static Intent getTextFileIntent( String param, boolean paramBoolean){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (paramBoolean){ Uri uri1 = Uri.parse(param ); intent.setDataAndType(uri1, "text/plain"); }else{ Uri uri2 = Uri.fromFile(new File(param )); intent.setDataAndType(uri2, "text/plain"); } return intent; } //Android获取一个用于打开PDF文件的intent public static Intent getPdfFileIntent( String param ){ Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Uri uri = Uri.fromFile(new File(param )); intent.setDataAndType(uri, "application/pdf"); return intent; } }
实现运行效果图:
评论列表: