import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import java.io.File;
public class DownloadManagerHelp {
// http://dworkstudio.com/xalbums/update/update.xml
public static final String BASE_PATH = "/xalbums/download/";
private static final String TAG = DownloadManagerHelp.class.getSimpleName();
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
private String filename = "xalbums.apk";//UpdateVersionTask.APK_NAME;
private Context context;
private DownloadManager downloadManager;
private String uri;
private long downloadId = 0;
private DownloadManagerHelp(Context c) {
this.context = c;
downloadManager = (DownloadManager) c
.getSystemService(Context.DOWNLOAD_SERVICE);
}
private static DownloadManagerHelp instance;
public static DownloadManagerHelp getInstance(Context c) {
if (instance == null) {
instance = new DownloadManagerHelp(c);
}
return instance;
}
private long getDownloadId(String dirType) {
downloadId = 0;
try {
downloadId = downloadManager.enqueue(new DownloadManager.Request(
Uri.parse(uri))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_WIFI)
.setAllowedOverRoaming(false)
.setTitle(context.getString(R.string.app_name))
.setVisibleInDownloadsUi(true)
.setDestinationInExternalPublicDir(dirType, filename));
} catch (Exception e) {
// download failed when download manager was disable, so we need create download thread by us.
FileDownloadThread.getInstance(context).setUrl(uri);
FileDownloadThread.getInstance(context).startDownload();
FLog.i(TAG, "getDownloadId throw error,create download thread by us to try again");
}
return downloadId;
}
private void enableDownloadManager() {
try {
//Open the specific App Info page:
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
context.startActivity(intent);
} catch (ActivityNotFoundException ex) {
ex.printStackTrace();
//Open the generic Apps page:
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
context.startActivity(intent);
}
}
public void startDownload() {
if (downloadManager != null) {
FLog.i(TAG, "downlaod strat.");
UserSetting.setBoolean(context, Constants.DOWNLOAD_START, true);
// 解决K900无法自动升级问题
downloadId = getDownloadId(BASE_PATH);
context.registerReceiver(downloadReceiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor c = downloadManager.query(query);
if (c != null && c.moveToFirst()) {
int status = c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS));
String filename = c.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
switch (status) {
case DownloadManager.STATUS_PAUSED:
case DownloadManager.STATUS_PENDING:
case DownloadManager.STATUS_RUNNING:
case DownloadManager.STATUS_SUCCESSFUL:
File file = new File(filename);
FLog.i("download", "filename:" + filename);
installApk(file);
break;
case DownloadManager.STATUS_FAILED:
stopDownload();
break;
}
}
if (c != null) {
c.close();
}
}
};
protected void installApk(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
FLog.i(TAG, "downlaod ok ,and install the application.");
}
public void stopDownload() {
if (downloadId != 0) {
downloadManager.remove(downloadId);
context.unregisterReceiver(downloadReceiver);
downloadId = 0;
}
}
}
2:
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.RemoteViews;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
@SuppressLint(“NewApi”)
public class FileDownloadThread extends Thread {
private String url;
private String path = Constants.ROOT_PATH;
private String savePath = path + "xalbums.apk";
private boolean run = false;
private final static int DOWNLOAD_ID = 201;
private Context mContext;
private Notification.Builder builder;
private NotificationManager manager;
private FileDownloadThread(Context context) {
this.mContext = context;
manager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new Notification.Builder(mContext);
}
private static FileDownloadThread instance = null;
public static FileDownloadThread getInstance(Context context) {
if (instance == null) {
instance = new FileDownloadThread(context);
}
return instance;
}
public void sendNotification(int progress, boolean isSuccess) {
RemoteViews rv = new RemoteViews(mContext.getPackageName(),
R.layout.download_notification);
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date d1 = new Date();
String t1 = format.format(d1);
Intent appIntent = new Intent(Intent.ACTION_MAIN);
appIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appIntent.setComponent(new ComponentName(mContext.getPackageName(),
"com.lenovo.linkit.HomeActivity"));
appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent mainPiIntent = PendingIntent.getActivity(mContext, 0,
appIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(mainPiIntent);
builder.setContentTitle(mContext
.getString(R.string.update_download_title));
builder.setSmallIcon(R.drawable.ic_launcher);
String text = String.format("%2d", progress) + "%";
rv.setTextViewText(R.id.notification_desc, text);
builder.setContentText(text);
builder.setWhen(System.currentTimeMillis());
builder.setOngoing(false);
rv.setTextViewText(R.id.notification_title,
mContext.getString(R.string.update_download_title));
if (progress != 100 && isSuccess) {
rv.setViewVisibility(R.id.content_view_progress, View.VISIBLE);
rv.setViewVisibility(R.id.notification_desc, View.GONE);
builder.setOngoing(true);
rv.setProgressBar(R.id.content_view_progress, 100, progress, false);
} else if (isSuccess) {
rv.setViewVisibility(R.id.notification_desc, View.VISIBLE);
rv.setViewVisibility(R.id.content_view_progress, View.GONE);
rv.setTextViewText(R.id.notification_desc,
mContext.getString(R.string.update_download_ok_start_install));
} else {
rv.setViewVisibility(R.id.notification_desc, View.VISIBLE);
rv.setViewVisibility(R.id.content_view_progress, View.GONE);
rv.setTextViewText(R.id.notification_desc,
mContext.getString(R.string.update_download_faile_please_retry));
}
rv.setTextViewText(R.id.notification_time, t1);
builder.setContent(rv);
builder.setTicker(mContext.getString(R.string.update_download_title));
Notification notification = builder.build();
notification.contentView = rv;
manager.notify(DOWNLOAD_ID, notification);
}
public void startDownload() {
if (run == false) {
new Thread(this).start();
}
}
@Override
public void run() {
super.run();
URL u;
try {
run = true;
sendNotification(0, true);
u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(5000);
double fileSize = conn.getContentLength();
InputStream is = conn.getInputStream();
File pathFile = new File(path);
if (!pathFile.exists()) {
pathFile.mkdir();
}
File file = new File(savePath);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
double total = 0;
double pcent = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total += len;
double percent = (int) ((total * 100 / fileSize));
if (percent - pcent >= 1.0) {
pcent = percent;
sendNotification((int) percent, true);
}
}
sendNotification(100, true);
fos.close();
bis.close();
is.close();
installApk(file);
manager.cancel(DOWNLOAD_ID);
run = false;
} catch (Exception e) {
run = false;
sendNotification(0, false);
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
protected void installApk(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
mContext.startActivity(intent);
}
}
public class Constants {
public static final String ENTRY_ALL_PHOTO_FRAGMENT_NULL = "entry_all_photo_fragment_null" ;
public static final String ENTRY_ALL_PHOTO_FRAGMENT_BIG_SIZE = "entry_all_photo_fragment_big_size" ;
public static final String ENTRY_ALL_PHOTO_FRAGMENT_SIMILAR = "entry_all_photo_fragment_similar" ;
public static final String ENTRY_ALL_PHOTO_FRAGMENT_NO_USE = "entry_all_photo_fragment_no_use" ;
public static final String FULL_REMIND_CLOSED = "full_remind_closed";
public static final String RIGHT_REMIND_CLOSED = "right_remind_closed";
public static final String FULL_REMIND_FIRST_SHOW = "full_remind_first_show";
public static final String RIGHT_REMIND_FIRST_SHOW = "right_remind_first_show";
public static final String APPLICATION_FRIST_ARRANGE = "application_frist_arrange";
}
重点内容