安卓实现异步任务5——使用IntentService实现
安卓中实现异步任务(5)——使用IntentService实现
问题背景
问题分析
在日常安卓开发汇总,我们在使用 Service 时如果要执行耗时任务,总会创建一个子线程来执行,而不是直接在 Service中执行。这是因为 Service 中的程序仍然运行于主线程中,当执行一项耗时操作时,很容易导致ANR错误。当需要与 UI线程进行交互时,使用 Handler 机制来进行处理。 为了简化操作,Android提供了IntentService类。IntentService是 Android中提供的后台服务类,是Service 自动实现多线程的子类。首先,我们一起来看看具体怎么使用。
实现demo
(1)新建我们的IntentService子类,在onHandleIntent中执行耗时任务,代码如下:
-
import android.app.IntentService;
-
import android.content.Intent;
-
import android.util.Log;
-
-
import androidx.annotation.Nullable;
-
-
public class MyIntentService extends IntentService {
-
private static final String TAG = "MyIntentService";
-
int i = 3;
-
//构造方法
-
public MyIntentService() {
-
super("");
-
}
-
-
-
protected void onHandleIntent( { Intent intent)
-
while (i > 0) {
-
Log.d(TAG, "onHandleIntent i : " i);
-
i--;
-
try {
-
// 模拟耗时任务
-
Thread.sleep(100);
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
-
public void onCreate() {
-
super.onCreate();
-
Log.i(TAG, "onCreate");
-
}
-
-
public void onDestroy() {
-
super.onDestroy();
-
Log.i(TAG, "onDestroy");
-
}
-
}
注意:IntentService是service的子类,定义后要记得在manifest配置文件中进行注册: <service android:name=".thread.MyIntentService"/>
(2)新建activity,对应layout布局文件代码如下:
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
xmlns:tools="http://schemas.android.com/tools"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent"
-
tools:context=".thread.IntentServiceActivity">
-
<Button
-
android:id="@ id/startIntentService"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:text="启动IntentService"
-
android:onClick="startIntentService"
-
android:gravity="center_horizontal"/>
-
-
-
</LinearLayout>
布局比较简单,就是一个button用来启动我们的intentservice。 (3)对应activity代码如下:
-
import android.content.Intent;
-
import android.os.Bundle;
-
import android.view.View;
-
-
public class IntentServiceActivity extends AppCompatActivity {
-
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_intent_service);
-
}
-
-
public void startIntentService(View view) {
-
//启动service
-
Intent intent = new Intent(IntentServiceActivity.this, MyIntentService.class);
-
startService(intent);
-
}
-
}
(4)执行APP log如下:
关键代码分析
持续更新。。。
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgfahhf
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
怎样阻止微信小程序自动打开
PHP中文网 06-13 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01