对于简单的应用程序,很少会需要连接服务器,单机运行就行了。但是当你需要不断更新软件版本,或者你的APP需要用到大量的资源而直接打包进APK文件太大,这时你就需要连接到服务器去下载文件。下面这个项目就提供了如何连接服务器更新APK和如何下载资源的方法。
连接服务器更新APK
服务器上放置一个记录版本号的txt文件,比如version.txt。放置一个用于更新的APK,比如new.apk
final static String strurl = "http://www.xxx.com/my/version.txt"; final static String strurl_apk = "http://www.xxx.com/my/new.apk";
MainActivity的onCreate()方法中调用CheckUpdate()方法
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); ...... CheckUpdate(); // 检查更新 }
连接服务器前当然要先判断网络连接,如果是要下载到SD卡的,还要判断是否有SD卡,判断的代码很简单就不贴上了。
// 检查更新 private void CheckUpdate(boolean isAuto) { // 判断版本号,然后下载 downloader = new HttpDownLoader(); int serverVersion = 1; serverVersion = Integer.parseInt(FusionField.downloader.downLoadText(strurl)); if(serverVersion > localVersion) { AlertDialog.Builder builder = new Builder(this); builder.setTitle("软件升级") .setMessage("发现新版本,是否升级!") .setPositiveButton("升级",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //开启更新服务UpdateService //这里为了把update更好模块化,可以传一些updateService依赖的值 //如布局ID,资源ID,动态获取的标题,这里以app_name为例 Intent updateIntent =new Intent(MainActivity.this, UpdateService.class); startService(updateIntent); } }) .setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } }
UpdateService.class执行后台下载和通知栏下载进度条的更新
public class UpdateService extends Service{ //文件存储 private File updateDir = null; private File updateFile = null; public static String downloadDir = "/download/"; //通知栏 private NotificationManager updateNotificationManager = null; private Notification updateNotification = null;