//下载更新
DownloadManager manager=(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Uri uri=
Uri.parse(Url_Conelect.URL_DOWN_HEAD+DBAdapter.version_new+".apk");
DownloadManager.Request request=
new DownloadManager.Request(uri);
request.setTitle("星语下载中...");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);//在wifi下下载
g_id=manager.enqueue(request);
//更新apk
//
AndroidManifest添加权限和广播
//权限
//android.permission.INTERNET
//android.permission.WRITE_EXTERNAL_STORAGE
//注册广播
<receiver android:name="MyBroadCastReceiver">
<intent-filter >
<action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
<action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/> </intent-filter> </receiver>
//广播服务
public class MyBroadCastReceiver extends BroadcastReceiver{
public MyBroadCastReceiver(){
super();
}
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
DownloadManager manager;
if(action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
//下载完成了
String path=null;
long id=intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
if(id== Liaotian_About.g_id){
DownloadManager.Query query=new DownloadManager.Query();
query.setFilterById(id);
manager=(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
Cursor cursor=manager.query(query);
if(cursor.moveToFirst()){
String string = cursor.getString(cursor.getColumnIndex("local_uri"));
path = string;
if (string == null) {
//---获取不到地址,直接返回
cursor.close();
return;
}
}
cursor.close();
if(path==null)return;
if(path.startsWith("content:")){
//如果得到的路径是内容提供者
cursor=context.getContentResolver().query(Uri.parse(path), null, null, null, null);
if(cursor!=null)
if(cursor.moveToFirst()){
path=cursor.getString(cursor.getColumnIndex("_data"));
if(path!=null){
//获取地址
//打开
File file=new File((path.trim()));
if(file.exists()){
//--
int a=0;
a++;
int b=a;
//--
}
if (Build.VERSION.SDK_INT > 21) {
//版本大于5.0
Uri apkUri = Uri.fromFile(file);
//FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent2 = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent2.setData(apkUri);
intent2.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Main_View.g_Context.startActivity(intent2);
}else{
Intent intent1=new Intent(Intent.ACTION_VIEW);
intent1.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Main_View.g_Context.startActivity(intent1);
}
//--
}
cursor.close();
}
}
}
}else if(action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){
//--清除下载
long id=intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
if(id==Liaotian_About.g_id){
//--下载被取消了
Method_Model.show_Toast(context,"下载被取消了");
}
}
}
}