https://blog.csdn.net/qq_33748378/article/details/52330382

https://blog.csdn.net/ryantang03/article/details/8146154

https://blog.csdn.net/hudashi/article/details/7986130

IntenteService使用姿势

1: IntenteService是 Service的 子类,用来处理异步请求,客户端通过 startService(intent) 将请求传递给 intentService, 其中 IntentService在onCreate() 函数中,通过HandlerThread 单独开启一个线程来处理所有的 intent请求对象,所对应的 任务,这样可以避免阻塞主线程,在执行完一个 inentServcie请求对象之后,如果没有新的 Intent请求到达,则自动停止 Service, 否则就执行下一个 intent 请求对应的任务

2 :IntenteService在处理事务时,还是采用Handler方式,创建一个名叫 ServiceHandler 的内部handler , 并绑定到 HandlerThread所对应的 子线程,ServiceHandler 吧处理一个Intent所对应的事务都封装在  onHandleIntent的虚函数中,因此我们需要实现 onHandleIntenth函数,在实现的函数里面 根据不同 intent 处理不同事务或者任务就可以了

3: 使用 IntentServcie的步骤

3-1 : 写构造函数

3-2 :实现 虚函数onHandleIntent() 

3-3  启动 IntentServcie :  startService(context, intentServcie.class) ; (注意 intentService默认实现了onBind() 函数,但是onBind() 函数返回值是 null )

3-4  另外,不建议通过 bindService() 启动 IntentService。IntentService 源码中的 onBind() 默认返回 null;不适合 bindService() 启动服务,如果你执意要 bindService() 来启动 IntentService,可能因为你想通过 Binder 或 Messenger 使得 IntentService 和 Activity 可以通信,这样那么 onHandleIntent() 不会被回调,相当于在你使用 Service 而不是 IntentService。

4 : intentService 停止:

     onHandleIntent ( ) 里面的任务如果执行完毕,那么service会自动停止,不需要手动  stop, 如果任务没有执行完毕,service不会停止,而 onHandleIntent() 里面的任务 ,就是 通过 startService(context, intentServcie.class)传递的,多次启动会将任务依次放到 onHandleIntent () 中,并且 intentService 只会启动一次 (即多次启动,onCreate()运行一次,但是会运行多次 onStartCommand() 函数)

4 : 使用场景:

    在Android开发中,我们或许会碰到这么一种业务需求,一项任务分成几个子任务,子任务按顺序先后执行,子任务全部执行完后,这项任务才算成功。

4-1  那么,利用几个子线程顺序执行是可以达到这个目的的,但是每个线程必须去手动控制,而且得在一个子线程执行完后,再开启另一个子线程。

4-2  或者,全部放到一个线程中让其顺序执行。这样都可以做到,

4-3  但是,如果这是一个后台任务,就得放到Service里面,由于Service和Activity是同级的,所以,要执行耗时任务,就得在Service里面开子线程来执行。那么,有没有一种简单的方法来处理这个过程呢,答案就是IntentService。

5 : 场景模拟

