Android四大组件应用系列——Activity与Service交互实现APK下载

  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=
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值