import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import androidx.core.app.NotificationCompat;
public class DownloadUtil {
private static final String TAG = "DownloadUtil";
private static DownloadUtil instance;
/**
* 通知的channel id
*/
final static String NOTIFICATION_CHANNEL_ID = "download_apk";
/**
* 通知的id
*/
final static int NOTIFICATION_ID = 0X001;
/**
* 点击之后广播的requestcode
*/
final static int REQUEST_CODE = 0X002;
public static DownloadUtil getInstance() {
if (instance == null) {
instance = new DownloadUtil();
}
return instance;
}
public void downloadApk(Context context, String url, String path) {
new MyAsyncTask(context, path).execute(url);
}
public class MyAsyncTask extends AsyncTask<String, Integer, Integer> {
private Context context;
private NotificationManager notificationManager;
private Notification.Builder notification;
private NotificationCompat.Builder notification1;
private String path;
public MyAsyncTask(Context context, String path) {
this.context = context;
this.path = path;
createNotice(context, path);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Integer doInBackground(String... params) {
Log.e(TAG, "doInBackground: " + params[0]);
InputStream is = null;
OutputStream os = null;
HttpURLConnection connection = null;
int total_length = 0;
try {
URL url1 = new URL(params[0]);
connection = (HttpURLConnection) url1.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(50000);
connection.connect();
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
os = new FileOutputStream(path);
byte[] buf = new byte[1024];
int len;
int pro1 = 0;
int pro2 = 0;
// 获取文件流大小,用于更新进度
long file_length = connection.getContentLength();
while ((len = is.read(buf)) != -1) {
total_length += len;
if (file_length > 0) {
pro1 = (int) ((total_length / (float) file_length) * 100);//传递进度(注意顺序)
}
if (pro1 != pro2) {
// 调用update函数,更新进度
publishProgress(pro2 = pro1);
}
os.write(buf, 0, len);
}
}
} 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 (connection != null) {
connection.disconnect();
}
}
return total_length;
}
@Override
protected void onCancelled(Integer integer) {
super.onCancelled(integer);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.e(TAG, "当前进度" + values[0] + "%");
int progress = values[0];
showNotice(progress);
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
showNotice(100);
Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
}
/**
* 显示通知栏
*/
private void showNotice(int progress) {
if (Build.VERSION.SDK_INT >= 26) {
if (notification != null) {
notification.setProgress(100, progress, false);
notification.setContentText(progress + "%");
if (progress == 100) {
Intent clickIntent = new Intent(context, NotificationClickReceiver.class);
clickIntent.putExtra("path", path);
notification.setContentText("下载完成");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, REQUEST_CODE,
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
}
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, notification.build());
}
}
} else {
//当sdk版本小于26
if (notification1 != null) {
notification1.setProgress(100, progress, false);
notification1.setContentText(progress + "%");
if (progress == 100) {
Intent clickIntent = new Intent(context, NotificationClickReceiver.class);
clickIntent.putExtra("path", path);
notification1.setContentText("下载完成");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, REQUEST_CODE,
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification1.setContentIntent(pendingIntent);
}
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, notification1.build());
}
}
}
}
/**
* 创建初始化通知栏
*/
private void createNotice(Context context, String path) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= 26) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "appname", importance);
notificationManager.createNotificationChannel(channel);
notification = new Notification.Builder(context, NOTIFICATION_CHANNEL_ID)
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentTitle("appname")
.setSmallIcon(R.drawable.umeng_push_notification_default_large_icon)
.setAutoCancel(true);
} else {
notification1 = new NotificationCompat.Builder(context)
.setContentTitle("appname")
.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.umeng_push_notification_default_small_icon)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.umeng_push_notification_default_large_icon))
.setAutoCancel(true);
}
}
}
}
//xml 中注册
<receiver android:name=".apk.NotificationClickReceiver"/>
//写一个接收器
public class NotificationClickReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle= intent.getExtras();
if(bundle!=null){
Toast.makeText(context,"你们自己安装,安装路径"+bundle.getString("path"),Toast.LENGTH_LONG).show();
}else {
Toast.makeText(context,"开始安装吧",Toast.LENGTH_LONG).show();
}
}
}
|