package com.application.intentservicedemo;import androidx.appcompat.app.AppCompatActivity;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;public class MainActivity extends AppCompatActivity implements View.OnClickListener {public static final String ACTION_DOWN_LOAD_IMAGE = "action_down_load_image";public static final String DOWN_LOAD_IMAGE_PATH = "down_load_image_path";public static final String RESULT_DOWNLOAD_IMAGE = "result_download_image";public static final String EXTRA_DOWNLOAD_IMAGE = "extra_download_image";private TextView addTask;private int i;private BroadcastReceiver receiver = new DownloadBroadCast();private LinearLayout content;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);addTask = findViewById(R.id.add_task);content = findViewById(R.id.content_container);addTask.setOnClickListener(this);//注册广播IntentFilter filter=new IntentFilter(RESULT_DOWNLOAD_IMAGE);registerReceiver(receiver,filter);}@Overridepublic void onClick(View view) {int id = view.getId();if (id == R.id.add_task) {// 点击按钮,添加图片下载任务TextView textView = new TextView(this);String path="/sdcard/imgs"+(++i)+".png";//模拟下载路径textView.setText(path + " is downloading");textView.setTag(path);content.addView(textView);startIntentServcieForDownload(path);}}private void startIntentServcieForDownload(String imagePath) {Intent intent = new Intent();intent.setClass(this,MyIntentService.class);intent.setAction(ACTION_DOWN_LOAD_IMAGE);intent.putExtra(DOWN_LOAD_IMAGE_PATH,imagePath);startService(intent);}public class DownloadBroadCast extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {if (TextUtils.equals(intent.getAction(),RESULT_DOWNLOAD_IMAGE)) {String imageResult = intent.getStringExtra(EXTRA_DOWNLOAD_IMAGE);TextView textView = (TextView) content.findViewWithTag(imageResult);textView.setText(imageResult + "is successful download");}}}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(receiver);}
}
package com.application.intentservicedemo;import android.app.IntentService;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;import androidx.annotation.Nullable;import static com.application.intentservicedemo.MainActivity.DOWN_LOAD_IMAGE_PATH;
import static com.application.intentservicedemo.MainActivity.EXTRA_DOWNLOAD_IMAGE;public class MyIntentService extends IntentService {private static final String TAG = "MyIntentService";public MyIntentService() {super("download image");}@Overridepublic void onCreate() {super.onCreate();Log.e(TAG,"onCreate enter");}@Overridepublic int onStartCommand(@Nullable Intent intent, int flags, int startId) {Log.e(TAG,"onStartCommand enter");return super.onStartCommand(intent, flags, startId);}/*** @param name* @deprecated*/public MyIntentService(String name) {super(name);}@Overrideprotected void onHandleIntent(@Nullable Intent intent) {Log.e(TAG,"onHandleIntent enter");if (intent != null) {if (TextUtils.equals(intent.getAction(),MainActivity.ACTION_DOWN_LOAD_IMAGE)) {String path = intent.getStringExtra(DOWN_LOAD_IMAGE_PATH);//根据下载路径,模拟图片的下载,在后头 service 并且开启线程来 完成图片下载任务downLoadWork(path);}}}private void downLoadWork(String path) {try {Log.e(TAG,"downLoadWork thread = " + Thread.currentThread().getName());Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}// 一般后台任务执行完毕后,怎么将 任务执行的结果给 传递出去了,就是通过广播的方式Intent intent=new Intent(MainActivity.RESULT_DOWNLOAD_IMAGE);intent.putExtra(EXTRA_DOWNLOAD_IMAGE,path);sendBroadcast(intent);}@Overridepublic void onDestroy() {super.onDestroy();Log.e(TAG,"onDestroy enter");}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.application.intentservicedemo"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><service android:name=".MyIntentService"android:exported="true"></service></application></manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"android:gravity="center"android:orientation="vertical"android:id="@+id/content_container"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="添加任务"android:id="@+id/add_task"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /></LinearLayout>

IntentService使用姿势相关推荐

  1. CVPR2019论文解读:单眼提升2D检测到6D姿势和度量形状

    CVPR2019论文解读:单眼提升2D检测到6D姿势和度量形状 ROI-10D: Monocular Lifting of 2D Detection to 6D Pose and Metric Sha ...

  2. OpenCV中的姿势估计及3D效果(3D坐标轴,3D立方体)绘制

    OpenCV中的姿势估计及3D效果(3D坐标轴,3D立方体)绘制 1. 效果图 2. 原理 3. 源码 3.1 姿态估计后绘制3D坐标轴 3.2 姿态估计后绘制立方体 参考 这篇博客将延续上一篇博客: ...

  3. mysql低权限用户getshell_GetShell的姿势总结

    原文来自SecIN社区-作者:WiHat 0x00 什么是WebShell 渗透测试工作的一个阶段性目标就是获取目标服务器的操作控制权限,于是WebShell便应运而生.Webshell中的WEB就是 ...

  4. 肠子的小心思(二):你坐在马桶上的姿势很可能不正确

    为什么80%的码农都做不了架构师?>>>    作者:汪娇娇 时间:2017年4月19日 1.不管坐着还是站着,肠道周围都有一块肌肉像套索一样包裹着它.向一个方向牵引着它,这就产生了 ...

  5. 与MySQL传统复制相比,GTID有哪些独特的复制姿势?

    与MySQL传统复制相比,GTID有哪些独特的复制姿势? http://mp.weixin.qq.com/s/IF1Pld-wGW0q2NiBjMXwfg 陈华军,苏宁云商IT总部资深技术经理,从事数 ...

  6. 无需3D运动数据训练,最新人体姿势估计方法达到SOTA | CVPR 2020

    作者 | Muhammed Kocabas 译者 | 刘畅 出品 | AI科技大本营(ID:rgznai100) 人体的运动对于理解人的行为是非常重要的.尽管目前已经在单图像3D姿势和动作估计方面取得 ...

  7. 薅资本主义羊毛新姿势,英伟达GPU免费用

    作者 | 阿司匹林 出品 | 人工智能头条(公众号ID:AI_Thinker) 在到处都是开源工具和学习资料的今天,深度学习的门槛已经大大降低.然而,学习的门槛降低并不意味着学习的成本降低了,比如说动 ...

  8. 吴忠强:刷LeetCode的正确姿势!

    ↑↑↑关注后"星标"Datawhale 每日干货 & 每月组队学习,不错过 Datawhale干货 作者:吴忠强,东北大学,Datawhale成员 写在前面 最近面试中做算 ...

  9. 【开源】一键生成各种姿势的火柴人gif:在线录制真人视频即可转换

    点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 子豪 发自 凹非寺 量子位 报道 | 公众号 QbitAI 现在,只 ...

  10. 博士真正搞科研的姿势

    萧箫 发自 凹非寺 量子位 报道 | 公众号 QbitAI 国内的各种科研人才,他们到底有什么与众不同之处? 又或者,拥有什么样的科研能力,才能更好地成为科研人才? 事实上,这些问题可以更具体一些:走 ...

最新文章

  1. 在Linux下怎样让top命令启动之后就按内存使用排序(或CPU使用排序)?
  2. jQuery 动感的横向柱状形投票统计图
  3. Ros知识【09】:功能包介绍
  4. python抢票代码_GitHub标星超12K,抢票神器大更新,支持候补
  5. Java并发篇_Java内存模型
  6. 2021爱智先行者—(1)开箱点评
  7. 信息学奥赛一本通 1978:【18NOIP普及组】标题统计 | 洛谷 P5015 [NOIP2018 普及组] 标题统计
  8. .net vue漂亮登录界面_6个宝藏级Vue管理后台框架 必须收藏
  9. B站智能防挡弹幕的一种python实现
  10. C++类成员函数的传参问题
  11. Win10 系统 WebLogic 12cR2 下载与安装图解
  12. MVC IIS创建过程问题收录
  13. 实战项目-python库分析科比生涯数据
  14. tf1.x版RandLA-Net源码解读(1):数据预处理
  15. IEEE期刊参考文献中的会议缩写
  16. vue filters的使用
  17. 4月刊佳文推荐:开发者的眼界
  18. mysql -hlocalhost -uroot -p_MySQL数据库的操作(01)--- MySQL的安装以及与idea的连接
  19. C语言转义字符及注意点
  20. codeforces-750【C思维】

热门文章

  1. [转]oracle性能调优之--Oracle 10g AWR 配置
  2. 超清视频制作:视频补帧+超分辨率
  3. python遍历字母_如何遍历字母表?
  4. 用VBA打开PDF文件
  5. 计算机网络ip地址分类的范围,ip地址分类及范围_ip地址由什么组成
  6. (转)牛牛牌型判定(五小牛 五花牛 炸弹 银牛 牛牛 有牛没牛)
  7. iOS自定义相机(转)
  8. java中 toast的意思,Java中toast
  9. 全屏动态滑稽网站HTML源码
  10. c语言 pow算圆的面积,简单微积分--积分求圆的面积