运行效果图:
[img]http://dl.iteye.com/upload/attachment/0084/2194/d16e884c-8c3d-32ac-963d-2ac3e1d54a91.png[/img]
工程结构图:
[img]http://dl.iteye.com/upload/attachment/0084/2198/a8194272-a236-3c74-b9b8-17eb2165d82e.png[/img]
xml:
AndroidManifest.xml
项目源码:
[img]http://dl.iteye.com/upload/attachment/0084/2194/d16e884c-8c3d-32ac-963d-2ac3e1d54a91.png[/img]
工程结构图:
[img]http://dl.iteye.com/upload/attachment/0084/2198/a8194272-a236-3c74-b9b8-17eb2165d82e.png[/img]
package com.cn.do1.downloadtest;
import com.cn.do1.downloadtest.service.DownloadService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
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();
}
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);
}
}
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;
}
}
}
}
}
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="fill_parent"
android:paddingLeft="3dp"
android:paddingRight="3dp" >
<Button
android:id="@+id/btn_load_btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="开始一" />
<Button
android:id="@+id/btn_load_btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_load_btn_one"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dip"
android:text="开始二"
/>
<Button
android:id="@+id/btn_load_btn_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/btn_load_btn_two"
android:layout_marginTop="20dip"
android:text="开始三"
/>
</RelativeLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cn.do1.downloadtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="7" />
<uses-permission android:name="androd.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".DownloadTest">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.cn.do1.downloadtest.service.DownloadService"
android:label="DownloadService"
></service>
</application>
</manifest>
项目源码: