您的位置:首页 > 其它

下载APk,并在通知栏显示下载进度(两种方式)

2016-05-04 11:27 721 查看

第一种方法:通过异步任务类实现

1.布局文件

布局很简单,写个点击下载的按钮就行

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ygd.jreduch09.DownloadActivity">
<Button
android:id="@+id/download"
android:layout_alignParentBottom="true"
android:text="下载"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</RelativeLayout>


2.主函数

public class DownloadActivity extends AppCompatActivity {
public Button download;
private NotificationManager nm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);

nm= (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
download= (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url= UrlManager.APK_LOCAL;
new MyDownloadAnsy().execute(url);
}
});
}

public class MyDownloadAnsy extends AsyncTask<String,Integer,Integer>{

@Override
protected Integer doInBackground(String... params) {
HttpURLConnection con=null;
InputStream is=null;
OutputStream os=null;
try {
URL url=new URL(params[0]);
con= (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5*1000);  //设置超时时间
if(con.getResponseCode()==200){ //判断是否连接成功
int fileLength = con.getContentLength();
is=con.getInputStream();    //获取输入
os = new FileOutputStream("/sdcard/weixin.apk");
byte[] buffer=new byte[1024*1024*10];
long total=0;
int count;
while ((count=is.read(buffer))!=-1){
total+=count;
if (fileLength > 0)
publishProgress((int) (total * 100 / fileLength));  //传递进度(注意顺序)
os.write(buffer,0,count);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if(con!=null){
con.disconnect();
}
}
return 1;
}

@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);

if(result==1){
Toast.makeText(DownloadActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
}

@Override
protected void onProgressUpdate(Integer... values) {
Log.d("===",""+values[0]);
super.onProgressUpdate(values);
NotificationCompat.Builder builder= new NotificationCompat.Builder(getBaseContext()).setProgress(100,values[0],false).setSmallIcon(R.mipmap.ic_launcher).setContentInfo("下载中...").setContentTitle("正在下载");
Notification nf=builder.build();
nm.notify(0,nf);
if(values[0]==100) {    //下载完成后点击安装
Intent it = new Intent(Intent.ACTION_VIEW);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
it.setDataAndType(Uri.parse("file:///sdcard/weixin.apk"), "application/vnd.android.package-archive");
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle("下载完成").setContentText("点击安装").setContentIntent(pendingIntent);
nf = builder.build();
nm.notify(0, nf);
}
}
}
}


3.运行前不要忘了加网络权限和读写sd卡权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


第二种方法:使用系统服务来实现

注:不是所有的手机版本都支持第二种方法,所以不是很推荐使用!

1.布局文件还跟上面一样

2.主函数

public class Download2Activity extends AppCompatActivity {

private Button download;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download2);

download= (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
downLoad();
}
});
}

public void downLoad(){
//取得系统的下载服务
DownloadManager downloadManager= (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
String downUrl= UrlManager.APK_LOCAL;
//创建下载请求对象
DownloadManager.Request request=new DownloadManager.Request(Uri.parse(downUrl));
request.setDestinationInExternalPublicDir("/"+getPackageName()+"/","test.apk");
request.setNotificationVisibility(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadManager.enqueue(request);

}
}


3.加权限

第一种方法优化:

由于老是在调用publishProgress(),导致程序非常卡,所以我做了如下改进:

public class DownloadActivity extends AppCompatActivity {
public Button download;
private NotificationManager nm;
private NotificationCompat.Builder builder;
private Notification nf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);

nm= (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
download= (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url= UrlManager.APK_LOCAL;
new MyDownloadAnsy().execute(url);
}
});
}

public class MyDownloadAnsy extends AsyncTask<String,Integer,Integer>{

@Override
protected void onPreExecute() {
super.onPreExecute();
builder= new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.mipmap.ic_launcher).setContentInfo("下载中...").setContentTitle("正在下载");
nf=builder.build();
}

@Override
protected Integer doInBackground(String... params) {
HttpURLConnection con=null;
InputStream is=null;
OutputStream os=null;
try {
URL url=new URL(params[0]);
con= (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5*1000);  //设置超时时间
if(con.getResponseCode()==200){ //判断是否连接成功
int fileLength = con.getContentLength();
is=con.getInputStream();    //获取输入
os = new FileOutputStream("/sdcard/weixin.apk");
byte[] buffer=new byte[1024*1024*10];
long total=0;
int count;
int pro1=0;
int pro2=0;
while ((count=is.read(buffer))!=-1){
total+=count;
if (fileLength > 0)
pro1=(int) (total * 100 / fileLength);  //传递进度(注意顺序)
if(pro1!=pro2)
publishProgress(pro2=pro1);
os.write(buffer,0,count);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if(con!=null){
con.disconnect();
}
}
return 1;
}

@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);

if(result==1){
Toast.makeText(DownloadActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
}

@Override
protected void onProgressUpdate(Integer... values) {
Log.d("===",""+values[0]);
super.onProgressUpdate(values);
builder.setProgress(100,values[0],false);
nf=builder.build();
nm.notify(0,nf);
if(values[0]==100) {    //下载完成后点击安装
Intent it = new Intent(Intent.ACTION_VIEW);
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
it.setDataAndType(Uri.parse("file:///sdcard/weixin.apk"), "application/vnd.android.package-archive");
PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle("下载完成").setContentText("点击安装").setContentIntent(pendingIntent);
nf = builder.build();
nm.notify(0, nf);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: