Servic与Activity相比它没有界面,主要是在后台执行一些任务,Service有两种启动方法startService()和bindService(),startService方式Service不可交互,可一直在后台即便应用结束,bindService方式可通过ServiceConnection获得运行的Service实例的方式实现Activity和Service之间的交互,通常Activity退出则绑定的服务也就取消了。我们可以通过同时执行启动服务和绑定服务的方式实现Service交互同时又使服务可一直在后台运行直到任务完成,下面我们就使用Service来实现Apk下载任务
实现如图所示效果:
一、编写应用起始界面(CheckUpdateActivity) |
单击“检查版本”执行代码如下:
public void checkUpdate(View view){ //先进行网络版本检查,代码这里不做讲解 showDownload();//转到下载界面 } public void showDownload(){ Intent intent=new Intent(CheckUpdateActivity.this,DownloadActivity.class); startActivity(intent);
}
二、 Activity与Service通信实现App下载(DownloadActivity+DownloadService) |
1、DownloadActivity
1.1先看一下界面
xml文件如下:
<RelativeLayout ...> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="正在下载" android:id="@+id/textView" android:layout_alignParentTop="true" /> <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/pbDownload" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:max="100" android:progress="0" android:indeterminate="false" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止" android:id="@+id/btStop" android:layout_below="@+id/pbDownload" android:layout_alignLeft=