Android实现APP版本自动更新功能

Android实现APP自动更新功能

现在一般的android软件都是需要不断更新的,当你打开某个app的时候,如果有新的版本,它会提示你有新版本需要更新。该小程序实现的就是这个功能。

该小程序的特点是,当有更新时,会弹出一个提示框,点击确定,则在通知来创建一个进度条进行下载,点击取消,则取消更新。

以下是详细代码:

1.创建布局文件notification_item.xml,用于在通知栏生成一个进度条和下载图标。

 

?
1
2
3
4
5
<relativelayout android:layout_height= "fill_parent" android:layout_width= "fill_parent" android:padding= "3dp" xmlns:android= "http://schemas.android.com/apk/res/android" ><imageview android:id= "@+id/notificationImage" android:layout_height= "wrap_content" android:layout_width= "wrap_content" android:src= "@android:drawable/stat_sys_download" ><textview android:id= "@+id/notificationTitle" android:layout_alignparentright= "true" android:layout_height= "wrap_content" android:layout_torightof= "@id/notificationImage" android:layout_width= "wrap_content" android:paddingleft= "6dp" android:textcolor= "#FF000000" ><textview android:id= "@+id/notificationPercent" android:layout_below= "@id/notificationImage" android:layout_height= "wrap_content" android:layout_width= "wrap_content" android:paddingtop= "2dp" android:textcolor= "#FF000000" >
 
     <progressbar android:id= "@+id/notificationProgress" android:layout_alignleft= "@id/notificationTitle" android:layout_alignparentright= "true" android:layout_aligntop= "@id/notificationPercent" android:layout_below= "@id/notificationTitle" android:layout_height= "wrap_content" android:layout_width= "wrap_content" android:paddingleft= "6dp" android:paddingright= "3dp" android:paddingtop= "2dp" style= "@style/ProgressBarHorizontal_color" >
 
</progressbar></textview></textview></imageview></relativelayout>

2.创建AppContext类,该类继承自Application。

 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.test.application;
 
import android.app.Application;
import android.content.Context;
 
import com.test.update.config.Config;
 
public class AppContext extends Application {
     private static AppContext appInstance;
     private Context context;
 
     public static AppContext getInstance() {
         return appInstance;
     }
 
     @Override
     public void onCreate() {
         // TODO Auto-generated method stub
         super .onCreate();
         appInstance = this ;
         context = this .getBaseContext();
//      // 获取当前版本号
//      try {
//          PackageInfo packageInfo = getApplicationContext()
//                  .getPackageManager().getPackageInfo(getPackageName(), 0);
//          Config.localVersion = packageInfo.versionCode;
//          Config.serverVersion = 1;// 假定服务器版本为2,本地版本默认是1
//      } catch (NameNotFoundException e) {
//          e.printStackTrace();
//      }
         initGlobal();
     }
 
     public void initGlobal() {
         try {
             Config.localVersion = getPackageManager().getPackageInfo(
                     getPackageName(), 0 ).versionCode; // 设置本地版本号
             Config.serverVersion = 2 ; // 假定服务器版本为2,本地版本默认是1--实际开发中是从服务器获取最新版本号,android具体与后端的交互见我另///外的博文
         } catch (Exception ex) {
             ex.printStackTrace();
         }
     }
}

3.创建配置文件类Config.java,在这个类里面定义一些与版本相关的常量

 

 

?
1
2
3
4
5
6
7
8
9
10
11
package com.test.update.config;
 
public class Config {
     //版本信息
     public static int localVersion = 0 ;
     public static int serverVersion = 0 ;
     /* 下载包安装路径 */ 
     public static final String savePath = /sdcard/test/; 
   
     public static final String saveFileName = savePath + test.apk; 
}


 

4.编写更新服务类UpdateServcie.java

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package com.test.update;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
 
import com.test.update.config.Config;
 
public class UpdateService extends Service {
     // 标题
     private int titleId = 0 ;
 
     // 文件存储
     private File updateDir = null ;
     private File updateFile = null ;
     // 下载状态
     private final static int DOWNLOAD_COMPLETE = 0 ;
     private final static int DOWNLOAD_FAIL = 1 ;
     // 通知栏
     private NotificationManager updateNotificationManager = null ;
     private Notification updateNotification = null ;
     // 通知栏跳转Intent
     private Intent updateIntent = null ;
     private PendingIntent updatePendingIntent = null ;
     /***
      * 创建通知栏
      */
     RemoteViews contentView;
     // 这样的下载代码很多,我就不做过多的说明
     int downloadCount = 0 ;
     int currentSize = 0 ;
     long totalSize = 0 ;
     int updateTotalSize = 0 ;
 
     // 在onStartCommand()方法中准备相关的下载工作:
     @SuppressWarnings (deprecation)
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
         // 获取传值
         titleId = intent.getIntExtra(titleId, 0 );
         // 创建文件
         if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
                 .getExternalStorageState())) {
             updateDir = new File(Environment.getExternalStorageDirectory(),
                     Config.saveFileName);
             updateFile = new File(updateDir.getPath(), getResources()
                     .getString(titleId) + .apk);
         }
 
         this .updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
         this .updateNotification = new Notification();
 
         // 设置下载过程中,点击通知栏,回到主界面
         updateIntent = new Intent( this , UpdateActivity. class );
         updatePendingIntent = PendingIntent.getActivity( this , 0 , updateIntent,
                 0 );
         // 设置通知栏显示内容
         updateNotification.icon = R.drawable.ic_launcher;
         updateNotification.tickerText = 开始下载;
         updateNotification.setLatestEventInfo( this , QQ, 0 %,
                 updatePendingIntent);
         // 发出通知
         updateNotificationManager.notify( 0 , updateNotification);
 
         // 开启一个新的线程下载,如果使用Service同步下载,会导致ANR问题,Service本身也会阻塞
         new Thread( new updateRunnable()).start(); // 这个是下载的重点,是下载的过程
 
         return super .onStartCommand(intent, flags, startId);
     }
 
     @Override
     public IBinder onBind(Intent arg0) {
         // TODO Auto-generated method stub
         return null ;
     }
 
     @SuppressLint (HandlerLeak)
     private Handler updateHandler = new Handler() {
         @Override
         public void handleMessage(Message msg) {
             switch (msg.what) {
                 
             case DOWNLOAD_COMPLETE:
                 // 点击安装PendingIntent
                 Uri uri = Uri.fromFile(updateFile);
                 Intent installIntent = new Intent(Intent.ACTION_VIEW);
                 installIntent.setDataAndType(uri,
                         application/vnd.android. package -archive);
 
                 updatePendingIntent = PendingIntent.getActivity(
                         UpdateService. this , 0 , installIntent, 0 );
 
                 updateNotification.defaults = Notification.DEFAULT_SOUND; // 铃声提醒
                 updateNotification.setLatestEventInfo(UpdateService. this ,
                         QQ, 下载完成,点击安装。, updatePendingIntent);
                 updateNotificationManager.notify( 0 , updateNotification);
 
                 // 停止服务
                 stopService(updateIntent);
             case DOWNLOAD_FAIL:
                 // 下载失败
                 updateNotification.setLatestEventInfo(UpdateService. this ,
                         QQ, 下载完成,点击安装。, updatePendingIntent);
                 updateNotificationManager.notify( 0 , updateNotification);
             default :
                 stopService(updateIntent);
             }
         }
     };
 
     public long downloadUpdateFile(String downloadUrl, File saveFile)
             throws Exception {
 
         HttpURLConnection httpConnection = null ;
         InputStream is = null ;
         FileOutputStream fos = null ;
 
         try {
             URL url = new URL(downloadUrl);
             httpConnection = (HttpURLConnection) url.openConnection();
             httpConnection
                     .setRequestProperty(User-Agent, PacificHttpClient);
             if (currentSize > 0 ) {
                 httpConnection.setRequestProperty(RANGE, bytes=
                         + currentSize + -);
             }
             httpConnection.setConnectTimeout( 10000 );
             httpConnection.setReadTimeout( 20000 );
             updateTotalSize = httpConnection.getContentLength();
             if (httpConnection.getResponseCode() == 404 ) {
                 throw new Exception(fail!);
             }
             is = httpConnection.getInputStream();
             fos = new FileOutputStream(saveFile, false );
             byte buffer[] = new byte [ 4096 ];
             int readsize = 0 ;
             while ((readsize = is.read(buffer)) > 0 ) {
                 fos.write(buffer, 0 , readsize);
                 totalSize += readsize;
                 // 为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
                 if ((downloadCount == 0 )
                         || ( int ) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) {
                     downloadCount += 10 ;
 
                     updateNotification.setLatestEventInfo(UpdateService. this ,
                             正在下载, ( int ) totalSize * 100 / updateTotalSize
                                     + %, updatePendingIntent);
 
                     
                     /***
                      * 在这里我们用自定的view来显示Notification
                      */
                     updateNotification.contentView = new RemoteViews(
                             getPackageName(), R.layout.notification_item);
                     updateNotification.contentView.setTextViewText(
                             R.id.notificationTitle, 正在下载);
                     updateNotification.contentView.setProgressBar(
                             R.id.notificationProgress, 100 , downloadCount, false );
                     
                     updateNotificationManager.notify( 0 , updateNotification);
                 }
             }
         } finally {
             if (httpConnection != null ) {
                 httpConnection.disconnect();
             }
             if (is != null ) {
                 is.close();
             }
             if (fos != null ) {
                 fos.close();
             }
         }
         return totalSize;
     }
 
     class updateRunnable implements Runnable {
         Message message = updateHandler.obtainMessage();
 
         public void run() {
             message.what = DOWNLOAD_COMPLETE;
             
             
             try {
                 // 增加权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
                 if (!updateDir.exists()) {
                     updateDir.mkdirs();
                 }
                 if (!updateFile.exists()) {
                     updateFile.createNewFile();
                 }
                 // 下载函数,以QQ为例子
                 // 增加权限<uses-permission android:name="android.permission.INTERNET">;
                 long downloadSize = downloadUpdateFile(
                         http: //softfile.3g.qq.com:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk,
                         updateFile);
                 if (downloadSize > 0 ) {
                     // 下载成功
                     updateHandler.sendMessage(message);
                 }
             } catch (Exception ex) {
                 ex.printStackTrace();
                 message.what = DOWNLOAD_FAIL;
                 // 下载失败
                 updateHandler.sendMessage(message);
             }
         }
     }
}
</uses-permission></uses-permission>

