1.Service下載的APK(已驗證)
Service類
public class DownloadService extends Service {
/**
* 安卓系統下載類
**/
DownloadManager manager;
/**
* 接收下載完的廣播
**/
DownloadCompleteReceiver receiver;
/**
* 初始化下載器
**/
private void initDownManager() {
manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
receiver = new DownloadCompleteReceiver();
//設置下載地址
DownloadManager.Request down = new DownloadManager.Request(
Uri.parse("http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk"));
// 設置允許使用的網絡類型,這裏是移動網絡和wifi都可以
down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_WIFI);
// 下載時,通知欄顯示途中
down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
// 顯示下載界面
down.setVisibleInDownloadsUi(true);
// 設置下載後文件存放的位置
down.setDestinationInExternalFilesDir(this,
Environment.DIRECTORY_DOWNLOADS, "baidumusic.apk");
// 將下載請求放入隊列
manager.enqueue(down);
//註冊下載廣播
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 調用下載
initDownManager();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// 註銷下載廣播
if (receiver != null)
unregisterReceiver(receiver);
super.onDestroy();
}
// 接受下載完成後的intent
class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//判斷是否下載完成的廣播
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
//獲取下載的文件id
long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//自動安裝apk
installAPK(manager.getUriForDownloadedFile(downId));//dManager.getUriForDownloadedFile(myDwonloadID);
//停止服務並關閉廣播
stopSelf();
}
}
/**
* 安裝apk文件
*/
private void installAPK(Uri downloadFileUri) {
Intent intents = new Intent();
intents.setAction(Intent.ACTION_VIEW);
intents.setData(downloadFileUri);
intents.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
}
}
}
Actiivity
public class ApkActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent mIntent = new Intent(this,DownloadService.class);
startService(mIntent);
}
}
AndroidManifest.xml註冊service:
<service
android:name="com.example.test.UpdataService"
android:enabled="true"
>
</service>
添加的權限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
2. IntentService下載(已驗證)
public class DownloadIntentService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public DownloadIntentService(String name) {
super(name);
}
public DownloadIntentService() {
super("test-intentService");
}
private NotificationManager notificationManager;
private Notification notification;
private RemoteViews rViews;
@Override
protected void onHandleIntent(Intent intent) {
Bundle bundle = intent.getExtras();
// 獲得下載文件的url
String downloadUrl = bundle.getString("url");
// 設置文件下載後的保存路徑,保存在SD卡根目錄的Download文件夾
File dirs = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download");
// 檢查文件夾是否存在,不存在則創建
if (!dirs.exists()) {
dirs.mkdir();
}
File file = new File(dirs, "file.apk");
// 設置Notification
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.ic_launcher, "版本更新下載", System.currentTimeMillis());
Intent intentNotifi = new Intent(this, ApkActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intentNotifi, 0);
notification.contentIntent = pendingIntent;
// 加載Notification的佈局文件
rViews = new RemoteViews(getPackageName(), R.layout.downloadfile_layout);
// 設置下載進度條
rViews.setProgressBar(R.id.downloadFile_pb, 100, 0, false);
notification.contentView = rViews;
notificationManager.notify(0, notification);
// 開始下載
downloadFile(downloadUrl, file);
// 移除通知欄
notificationManager.cancel(0);
// 廣播出去,由廣播接收器來處理下載完成的文件
Intent sendIntent = new Intent("com.test.downloadComplete");
// 把下載好的文件的保存地址加進Intent
sendIntent.putExtra("downloadFile", file.getPath());
sendBroadcast(sendIntent);
}
private int fileLength, downloadLength;
public void onDestroy() {
// 移除定時器
handler.removeCallbacks(run);
super.onDestroy();
}
// 定時器,每隔一段時間檢查下載進度,然後更新Notification上的ProgressBar
private Handler handler = new Handler();
private Runnable run = new Runnable() {
public void run() {
rViews.setProgressBar(R.id.downloadFile_pb, 100, downloadLength*100 / fileLength, false);
notification.contentView = rViews;
notificationManager.notify(0, notification);
handler.postDelayed(run, 1000);
}
};
private void downloadFile(String downloadUrl, File file){
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// Log.e(TAG, "找不到保存下載文件的目錄");
e.printStackTrace();
}
InputStream ips = null;
try {
URL url = new URL(downloadUrl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("GET");
huc.setReadTimeout(10000);
huc.setConnectTimeout(3000);
fileLength = Integer.valueOf(huc.getHeaderField("Content-Length"));
ips = huc.getInputStream();
// 拿到服務器返回的響應碼
int hand = huc.getResponseCode();
if (hand == 200) {
// 開始檢查下載進度
handler.post(run);
// 建立一個byte數組作爲緩衝區,等下把讀取到的數據儲存在這個數組
byte[] buffer = new byte[8192];
int len = 0;
while ((len = ips.read(buffer)) != -1) {
fos.write(buffer, 0, len);
downloadLength = downloadLength + len;
}
} else {
// Log.e(TAG, "服務器返回碼" + hand);
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (ips != null) {
ips.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ApkActivity extends Activity {
BroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "http://www.appchina.com/market/d/1603385/cop.baidu_0/com.google.android.apps.maps.apk";
Intent downloadIntent = new Intent(this, DownloadIntentService.class);
Bundle bundle = new Bundle();
bundle.putString("url", url);
downloadIntent.putExtras(bundle);
startService(downloadIntent);
// 設置廣播接收器,當新版本的apk下載完成後自動彈出安裝界面
IntentFilter intentFilter = new IntentFilter("com.test.downloadComplete");
receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Intent install = new Intent(Intent.ACTION_VIEW);
String pathString = intent.getStringExtra("downloadFile");
install.setDataAndType(Uri.fromFile(new File(pathString)), "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
};
registerReceiver(receiver, intentFilter);
}
protected void onDestroy() {
// 移除廣播接收器
if (receiver != null) {
unregisterReceiver(receiver);
}
super.onDestroy();
}
}
AndroidManifest.xml註冊service:
<service android:name=“.downloadApk.DownloadIntentService"/>