草庐IT

Android服务(Service)

NoBugException 2023-03-28 原文
一、介绍

Service是一种可在后台执行长时间运行操作而不提供界面的应用组件。服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行。此外,组件可通过绑定到服务与之进行交互,甚至是执行进程间通信 (IPC)。例如,服务可在后台处理网络事务、播放音乐,执行文件 I/O 或与内容提供程序进行交互。

二、3种服务

服务分为三种:前台服务、后台服务、绑定服务

【1】前台服务

前台服务执行一些用户能注意到的操作。
例如,音频应用会使用前台服务来播放音频曲目。
前台服务必须显示通知。即使用户停止与应用的交互,前台服务仍会继续运行。

【2】后台服务

后台服务执行用户不会直接注意到的操作。
例如,如果应用使用某个服务来压缩其存储空间,则此服务通常是后台服务。

【3】绑定服务

当应用组件通过调用 bindService() 绑定到服务时,服务即处于绑定状态。
绑定服务会提供客户端-服务器接口,以便组件与服务进行交互、发送请求、接收结果,
甚至是利用进程间通信 (IPC) 跨进程执行这些操作。仅当与另一个应用组件绑定时,绑定服务才会运行。
多个组件可同时绑定到该服务,但全部取消绑定后,该服务即会被销毁。
三、注册服务

Service需要在清单文件中声明:

<manifest ...>
    <application...>
        <service android:name=".ExampleService"/>
    </application>
</manifest>

ExampleService 是 Service 的子类:

public class ExampleService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}
四、启动服务和停止服务

通过 startService 启动服务:

            // 必须显示启动services
            Intent intent = new Intent(MainActivity.this, ExampleService.class);
            startService(intent);

Intent 必须是显式,否则程序将会报错。

另外,还有一种启动方式,启动前台服务:

startForegroundService() // Android 8.0新增

Android 8.0(API 26)对Service做了一些限制,因为某些限制,新增了 startForegroundService 接口。

API 26 之后,当在前台启动Service时,startService 和 startForegroundService 并没有什么区别。当在后台启动Service时,则必须使用 startForegroundService 接口,将 Service 从后台切换到前台,并且在5秒之内调用自己的 startForeground() 方法。

通过 stopService 可以停止服务:

            Intent intent = new Intent(MainActivity.this, ExampleService.class);
            stopService(intent);

当然,也可以在服务结束的地方执行 stopSelf() 来停止服务。

启动服务之后,服务将在内存中一直运行,直到执行 stopService 或者 stopSelf 停止服务。

五、IntentService

onStartCommand 方法中不能存在耗时操作,否则主线程会被阻塞,甚至可能导致发生crash和ANR。
即使 onStartCommand 执行的不是耗时操作,当多次启动服务,onStartCommand 会被执行多次,这种情况仍然可能导致程序异常或者ANR。
为了保守起见,onStartCommand 的工作应该另起一个线程执行,除非能够保证没有耗时操作。

IntentService 会创建一个作业线程来执行任务,并且还可以保证线程安全,所以可以把 IntentService 做为 Service 的替代方案。

IntentService同样需要在注册:

<manifest ...>
    <application...>
        <service android:name=".HelloIntentService"/>
    </application>
</manifest>

public class HelloIntentService extends IntentService {

    public HelloIntentService() {
        super("HelloIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
    }
}

启动IntentService:

            Intent intent = new Intent(MainActivity.this, HelloIntentService.class);
            startService(intent);

启动IntentService会执行以下操作:

  • 创建默认的工作线程,用于在应用的主线程外执行传递给 onStartCommand() 的所有 Intent。
  • 创建工作队列,用于将 Intent 逐一传递给 onHandleIntent() 实现,这样您就永远不必担心多线程问题。
  • 在处理完所有启动请求后停止服务,因此您永远不必调用 stopSelf()。
  • 提供 onBind() 的默认实现(返回 null)。
  • 提供 onStartCommand() 的默认实现,可将 Intent 依次发送到工作队列和 onHandleIntent() 实现。

IntentService的业务逻辑是在 onHandleIntent 方法中执行的,onHandleIntent 方法执行在工作线程,并且能够保证线程安全,这就是 IntentService 的强大之处了。
IntentService 会自动调用 stopSelf() ,所以不需要主动调用 stopService 或者 stopSelf。但是,因为这个特性,IntentService无法保证让 Service 一直处理Running状态。

六、绑定服务

使用 bindService 绑定服务:

Intent intent = new Intent(MainActivity.this, ExampleService.class);
bindService(intent, serviceConnection, Service.BIND_AUTO_CREATE);

private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        binder = IExampleBinder.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        binder = null;
    }
};

绑定服务后,Service 会自动启动。

解绑服务:

unbindService(serviceConnection);

onBind的返回值不能为null:

public class ExampleService extends Service {

    private class MyBinder extends IExampleBinder.Stub {
        @Override
        public String getName() throws RemoteException {
            return "zhangsan";
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("ExampleService", "==onBind==");
        return new MyBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ExampleService", "==onStartCommand1==");
        return super.onStartCommand(intent, flags, startId);
    }
}

IExampleBinder 是AIDL文件(IExampleBinder.aidl):

interface IExampleBinder {
    String getName();
}
七、新特性

Android 8 之前, 只要调用 startService 就可以启动前台服务和后台服务。

但是,在Android 8.0之后,如果当前程序在后台,就必须启动前台服务 startForegroundService:

startForegroundService(new Intent(getApplicationContext(), RemoteService.class));

启动前台服务之后,必须在5秒之内执行 startForeground 方法:

NotificationChannel channel = new NotificationChannel("persident", "persident", 
NotificationManager.IMPORTANCE_LOW);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, "persident")
            .setAutoCancel(true)
            .setCategory(Notification.CATEGORY_SERVICE)
            .setOngoing(true)
            .setPriority(NotificationManager.IMPORTANCE_LOW).build();
        startForeground(10, notification);

startForeground 的 ID 不能为0。

如要从前台移除服务,请调用 stopForeground()。

Android 9 之后,还需要添加权限:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

[本章完...]

有关Android服务(Service)的更多相关文章

  1. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  2. ruby - 具有身份验证的私有(private) Ruby Gem 服务器 - 2

    我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..

  3. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  4. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  5. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  6. ruby-on-rails - 在 Rails 中调试生产服务器 - 2

    您如何在Rails中的实时服务器上进行有效调试,无论是在测试版/生产服务器上?我试过直接在服务器上修改文件,然后重启应用,但是修改好像没有生效,或者需要很长时间(缓存?)我也试过在本地做“脚本/服务器生产”,但是那很慢另一种选择是编码和部署,但效率很低。有人对他们如何有效地做到这一点有任何见解吗? 最佳答案 我会回答你的问题,即使我不同意这种热修补服务器代码的方式:)首先,你真的确定你已经重启了服务器吗?您可以通过跟踪日志文件来检查它。您更改的代码显示的View可能会被缓存。缓存页面位于tmp/cache文件夹下。您可以尝试手动删除

  7. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  8. ruby - 我的 Ruby IRC 机器人没有连接到 IRC 服务器。我究竟做错了什么? - 2

    require"socket"server="irc.rizon.net"port="6667"nick="RubyIRCBot"channel="#0x40"s=TCPSocket.open(server,port)s.print("USERTesting",0)s.print("NICK#{nick}",0)s.print("JOIN#{channel}",0)这个IRC机器人没有连接到IRC服务器,我做错了什么? 最佳答案 失败并显示此消息::irc.shakeababy.net461*USER:Notenoughparame

  9. ruby - Rails 开发服务器、PDFKit 和多线程 - 2

    我有一个使用PDFKit呈现网页的pdf版本的Rails应用程序。我使用Thin作为开发服务器。问题是当我处于开发模式时。当我使用“bundleexecrailss”启动我的服务器并尝试呈现任何PDF时,整个过程会陷入僵局,因为当您呈现PDF时,会向服务器请求一些额外的资源,如图像和css,看起来只有一个线程.如何配置Rails开发服务器以运行多个工作线程?非常感谢。 最佳答案 我找到的最简单的解决方案是unicorn.geminstallunicorn创建一个unicorn.conf:worker_processes3然后使用它:

  10. ruby-on-rails - 将 Amazon Simple Notification service SNS 与 ruby​​ 结合使用 - 2

    很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visitthehelpcenter.关闭9年前。我需要从基于ruby​​的应用程序使用AmazonSimpleNotificationService,但不知道从哪里开始。您对从哪里开始有什么建议吗?

随机推荐