5.编写活动类UpdateActivity

 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.test.update;
 
import com.test.update.config.Config;
 
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
 
public class UpdateActivity extends Activity {
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         checkVersion();
     }
 
     /**
      * 检查更新版本
      */
     public void checkVersion() {
 
         if (Config.localVersion < Config.serverVersion) {
             Log.i(hgncxzy, ==============================);
             // 发现新版本,提示用户更新
             AlertDialog.Builder alert = new AlertDialog.Builder( this );
             alert.setTitle(软件升级)
                     .setMessage(发现新版本,建议立即更新使用.)
                     .setPositiveButton(更新,
                             new DialogInterface.OnClickListener() {
                                 public void onClick(DialogInterface dialog,
                                         int which) {
                                     // 开启更新服务UpdateService
                                     // 这里为了把update更好模块化,可以传一些updateService依赖的值
                                     // 如布局ID,资源ID,动态获取的标题,这里以app_name为例
                                     Intent updateIntent = new Intent(
                                             UpdateActivity. this ,
                                             UpdateService. class );
                                     updateIntent.putExtra(titleId,
                                             R.string.app_name);
                                     startService(updateIntent);
                                 }
                             })
                     .setNegativeButton(取消,
                             new DialogInterface.OnClickListener() {
                                 public void onClick(DialogInterface dialog,
                                         int which) {
                                     dialog.dismiss();
                                 }
                             });
             alert.create().show();
         } else {
             // 清理工作,略去
             // cheanUpdateFile()
         }
     }
}

6.添加权限以及将服务静态加载(在配置文件中加载)。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android应用程序的自动更新可以通过以下步骤实现: 1. 在应用程序中添加版本检查功能,以检查当前应用程序版本是否为最新版本。 2. 如果当前应用程序版本不是最新版本,则从服务器下载最新版本的应用程序。 3. 下载完成后,使用Android的PackageInstaller API安装新版本的应用程序。 4. 在应用程序中添加后台服务,以定期检查新版本的应用程序是否可用,并在发现新版本自动下载和安装。 5. 在应用程序中添加设置选项,以允许用户选择是否启用自动更新功能,并设置更新检查的时间间隔。 6. 在应用程序中添加通知功能,以通知用户新版本的应用程序已经下载并准备安装。 以上是Android应用程序自动更新的基本实现步骤。需要注意的是,在实现自动更新功能时,需要确保应用程序的安全性和稳定性,并遵循Google Play Store的开发者政策和规定。 ### 回答2: Android应用自动更新功能对于用户来说是非常方便的,因为可以自动升级应用程序并不需要用户手动下载或更新应用。从开发人员的角度来看,自动更新也可以提高应用程序的可靠性和安全性。 实现Android应用的自动更新,一般需要应用程序具有以下特点: 1.应用程序需要有版本号:在应用程序中设置版本号,可以让应用程序知道当前的版本,从而实现更新。 2.应用程序需要能够获取服务器的最新版本号:一般是通过网络请求(HTTP请求接口)获取服务器的最新版本号。 3.应用程序需要将最新版本号与当前版本号进行比较:如果最新版本号大于当前版本号,则需要进行更新。 4.应用程序需要自动下载最新版本的APK文件:一般是通过下载管理器进行下载。 5.安装最新版本:通过调用系统的安装器来安装最新版本的APK文件。 在实现自动更新的过程中,需要做好以下几方面的工作: 1.确定应用程序的版本号,并与服务器上的版本号保持同步。 2.建立服务器端接口,提供应用程序的版本信息,以供客户端获取。 3.客户端获取最新版本信息后进行比较,根据比较结果决定是否需要更新。 4.下载最新版本的APK文件,并确保下载过程中不出现错误。 5.执行APK文件安装,并确保在安装过程中不出现错误。 总的来说,实现Android应用的自动更新需要对Android开发框架、网络通信、下载、存储、安装等方面有比较深入的了解,需要开发人员具备一定的技术实力。如果需要实现这个功能,可以参考Android开发文档、开源框架或网上的相关教程,以实现自动更新功能。 ### 回答3: Android应用的自动更新是一种很重要的功能,可以方便地向用户推送新版本,并解决了用户手动更新应用的繁琐问题。下面将介绍如何实现Android app自动更新。 1. 获取新版本信息 首先,我们需要在应用服务器上存储最新版本的信息,包括版本号、版本名、更新说明、下载链接等。当用户打开应用时,应用可以向服务器请求最新版本的信息。如果服务器返回的版本号大于当前应用版本号,就说明有新版本,需要更新。否则,应用继续运行。 2. 下载新版本apk 获取新版本信息后,应用需要下载最新版本的apk文件。一般情况下,我们会把apk文件上传到服务器,并返回下载链接。应用可以通过建立HTTP连接来下载apk文件,并保存到本地存储器。下载完毕后,应用需要获取文件头,获取apk文件的版本号和包名。 3. 安装新版本apk 下载完成后,应用需要自动打开安装新版应用。由于apk文件需要具有写操作权限才能被安装,因此需要在AndroidManifest.xml文件中添加读写文件权限。安装时需要调用系统提供的安装接口来完成。调用语句如下: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(f), "application/vnd.android.package-archive"); startActivity(intent); 其中,f是apk文件的File对象。开始安装后,系统会提示用户是否允许应用获取读写权限,如果用户没有允许,安装过程会中断。 4. 其他实现细节 为避免重复下载,可以在服务器端设定最新版本的HASH值,app检查是否有新版本的时候通过HASH检查是否更新。 新版本需要提醒用户更改了什么,这就需要app在服务器端声明release notes,app通过检查新版本的主要变化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值