Android 之版本更新
来源:互联网 发布:淘宝店铺违规24分 编辑:程序博客网 时间:2024/05/16 06:41
/**
* 查询手机安装的应用
*
* @param context
* @return
*/
- public static List<PackageInfo> getAllNotSystemApps(Context context) {
- List<PackageInfo> apps = new ArrayList<PackageInfo>();
- PackageManager pManager = context.getPackageManager();
- List<PackageInfo> paklist = pManager.getInstalledPackages(0);
- for (int i = 0; i < paklist.size(); i++) {
- PackageInfo pak = (PackageInfo) paklist.get(i);
- if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
- apps.add(pak);
- }
- }
- return apps;
- }
/**
* 判断是否安装过此应用
*
* @param context 上下文
* @param packageName 应用的包名 清单文件
*
* @return
*/
- public static boolean isHaveApp(Context context, String packageName) {
- PackageInfo pa = null;
- List<PackageInfo> packages = getAllNotSystemApps(context);
- for (int i = 0; i < packages.size(); i++) {
- pa = packages.get(i);
- String appPackage = pa.packageName;
- if (appPackage.equals(packageName.trim())) {
- return true;
- }
- }
- return false;
- }
/* 卸载
* packageName 应用的包名 清单文件
*
* */
- public static void uninstallApk(Context context, String packageName) {
- Uri uri = Uri.parse("package:" + packageName);
- Intent intent = new Intent(Intent.ACTION_DELETE, uri);
- context.startActivity(intent);
- }
//得到当前应用的VersionName VersionCode
- private String getVersionName(Context context) {
- String versionName = "";
- try {
- versionName = context.getPackageManager().getPackageInfo(
- context.getApplicationInfo().packageName, 0).versionName;
- versionCode = context.getPackageManager().getPackageInfo(
- context.getApplicationInfo().packageName, 0).versionCode;
- } catch (NameNotFoundException e) {
- e.printStackTrace();
- }
- return versionName;
- }
操作步骤:
1.首先判断是否安装过应用
2.如果安装过应用,就卸载
3.如果没有安装过,就下载更新
/**
* 判断应用是否安装过
*/
boolean haveApp = AppUtil.isHaveApp(this, "com.ideal.wdm.activity");
if (haveApp) {
//如果有就卸载apk
AppUtil.uninstallApk(this, "com.ideal.wdm.activity");
}
getUpate(); //更新下载操作
- private void getUpate(){
- AlertDialog.Builder builder = new Builder(mContext);
- builder.setTitle("升级提示");
- //内容模拟写死
- builder.setMessage("版本:1.0.1\n大小:6.5M\n1、修改Bug\n2、增加功能");
- builder.setNegativeButton("稍后再说", new AlertDialog.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- builder.setPositiveButton("马上跟新", new AlertDialog.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- Intent intent = new Intent(mContext,DownloadService.class);
- //模拟写死
- intent.putExtra("url", "Http://cdn.weibaobiao.com/syy2.apk");
- startService(intent);
- }
- });
- builder.show();
- }
开启服务下载:
- public class DownloadService extends Service{
- public static final String DOWNLOAD_PATH =
- Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloads/";
- public static final String TAG = "download";
- private String url;//下载链接
- private Integer length;//文件长度
- private String fileName=null;//文件名
- private Notification notification;
- private RemoteViews contentView;
- private NotificationManager notificationManager;
- private static final int MSG_INIT = 0;
- private static final int URL_ERROR = 1;
- private static final int NET_ERROR = 2;
- private static final int DOWNLOAD_SUCCESS = 3;
- private Handler mHandler = new Handler(){
- public void handleMessage(android.os.Message msg) {
- switch (msg.what) {
- case MSG_INIT:
- length =(Integer) msg.obj;
- new DownloadThread(url,length).start();
- createNotification();
- break;
- case DOWNLOAD_SUCCESS:
- //下载完成
- notifyNotification(100, 100);
- installApk(DownloadService.this,new File(DOWNLOAD_PATH,fileName));
- Toast.makeText(DownloadService.this, "下载完成", 0).show();
- break;
- case URL_ERROR:
- Toast.makeText(DownloadService.this, "下载地址错误", 0).show();
- break;
- case NET_ERROR:
- Toast.makeText(DownloadService.this, "连接失败,请检查网络设置", 0).show();
- }
- };
- };
- public IBinder onBind(Intent arg0) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- if(intent != null){
- //接收activity传过来的地址:
- url = intent.getStringExtra("url");
- if(url != null && !TextUtils.isEmpty(url)){
- new InitThread(url).start();
- }else{
- mHandler.sendEmptyMessage(URL_ERROR);
- }
- }
- return super.onStartCommand(intent, flags, startId);
- }
- /**
- * 初始化子线程
- * @author dong
- *
- */
- class InitThread extends Thread{
- String url = "";
- public InitThread(String url) {
- this.url = url;
- }
- public void run() {
- HttpURLConnection conn= null;
- RandomAccessFile raf = null;
- try {
- //连接网络文件
- URL url = new URL(this.url);
- conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(3000);
- conn.setRequestMethod("GET");
- int length = -1;
- if(conn.getResponseCode() == HttpStatus.SC_OK){
- //获得文件长度
- length = conn.getContentLength();
- }
- if(length <= 0){
- return;
- }
- File dir = new File(DOWNLOAD_PATH);
- if(!dir.exists()){
- dir.mkdir();
- }
- fileName = this.url.substring(this.url.lastIndexOf("/")+1, this.url.length());
- if(fileName==null && TextUtils.isEmpty(fileName) && !fileName.contains(".apk")){
- fileName = getPackageName()+".apk";
- }
- File file = new File(dir, fileName);
- raf = new RandomAccessFile(file, "rwd");
- //设置文件长度
- raf.setLength(length);
- mHandler.obtainMessage(MSG_INIT,length).sendToTarget();
- } catch (Exception e) {
- mHandler.sendEmptyMessage(URL_ERROR);
- e.printStackTrace();
- } finally{
- try {
- conn.disconnect();
- raf.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * 下载线程
- * @author dong
- *
- */
- class DownloadThread extends Thread{
- String url;
- int length;
- public DownloadThread(String url, int length) {
- this.url = url;
- this.length = length;
- }
- @Override
- public void run() {
- HttpURLConnection conn = null;
- RandomAccessFile raf = null;
- InputStream input = null;
- try {
- URL url = new URL(this.url);
- conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(3000);
- conn.setRequestMethod("GET");
- //设置下载位置
- int start =0;
- conn.setRequestProperty("Range", "bytes="+0+"-"+length);
- //设置文件写入位置
- File file = new File(DownloadService.DOWNLOAD_PATH,fileName);
- raf = new RandomAccessFile(file, "rwd");
- raf.seek(start);
- long mFinished = 0;
- //开始下载
- if(conn.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT){
- //LogUtil.i("下载开始了。。。");
- //读取数据
- input = conn.getInputStream();
- byte[] buffer = new byte[1024*4];
- int len = -1;
- long speed = 0;
- long time = System.currentTimeMillis();
- while((len = input.read(buffer)) != -1){
- //写入文件
- raf.write(buffer,0,len);
- //把下载进度发送广播给Activity
- mFinished += len;
- speed += len;
- if(System.currentTimeMillis() - time > 1000){
- time = System.currentTimeMillis();
- notifyNotification(mFinished,length);
- Log.i(TAG, "mFinished=="+mFinished);
- Log.i(TAG, "length=="+length);
- Log.i(TAG, "speed=="+speed);
- speed = 0;
- }
- }
- mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
- Log.i(TAG, "下载完成了。。。");
- }else{
- Log.i(TAG, "下载出错了。。。");
- mHandler.sendEmptyMessage(NET_ERROR);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally{
- try {
- if(conn != null){
- conn.disconnect();
- }
- if(raf != null){
- raf.close();
- }
- if(input != null ){
- input.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- @SuppressWarnings("deprecation")
- public void createNotification() {
- notification = new Notification(
- R.drawable.ic_launcher,//应用的图标
- "安装包正在下载...",
- System.currentTimeMillis());
- notification.flags = Notification.FLAG_ONGOING_EVENT;
- //notification.flags = Notification.FLAG_AUTO_CANCEL;
- /*** 自定义 Notification 的显示****/
- contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
- contentView.setProgressBar(R.id.progress, 100, 0, false);
- contentView.setTextViewText(R.id.tv_progress, "0%");
- notification.contentView = contentView;
- /*updateIntent = new Intent(this, AboutActivity.class);
- updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
- updateIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
- notification.contentIntent = pendingIntent;*/
- notification.flags = Notification.FLAG_AUTO_CANCEL;
- notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- //设置notification的PendingIntent
- /*Intent intt = new Intent(this, MainActivity.class);
- PendingIntent pi = PendingIntent.getActivity(this,100, intt,Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
- notification.contentIntent = pi;*/
- notificationManager.notify(R.layout.notification_item, notification);
- }
- private void notifyNotification(long percent,long length){
- contentView.setTextViewText(R.id.tv_progress, (percent*100/length)+"%");
- contentView.setProgressBar(R.id.progress, (int)length,(int)percent, false);
- notification.contentView = contentView;
- notificationManager.notify(R.layout.notification_item, notification);
- }
- /**
- * 安装apk
- *
- * @param context 上下文
- * @param file APK文件
- */
- public static void installApk(Context context, File file) {
- Intent intent = new Intent();
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.setAction(Intent.ACTION_VIEW);
- intent.setDataAndType(Uri.fromFile(file),
- "application/vnd.android.package-archive");
- context.startActivity(intent);
- }
- }
notification_item.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="60dp"
- android:orientation="horizontal">
- <ImageView
- android:layout_width="60dp"
- android:layout_height="60dp"
- android:background="@drawable/ic_launcher"/>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- >
- <TextView
- android:layout_centerVertical="true"
- android:padding="5dp"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="安装包正在下载..."
- />
- <TextView
- android:id="@+id/tv_progress"
- android:layout_alignParentRight="true"
- android:padding="5dp"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="0%"
- />
- </RelativeLayout>
- <ProgressBar
- android:padding="5dp"
- android:id="@+id/progress"
- style="?android:attr/progressBarStyleHorizontal"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
- </LinearLayout>
最后清单文件注册和添加权限:
<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"/>
<service android:name="com.example.updateservice.DownloadService"></service>
- Android之版本更新
- Android 之版本更新
- Android之Apk版本更新
- Android笔记之版本更新
- Android功能模块化之版本更新
- Android之版本检测和更新
- android 版本更新之JAR的应用
- Android开发之版本检查更新
- Android 版本更新之增量更新 包含java、.net服务端
- Android 版本更新之增量更新 包含java、.net服务端
- android:versionCode、android:versionName之实现第一次登陆、版本更新
- Android版本更新
- Android SDK版本更新
- Android软件版本更新
- Android 检测版本更新
- Android版本更新实现
- android版本更新问题
- android apk版本更新
- IOS 标准时间与时间戳 相互转化
- 用于linux与开发板之间下载文件的tftp配置详细总结
- linux硬盘分区讲解
- Hadoop2.4.1分布式安装(详细)
- 关于Activity和Fragment的规范使用和系统回收activity的处理
- Android 之版本更新
- IOS-Nsstring
- 多线程技术----最简单的demo开始之linux版
- 解决修改css或js文件,浏览器缓存更新问题。
- 基于ROS_Arduino室内移动机器人SLAM实验测试
- 杭电acm2709
- es小常识1
- Java JDBC批处理插入数据操作
- Local declaration of 'XXX' hides instance variable