湖北建设网站四库一平台,精准扶贫网站建设目的,微信网页版怎么扫描二维码,遵义在线新闻1、Service介绍
Android Service#xff08;服务#xff09;是 Android 四大组件之一#xff0c;主要作用是执行后台操作。它是一个后台运行的组件#xff0c;执行长时间运行且不需要用户交互的任务。即使应用被销毁也依然可以工作。 Service并不是运行在一个独立的进程当…1、Service介绍
Android Service服务是 Android 四大组件之一主要作用是执行后台操作。它是一个后台运行的组件执行长时间运行且不需要用户交互的任务。即使应用被销毁也依然可以工作。 Service并不是运行在一个独立的进程当中的而是依赖于创建Service时所在的应用程序进程。当某个应用程序进程被杀掉时所有依赖于该进程的Service也会停止运行。 服务基本上包含两种状态
Started当 Android 的应用程序组件如活动通过 startService() 启动了服务则服务是 Started 状态。一旦启动服务可以在后台无限期运行即使启动它的组件已经被销毁。Bound当 Android 的应用程序组件通过 bindService() 绑定了服务则服务是 Bound 状态。Bound 状态的服务提供了一个客户服务器接口来允许组件与服务进行交互如发送请求获取结果甚至通过 IPC 来进行跨进程通信。
服务拥有生命周期方法可以实现监控服务状态的变化可以在合适的阶段执行工作。例如onStartCommand() 方法会在其他组件如活动通过调用 startService() 来请求启动服务时被系统调用。
要创建服务你需要创建一个继承自 Service 基类或者它的已知子类的 Java 类。例如下面是一个简单的 Service 类的示例
public class MyService extends Service {Overridepublic void onCreate() {// 服务被创建时调用}Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// 其他组件通过调用 startService() 来请求启动服务时系统调用该方法return super.onStartCommand(intent, flags, startId);}NullableOverridepublic IBinder onBind(Intent intent) {// 当其他组件想要通过 bindService() 来绑定服务时系统调用该方法return null;}Overridepublic boolean onUnbind(Intent intent) {// 当客户中断所有服务发布的特殊接口时系统调用该方法return super.onUnbind(intent);}Overridepublic void onDestroy() {// 当服务不再有用或者被销毁时系统调用该方法}
}与之对应的Kotlin代码如下
class MyService : Service() {// 当其他组件通过bindService来绑定服务时被调用override fun onBind(intent: Intent): IBinder {// 返回一个IBinder对象TODO()}// 在Service被创建时调用override fun onCreate() {super.onCreate()}// 当其他组件通过startService来请求启动Service时该方法被调用override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {return super.onStartCommand(intent, flags, startId)}// 当服务不再有用或者被销毁时系统调用该方法override fun onDestroy() {super.onDestroy()}// 当客户中断所有服务发布的特殊接口时系统调用该方法override fun onUnbind(intent: Intent?): Boolean {return super.onUnbind(intent)}
}onCreate()方法是在Service第一次创建的时候调用的而onStartCommand()方法则在每次启动Service的时候都会调用。
2、异步消息处理机制
Android的异步消息处理主要由以下四个部分组成Message、Handler、MessageQueue和Looper。 MessageMessage是在线程之间传递的消息它可以携带少量的信息用于在不同线程之间传递数据。我们可以使用Message的what、arg1、arg2字段来携带整型数据或者使用obj字段来携带一个Object对象。 HandlerHandler主要用于发送和处理消息。我们可以使用Handler的sendMessage()、post()等方法来发送消息发送出的消息会最终传递到Handler的handleMessage()方法中进行处理。 MessageQueueMessageQueue是消息队列主要用于存放所有通过Handler发送的消息。这些消息会一直存在于消息队列中等待被处理。每个线程中只会有一个MessageQueue对象。 LooperLooper是每个线程中的MessageQueue的管家当调用Looper的loop()方法后就会进入一个无限循环中。每当发现MessageQueue中存在一条消息时就会将它取出并传递到Handler的handleMessage()方法中。每个线程中只会有一个Looper对象。
异步消息处理的整个流程首先在主线程中创建一个Handler对象并重写handleMessage()方法。然后当子线程需要进行UI操作时创建一个Message对象并通过Handler将这条消息发送出去。这条消息会被添加到MessageQueue的队列中等待被处理。而Looper则会一直尝试从MessageQueue中取出待处理消息最后分发回Handler的handleMessage()方法中。由于在Handler的构造函数中我们传入了Looper.getMainLooper()所以此时handleMessage()方法中的代码会在主线程中运行这样我们就可以在这里进行UI操作了。
class MainActivity : AppCompatActivity() {private val updateText 1 // 用于标识哪个动作private lateinit var textView: TextView// Handler顾名思义也就是处理者的意思它主要是用于发送和处理消息的。发送消息一般//是使用Handler的sendMessage()方法、post()方法等而发出的消息经过一系列地辗//转处理后最终会传递到Handler的handleMessage()方法中private val handler object : Handler(Looper.getMainLooper()){override fun handleMessage(msg: Message) {// 在主线程中进行UI操作when(msg.what){updateText - textView.text msg.obj.toString()}}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)textView findViewByIdTextView(R.id.textView)val changeTextBtn findViewByIdButton(R.id.changeTextBtn)changeTextBtn.setOnClickListener{// 开启一个新的线程thread {// Message是在线程之间传递的消息它可以在内部携带少量的信息用于在不同线程之间传递数据val message Message()message.what updateTextmessage.arg1 1 // 携带整型数据message.arg2 2message.obj 你好啊 // 携带对象类型数据// 发送Message对象handler.sendMessage(message)// 通过post方法发送一个 Runnable 对象这个 Runnable 对象会被添加到消息队列的尾部handler.post(Runnable { Log.d(Handler, post) })}}}
}3、Service的使用
例如一个后台下载服务的简单实现
class MyService : Service() {private val mBinder DownloadBinder()// 当其他组件通过bindService来绑定服务时被调用override fun onBind(intent: Intent): IBinder {// 返回一个IBinder对象return mBinder}// 在Service被创建时调用override fun onCreate() {super.onCreate()}// 当其他组件通过startService来请求启动Service时该方法被调用override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {return super.onStartCommand(intent, flags, startId)}// 当服务不再有用或者被销毁时系统调用该方法override fun onDestroy() {super.onDestroy()}// 当客户中断所有服务发布的特殊接口时系统调用该方法override fun onUnbind(intent: Intent?): Boolean {return super.onUnbind(intent)}class DownloadBinder : Binder() {fun startDownload() {Log.d(MyService, startDownload executed)}fun getProgress(): Int {Log.d(MyService, getProgress executed)return 0}}
}class MainActivity2: AppCompatActivity(){private lateinit var mBinder: MyService.DownloadBinder// ServiceConnection用于监听服务的状态, 以便于在服务绑定成功时执行相应的逻辑private val connection object : ServiceConnection {override fun onServiceConnected(name: ComponentName?, service: IBinder?) {mBinder service as MyService.DownloadBindermBinder.startDownload()mBinder.getProgress()}override fun onServiceDisconnected(name: ComponentName?) {}}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)// 启动服务findViewByIdButton(R.id.startServiceBtn).setOnClickListener {val intent Intent(this, MyService::class.java)startService(intent)}// 停止服务findViewByIdButton(R.id.stopServiceBtn).setOnClickListener {val intent Intent(this, MyService::class.java)stopService(intent)}// 绑定服务,这样Activity和Service就建立了关联findViewByIdButton(R.id.bindServiceBtn).setOnClickListener {val intent Intent(this, MyService::class.java)// 传入参数intent, ServiceConnection, flags// flags一般传入BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建ServicebindService(intent, connection, BIND_AUTO_CREATE)}// 解绑服务findViewByIdButton(R.id.unbindServiceBtn).setOnClickListener {unbindService(connection)}}
}4、前台Service
从Android 8.0系统开始只有当应用保持在前台可见状态的情况下Service 才能保证稳定运行一旦应用进入后台之后Service随时都有可能被系统回收。而如果你希望Service能够一直保持运行状态就可以考虑使用前台Service。前台Service和普通Service最大的区别就在于它一直会有一个正在运行的图标在系统的状态栏显示下拉状态栏后可以看到更加详细的信息非常类似于通知的效果。
class FrontService : Service(){override fun onCreate() {super.onCreate()val manager getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagerval channel NotificationChannel(my_service,前台Service通知,NotificationManager.IMPORTANCE_DEFAULT)manager.createNotificationChannel(channel)val intent Intent(this, MainActivity::class.java)val pendingIntent PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)val notification NotificationCompat.Builder(this, my_service).setContentTitle(Content title).setContentText(content text).setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round)).setContentIntent(pendingIntent).build()// 第一个参数是通知的id类似于notify()方法的第一个参数第二个参数则是//构建的Notification对象。调用startForeground()方法后就会让MyService变成一个前//台Service并在系统状态栏显示出来。startForeground(1, notification)}override fun onBind(intent: Intent?): IBinder? {TODO(Not yet implemented)}}这里需要声明权限同时指定Service的foregroundServiceType根据实际选择
uses-permission android:nameandroid.permission.FOREGROUND_SERVICE/
uses-permission android:nameandroid.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK/
service android:name.FrontServiceandroid:enabledtrueandroid:exportedtrueandroid:foregroundServiceTypemediaPlayback/4、IntentService
Service中的代码都是默认运行在主线程当中的如果直接在Service里处理一些耗时的逻辑就很容易出现ANRApplication Not Responding的情况。 应该在其他线程处理耗时操作如下所示。
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {thread {// 开启一个线程执行耗时操作stopSelf() // 操作执行完毕关闭Service}return super.onStartCommand(intent, flags, startId)}Android提供了IntentService这种Service在执行完后自动销毁。
class MyIntentService: IntentService(MyIntentService){// 新增了一个方法该方法已经在子线程中执行所以将耗时操作放在这里override fun onHandleIntent(intent: Intent?) {TODO(Not yet implemented)}// 其他方法和普通Service一样override fun onCreate() {super.onCreate()}
}