实例介绍
package com.cn.do1.downloadtest.service; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import com.cn.do1.downloadtest.DownloadTest; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.widget.Toast; public class DownloadService extends Service{ private static NotificationManager nm; private static Notification notification; private static boolean cancelUpdate = false; private static MyHandler myHandler; private static ExecutorService executorService = Executors.newFixedThreadPool(5); // 固定五个线程来执行任务 public static Map<Integer,Integer> download = new HashMap<Integer, Integer>(); public static Context context; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public void onCreate() { super.onCreate(); nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); myHandler = new MyHandler(Looper.myLooper(), DownloadService.this); context = this; } @Override public void onDestroy() { super.onDestroy(); } public static void downNewFile(final String url,final int notificationId,final String name){ if(download.containsKey(notificationId)) return; notification = new Notification(); notification.icon = android.R.drawable.stat_sys_download; // notification.icon=android.R.drawable.stat_sys_download_done; notification.tickerText = name "开始下载"; notification.when = System.currentTimeMillis(); notification.defaults = Notification.DEFAULT_LIGHTS; //显示在“正在进行中” notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; PendingIntent contentIntent = PendingIntent.getActivity(context, notificationId,new Intent(context, DownloadTest.class), 0); notification.setLatestEventInfo(context, name, "0%", contentIntent); download.put(notificationId, 0); // 将下载任务添加到任务栏中 nm.notify(notificationId, notification); // 启动线程开始执行下载任务 downFile(url,notificationId,name); } // 下载更新文件 private static void downFile(final String url,final int notificationId,final String name) { executorService.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub File tempFile = null; try { HttpClient client = new DefaultHttpClient(); // params[0]代表连接的url HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); if (is != null) { File rootFile = new File(Environment.getExternalStorageDirectory(),"/zhtrade"); if (!rootFile.exists() && !rootFile.isDirectory()) rootFile.mkdir(); tempFile = new File(Environment.getExternalStorageDirectory(),"/zhtrade/" url.substring(url.lastIndexOf("/"),url.indexOf("?")) "_" notificationId ".apk"); if (tempFile.exists()) tempFile.delete(); tempFile.createNewFile(); // 已读出流作为参数创建一个带有缓冲的输出流 BufferedInputStream bis = new BufferedInputStream(is); // 创建一个新的写入流,讲读取到的图像数据写入到文件中 FileOutputStream fos = new FileOutputStream(tempFile); // 已写入流作为参数创建一个带有缓冲的写入流 BufferedOutputStream bos = new BufferedOutputStream(fos); int read; long count = 0; int precent = 0; byte[] buffer = new byte[1024]; while ((read = bis.read(buffer)) != -1 && !cancelUpdate) { bos.write(buffer, 0, read); count = read; precent = (int) (((double) count / length) * 100); // 每下载完成1%就通知任务栏进行修改下载进度 if (precent - download.get(notificationId) >= 1) { download.put(notificationId, precent); Message message = myHandler.obtainMessage(3,precent); Bundle bundle = new Bundle(); bundle.putString("name", name); message.setData(bundle); message.arg1 = notificationId; myHandler.sendMessage(message); } } bos.flush(); bos.close(); fos.flush(); fos.close(); is.close(); bis.close(); } if (!cancelUpdate) { Message message = myHandler.obtainMessage(2, tempFile); message.arg1 = notificationId; Bundle bundle = new Bundle(); bundle.putString("name", name); message.setData(bundle); myHandler.sendMessage(message); } else { tempFile.delete(); } } catch (ClientProtocolException e) { if (tempFile.exists()) tempFile.delete(); Message message = myHandler.obtainMessage(4, name "下载失败:网络异常!"); message.arg1 = notificationId; myHandler.sendMessage(message); } catch (IOException e) { if (tempFile.exists()) tempFile.delete(); Message message = myHandler.obtainMessage(4, name "下载失败:文件传输异常"); message.arg1 = notificationId; myHandler.sendMessage(message); } catch (Exception e) { if (tempFile.exists()) tempFile.delete(); Message message = myHandler.obtainMessage(4, name "下载失败," e.getMessage()); message.arg1 = notificationId; myHandler.sendMessage(message); } } }); } // 安装下载后的apk文件 private void Instanll(File file, Context context) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive"); context.startActivity(intent); } /* 事件处理类 */ class MyHandler extends Handler { private Context context; public MyHandler(Looper looper, Context c) { super(looper); this.context = c; } @Override public void handleMessage(Message msg) { PendingIntent contentIntent = null; super.handleMessage(msg); if (msg != null) { switch (msg.what) { case 0: Toast.makeText(context, msg.obj.toString(),Toast.LENGTH_SHORT).show(); download.remove(msg.arg1); break; case 1: break; case 2: contentIntent = PendingIntent.getActivity(DownloadService.this, msg.arg1,new Intent(DownloadService.this, DownloadTest.class), 0); notification.setLatestEventInfo(DownloadService.this, msg.getData().getString("name") "下载完成", "100%",contentIntent); nm.notify(msg.arg1, notification); // 下载完成后清除所有下载信息,执行安装提示 download.remove(msg.arg1); nm.cancel(msg.arg1); Instanll((File) msg.obj, context); break; case 3: contentIntent = PendingIntent.getActivity(DownloadService.this, msg.arg1,new Intent(DownloadService.this, DownloadTest.class), 0); notification.setLatestEventInfo(DownloadService.this, msg.getData().getString("name") "正在下载", download.get(msg.arg1) "%",contentIntent); nm.notify(msg.arg1, notification); break; case 4: Toast.makeText(context, msg.obj.toString(),Toast.LENGTH_SHORT).show(); download.remove(msg.arg1); nm.cancel(msg.arg1); break; } } } } }
package com.cn.do1.downloadtest; import java.io.ByteArrayInputStream; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.List; import com.cn.do1.downloadtest.service.DownloadService; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; public class DownloadTest extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.down_file); Intent intent = new Intent(this, DownloadService.class); startService(intent); bindListener(); getSingInfo(); } void bindListener() { findViewById(R.id.btn_load_btn_one).setOnClickListener(this); findViewById(R.id.btn_load_btn_two).setOnClickListener(this); findViewById(R.id.btn_load_btn_three).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_load_btn_one: DownloadService .downNewFile( "http://m.appchina.com/market/e/882602/0/16/44DFFDF6E89D0CC2F5CB41CE041E9BB7/packagename.apk?refererPage=m.cherry.soft_list", 351, "百度知道"); break; case R.id.btn_load_btn_two: DownloadService .downNewFile( "http://m.appchina.com/market/e/886657/feature/1/360F5D5A76A3E0E397451CE9EA503DE6/com.sogou.novel?refererPage=m.cherry.soft_main", 1071, "搜狗小说"); break; case R.id.btn_load_btn_three: DownloadService .downNewFile( "http://m.appchina.com/market/e/885495/feature/2/360F5D5A76A3E0E397451CE9EA503DE6/com.king2.yyh?refererPage=m.cherry.soft_main", 1072, "君王2(新服开启)"); break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { System.exit(0); return false; } return super.onKeyDown(keyCode, event); } public void getSingInfo() { try { PackageInfo packageInfo = getPackageManager().getPackageInfo( "com.air.sz", PackageManager.GET_SIGNATURES); Signature[] signs = packageInfo.signatures; Signature sign = signs[0]; parseSignature(sign.toByteArray()); } catch (Exception e) { e.printStackTrace(); } } public void parseSignature(byte[] signature) { try { CertificateFactory certFactory = CertificateFactory .getInstance("X.509"); X509Certificate cert = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(signature)); String pubKey = cert.getPublicKey().toString(); String signNumber = cert.getSerialNumber().toString(); System.out.println("signName:" cert.getSigAlgName()); System.out.println("pubKey:" pubKey); System.out.println("signNumber:" signNumber); System.out.println("subjectDN:" cert.getSubjectDN().toString()); List<String> extendKey = cert.getExtendedKeyUsage(); System.out.println("subjectDN_one:" cert.getSubjectAlternativeNames()); System.out.println("subjectDN_two:" cert.getSubjectX500Principal()); System.out.println("subjectDN_three:" cert.getExtensionValue("SubjectKeyIdentifier")); } catch (CertificateException e) { e.printStackTrace(); } } }
标签: Android
网友评论
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)
支持(0) 盖楼(回复)