温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

【三】7认识 Android Service

发布时间:2020-07-28 18:01:19 来源:网络 阅读:746 作者:Sesedese 栏目:移动开发

【一】使用Service


这节课程内容包括:使用Service、绑定Service、Service的生命周期


Activity能够呈现用户界面,与用户进行交互,

而很多时候,我们程序不需要与用户交互,只需要一直在后台运行,

做一些事物处理,例如:Socket长连接、Http网络通信、与服务器保持推送的连接。


如何创建Service?

建一个继承于Service的子类,然后在AndroidManifest.xml中配置即可。

public class MyService extends Service{
    public IBinder onBind(Intent intent){
        throw new UnsupportOperationException("Not yet implemented");
    }
}


<Service
    android:name=".MyService"
    android:enabled="true"
    android:exported="Service"
>
</Service>
  • android:exported —— 是否向外界公开

  • android:enabled —— 是否启用


如何启动Service?

新建一个Button,在MainActivity中给它设置一个事件监听器,然后

startService(new Intent(MainActivity.this,MyService.class));

这样就能启动服务,接下来建一个停止服务的Button,写上

stopService(new Intent(MainActivity.this,MyService.class))

疑问:启动和停止都创建了一个Intent,这两个新创建的Intent实例,是否操作是同一个服务呢?

回答:是同一个服务。因为服务的实例,在操作系统上,只可能有那么一个。

把Intent定义为成员变量,startService和stopService都传入这同一个Intent,效果还是一样的,

因为Intent只是用来配置程序要启动Service的信息的,具体所要操作的Service还是同一个Service。


在"系统设置"-"应用"-"运行中"就可以看我们写的服务是否启动。


现在补充一下,让我们的Service在后台不断执行输出语句,

这需要重写onStartCommand方法:

public class MyService extends Service{

    public IBinder onBind(Intent intent){
        throw new UnsupportOperationException("Not yet implemented");
    }
    
    @Override
    public int onStartCommand(Intent intent,int flags,int startId){
    
        new Thread(){
            public void run(){
                super.run();
                while(true){
                    System.out.println("服务正在运行");
                }
                try{
                    sleep(100);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }.start();
    
    
        return super.onStartCommand(intent,flag,startId);
    }
}

这样,如果启动了服务,就算Activity已经退出,它仍然会在后台执行。


【二】绑定Service


启动Service还能用绑定Service的方式来启动,如何绑定?

在MainActivity加两个Button,一个"BindService",一个"UnBindService"。

它们触发的方法分别是bindService()和unbindService()。


bindService()有三个参数,Intent、服务的连接(用于监听服务的状态,这里传入)、传一个常量Context.BIND_AUTO_CREATE。

第二个参数需要MainActivity实现ServiceConnection接口,需要实现重写以下的方法:

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    Toast.makeText(MainActivity.this, "onServiceConnected", Toast.LENGTH_SHORT).show();
}

@Override
public void onServiceDisconnected(ComponentName name) {

}

onServiceConnected在服务被绑定成功时执行,

onServiceDisconnected在服务所在进行崩溃或被杀掉时被执行。


unbindService()的参数就是this。


接下来执行程序,会发现出错:

java.lang.RuntimeException: Unable to bind to service com.linww.demo.learnservice.MyService@23e111e3 with Intent { cmp=com.linww.demo.learnservice/.MyService }: java.lang.UnsupportedOperationException: Not yet implemented


通过查看发现是onBind这里抛异常,在这方法返回一个Binder()对象就OK了。

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
   // throw new UnsupportedOperationException("Not yet implemented");
    return new Binder();
}


【三】Service的生命周期


服务生命周期只需要记得有 onCreate()和onDestroy()。


规律:同时启动服务并且绑定服务,必须同时停止和解除绑定,服务才能被停止。


如果Activity与某一个Service绑定,那么退出这个Activity,Service也会被取消绑定。


关于onStartCommand()方法,如果Service第一次启动,是onCreate()后执行onStartCommand();

而如果Service已经被启动过了,那么再去启动它,例如点击启动按钮,

则只会执行onStartCommand(),不会重复执行onCreate()。









向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI