android 原生的DownloadManager
代码:
public class MainActivity extends Activity {
private DownloadManager downloadManager;
public static final String DOWNLOAD_FOLDER_NAME = "Trinea";
public static final String DOWNLOAD_FILE_NAME = "MeiLiShuo.apk";
public static final String APK_URL = "http://img.meilishuo.net/css/images/AndroidShare/Meilishuo_3.6.1_10006.apk";
public static final String KEY_NAME_DOWNLOAD_ID = "downloadId";
private long downloadId = 0;
private CompleteReceiver completeReceiver;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
File folder = Environment
.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);
if (!folder.exists() || !folder.isDirectory()) {
folder.mkdirs();
}
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(APK_URL));
request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME,
DOWNLOAD_FILE_NAME);
request.setTitle("美丽传说");
request.setDescription("meilishuo desc");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(false);
// request.allowScanningByMediaScanner();
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
// request.setShowRunningNotification(false);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
//application/cn.trinea.download.file
request.setMimeType("application/vnd.android.package-archive");
downloadId = downloadManager.enqueue(request);
/** save download id to preferences **/
}
});
}
private void init() {
// TODO Auto-generated method stub
completeReceiver = new CompleteReceiver();
/** register download success broadcast **/
registerReceiver(completeReceiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
}
private int getInt(long downloadId, String columnName) {
DownloadManager.Query query = new DownloadManager.Query()
.setFilterById(downloadId);
int result = -1;
Cursor c = null;
try {
c = downloadManager.query(query);
if (c != null && c.moveToFirst()) {
result = c.getInt(c.getColumnIndex(columnName));
}
} finally {
if (c != null) {
c.close();
}
}
return result;
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(completeReceiver);
}
class CompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/**
* get the id of download which have download success, if the id is
* my id and it's status is successful, then install it
**/
long completeDownloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (completeDownloadId == downloadId) {
// if download successful, install apk
// if (downloadManagerPro.getStatusById(downloadId) ==
// DownloadManager.STATUS_SUCCESSFUL) {
if (getInt(downloadId, DownloadManager.COLUMN_STATUS) == DownloadManager.STATUS_SUCCESSFUL) {
String apkFilePath = new StringBuilder(Environment
.getExternalStorageDirectory().getAbsolutePath())
.append(File.separator)
.append(DOWNLOAD_FOLDER_NAME)
.append(File.separator).append(DOWNLOAD_FILE_NAME)
.toString();
install(context, apkFilePath);
}
}
}
};
/**
* install app
*
* @param context
* @param filePath
* @return whether apk exist
*/
public static boolean install(Context context, String filePath) {
Intent i = new Intent(Intent.ACTION_VIEW);
File file = new File(filePath);
if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
i.setDataAndType(Uri.parse("file://" + filePath),
"application/vnd.android.package-archive");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
return true;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
清单文件里的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
但是在做系统适配的时会出问题,上面的这种不支持低版本的,所以自己写service来后台更新
/**
* 更新apk
*
* @author jian.zhou test
*/
@SuppressLint("HandlerLeak")
public class UpdateService extends Service {
private static final int DOWN_OK = 1;
private static final int DOWN_ERROR = 0;
private String app_name;
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
private int notification_id = 0;
protected FinalHttp finalHttp; @Override
public IBinder onBind(Intent arg0) {
return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
finalHttp = new FinalHttp();
app_name=intent.getStringExtra("app_name");
createNotification();
createThread();
return super.onStartCommand(intent, flags, startId); } Handler handler = new Handler() {
@SuppressWarnings("deprecation")
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWN_OK:
Uri uri = Uri.fromFile(new File(FileUtlis.getSDKPath()
+ app_name));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri,
"application/vnd.android.package-archive");
pendingIntent = PendingIntent.getActivity(UpdateService.this,
0, intent, 0);
contentViews.setTextViewText(R.id.notificationTitle,
"下载完成!点击安装");
mBuilder.setContentIntent(pendingIntent);
notificationManager.notify(notification_id, mBuilder.build());
stopService(new Intent("mmdops.services.UpdateService"));
break;
case DOWN_ERROR:
contentViews.setTextViewText(R.id.notificationTitle, "下载失败!");
notificationManager.notify(notification_id, mBuilder.build());
break; default:
stopService(new Intent("mmdops.services.UpdateService"));
break;
}
}
}; /***
* 开线程下载
*/
public void createThread() {
String path = FileUtlis.createFile(app_name);
Logger.e("PATH---->"+path);
finalHttp.download(Cants.HTTP_DOWN_APK, path, new AjaxCallBack<File>() { @Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Logger.e("----------->下载开始!");
} @Override
public void onLoading(long count, long current) {
// TODO Auto-generated method stub
super.onLoading(count, current);
Logger.e("----------->下载...");
contentViews.setProgressBar(R.id.notificationProgress,
(int) count, (int) current, false);
// show_view
notificationManager.notify(notification_id, mBuilder.build());
} @Override
public void onSuccess(File t) {
// TODO Auto-generated method stub
super.onSuccess(t);
Logger.e("----------->下载onSuccess!");
handler.obtainMessage(DOWN_OK).sendToTarget();
} @Override
public void onFailure(Throwable t, int errorNo, String strMsg) {
// TODO Auto-generated method stub
super.onFailure(t, errorNo, strMsg);
handler.obtainMessage(DOWN_ERROR).sendToTarget();
}
});
} /***
* 创建通知栏
*/
private RemoteViews contentViews;
private NotificationCompat.Builder mBuilder; public void createNotification() { contentViews = new RemoteViews(getPackageName(),
R.layout.notification_item);
contentViews.setTextViewText(R.id.notificationTitle, "正在下载");
contentViews.setProgressBar(R.id.notificationProgress, 100, 0, false); Intent intent = new Intent(this, LoginActivity.class);
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder = new NotificationCompat.Builder(this).setSmallIcon(
R.drawable.logo_jm).setTicker("后台更新中");
mBuilder.setAutoCancel(true); mBuilder.setContentIntent(pendingIntent);
mBuilder.setContent(contentViews);
mBuilder.setAutoCancel(true); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification_id, mBuilder.build());
} }
android 原生的DownloadManager的更多相关文章
- 拓展 Android 原生 CountDownTimer 倒计时
拓展 Android 原生 CountDownTimer 倒计时 [TOC] CountDownTimer 在系统的CountDownTimer上进行的修改,主要是拓展了功能,当然也保留了系统默认的模 ...
- Android原生json和fastjson的简单使用
android原生操作json数据 主要是两个类 JSONObject 操作对象 JONSArray操作json数组 对象转json //创建学生对象 Student student=new ...
- Android原生游戏开发:使用JustWeEngine开发微信打飞机
使用JustWeEngine开发微信打飞机: 作者博客: 博客园 引擎地址:JustWeEngine 示例代码:EngineDemo JustWeEngine? JustWeEngine是托管在Git ...
- android原生ExpandableListView
android原生可扩展ExpandableListView就是可以伸缩的listView,一条标题下面有多条内容. 这个list的adapter对的数据要求与普通ListView的数据要求也有一些差 ...
- [Android Pro] android 4.4 Android原生权限管理:AppOps
reference : http://m.blog.csdn.net/blog/langzxz/45308199 reference : http://blog.csdn.net/hyhyl1990/ ...
- 【android原生应用】之闹钟应用搭起篇
由于工作原因接触android开发一段时间了,对于开发有了一些了解,于是萌生了搭起android原生应用进行分析和学习的想法.先从闹钟应用开始吧. 1.首先要下载原生应用,原生应用在原生系统里面(当然 ...
- PhoneGap或者Cordova框架下实现Html5中JS调用Android原生代码
PhoneGap或者Cordova框架下实现Html5中JS调用Android原生代码 看看新闻网>看引擎>开源产品 0人收藏此文章, 发表于8小时前(2013-09-06 00:39) ...
- Android 原生listview item伸展收缩效果
Android原生listview做的一个item的伸缩效果.*永远不要让你老大有机会改需求 package com.example.yunkanglast; import java.io.Seria ...
- Android原生APP内分享
Android原生APP内分享,可实现数据分享以及assets文件夹分享及私有文件分享 项目地址:https://github.com/json-pu/AndroidAppShare.git
随机推荐
- winform/wpf 程序部署
(1):一些发布方式 ClickOnce是什么玩意儿,这个问题嘛,在21世纪的互联网严重发达的时代,估计也没有必要大费奏章去介绍了,弄不好的话,还有抄袭之嫌.因此,有关ClickOnce的介绍,各位朋 ...
- Unlocker(强力删除文件工具) 1.9.2 汉化绿色版
软件名称: Unlocker(强力删除文件工具) 1.9.2 汉化绿色版软件语言: 简体中文授权方式: 免费软件运行环境: Win7 / Vista / Win2003 / WinXP 软件大小: 5 ...
- 2015 Multi-University Training Contest 9
1001 Expression 式子不好推啊.见官方题解. 式子知道就方便了.处理好组合数和阶乘. 按区间长度从小到大递推完就好. # include <iostream> # inclu ...
- 依赖跟踪如何工作的(How dependency tracking works)
这一块主要是理论的讲解,本人刚接触这块不久,就不敢翻译了,请参见园子里其他人的现有文章 http://www.cnblogs.com/TomXu/archive/2011/11/22/2256820. ...
- MySql 安装报错 :Last Error:Unable to update security. Access denied for user 'root'@'localhost(useing password:YES)
在网上查了一下,其实这个问题很好解决,. try again 然后current password mysql是默认密码为空,不要填,记住不要填就ok了
- 如何通过Maven的Jetty插件运行Web工程
首先建议使用jetty9,因为据官方文档显示,Jetty 7 and Jetty 8 are now EOL (End of Life),如下.但是由于项目使用的版本一般都比较低,这里以jetty8为 ...
- Android:如何实现更换主题
关键代码:setTheme(int ID); 注意点: 1.设置主题必须要在setContentView() 之前调用,所以需要写个Intent去重新开启Activity. 2.为了切换主题保证流畅性 ...
- FTP、TFTP
FTP 文件传送协议 (File Transfer Protocol) FTP是因特网上使用得最广泛的文件传送协议. 文件传送协议 FTP (File Transfer Protocol) 是因 ...
- VBS基础篇 - 循环语句(4) - For Each...Next
VBS基础篇 - 循环语句(4) - For Each...Next For Each...Next 循环与 For...Next 循环类似.For Each...Next 不是将语句运行指定的次 ...
- WebViewJavascriptBridge详细使用
前言 WebViewJavascriptBridge是支持到iOS6之前的版本的,用于支持native的iOS与javascript交互.如果需要支持到iOS6之前的app,使用它是很不错的.本篇讲讲 ...