In this tutorial, we’ll be discussing one of the fundamental components of the Android framework, namely IntentService. We’ll be developing an Android IntentService application using BroadcastReceiver.

在本教程中,我们将讨论Android框架的基本组件之一,即IntentService。 我们将使用BroadcastReceiver开发一个Android IntentService应用程序。

Android IntentService (Android IntentService)

We’ve discussed Android Service in earlier tutorial. An IntentService extends the Service class.

我们在前面的教程中讨论了Android Service 。 IntentService扩展了Service类。

Both Services and IntentServices are used to run operations that do not need a UI.

Services和IntentServices都用于运行不需要UI的操作。

An IntentService is used to run data sequentially. Each time you call an Intent to the Service, that operation would be added into the queue.

IntentService用于顺序运行数据。 每次您对服务调用Intent时,该操作都会添加到队列中。

Android IntentService与服务 (Android IntentService vs Service)

.tg {border-collapse:collapse;border-spacing:0;border-color:#999;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;}
.tg .tg-yw4l{vertical-align:top}
.tg .tg-6k2t{background-color:#D2E4FC;vertical-align:top}

.tg {border-collapse:collapse; border-spacing:0; border-color:#999;}
.tg td {font-family:Arial,sans-serif; font-size:14px; padding:10px 5px; border-style:solid; border-width:1px; overflow:hidden; word-break:normal; border-color :#999;颜色:#444;背景颜色:#F7FDFA;}
.tg th {font-family:Arial,sans-serif; font-size:14px; font-weight:normal; padding:10px 5px; border-style:solid; border-width:1px; overflow:hidden; word-break :正常;边框颜色:#999;颜色:#fff;背景颜色:#26ADE4;}
.tg .tg-yw4l {vertical-align:top}
.tg .tg-6k2t {background-color:#D2E4FC; vertical-align:top}

A Service is invoked using startService() An IntentService is invoked using Intent.
A Service can be invoked from any thread. An IntentService can in invoked from the Main thread only.
A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI. An IntentService creates a separate worker thread to run background operations.
A Service invoked multiple times would create multiple instances. An IntentService invoked multiple times won’t create multiple instances.
A service needs to be stopped using stopSelf() or stopService() An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
Android service can run parallel operations. In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
An IntentService cannot run parallel operation like a Service.
使用startService()调用服务 使用Intent调用IntentService。
可以从任何线程调用服务。 IntentService只能从Main线程中调用。
默认情况下,服务在应用程序的主线程上运行后台操作。 因此,它可以阻止您的应用程序的UI。 IntentService创建一个单独的工作线程来运行后台操作。
多次调用的服务将创建多个实例。 多次调用的IntentService不会创建多个实例。
需要使用stopSelf()或stopService()停止服务 队列完成后,IntentService自动停止。 无需触发stopService()或stopSelf()。
Android服务可以运行并行操作。 在IntentService中,多个intent调用会自动排队,并且将按顺序执行。
IntentService不能像Service一样运行并行操作。

In a service, the onHandleIntent() method gets invoked when the intent is passed from the activity.

在服务中,当从活动传递意图时,将调用onHandleIntent()方法。

BroadcastReceivers are used to transfer messages across applications or between a service and an activity.
To transfer data between a service and an activity we need to use a LocalBroadcastManager.

BroadcastReceivers用于在应用程序之间或服务与活动之间传输消息。
为了在服务和活动之间传输数据,我们需要使用LocalBroadcastManager

LocalBroadcastManager class comes with the support library and is used to transfer data locally only.
You cannot transfer data outside the application.

支持库随附LocalBroadcastManager类,该类仅用于本地传输数据。
您无法在应用程序外部传输数据。

In the following section, we’ll create an application that passes a string to the IntentService which returns it to the Activity after a delay. Thanks to IntentService, this happens sequentially.

在下一节中,我们将创建一个应用程序,该应用程序将字符串传递给IntentService,并在延迟后将其返回给Activity。 多亏了IntentService,这是顺序发生的。

Android IntentService示例项目结构 (Android IntentService Example Project Structure)

布局代码 (Layout code)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:app="https://schemas.android.com/apk/res-auto"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><EditTextandroid:id="@+id/inputText"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="8dp"android:hint="Enter your message"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="8dp"android:text="Send Message"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/inputText" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="24dp"android:text="Message received from the Service is:\n"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /></android.support.constraint.ConstraintLayout>

The code for the MainActivity.java class is given below:

MainActivity.java类的代码如下:

package com.journaldev.androidintentservices;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;public class MainActivity extends AppCompatActivity {TextView textView;Button button;EditText editText;MyReceiver myReceiver;public static final String FILTER_ACTION_KEY = "any_key";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = findViewById(R.id.textView);button = findViewById(R.id.button);editText = findViewById(R.id.inputText);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {String message = editText.getText().toString();Intent intent = new Intent(MainActivity.this, MyService.class);intent.putExtra("message", message);startService(intent);}});}private void setReceiver() {myReceiver = new MyReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(FILTER_ACTION_KEY);LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);}@Overrideprotected void onStart() {setReceiver();super.onStart();}@Overrideprotected void onStop() {unregisterReceiver(myReceiver);super.onStop();}private class MyReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String message = intent.getStringExtra("broadcastMessage");textView.setText(textView.getText() + "\n" + message);}}
}

Some important points:

一些要点:

  • We need to set an IntentFilter to register our BroadcastReceiver.我们需要设置一个IntentFilter来注册我们的BroadcastReceiver。
  • Inside the IntentFilter Action we specify a string.在IntentFilter Action内部,我们指定一个字符串。
  • The same string would be used in our IntentService as well.同样的字符串也将在我们的IntentService中使用。
  • We must unregister our BroadcastReceiver in the onStop() method.我们必须在onStop()方法中取消注册BroadcastReceiver。
  • LocalBroadcastManager instance is used to set the receiver.LocalBroadcastManager实例用于设置接收方。
  • Our BroadcastReceiver would append the string returned from the service.我们的BroadcastReceiver将附加从服务返回的字符串。

The code for MyService.java class is given below:

MyService.java类的代码如下:

package com.journaldev.androidintentservices;import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;public class MyService extends IntentService {public MyService() {super("MyService");}@Overrideprotected void onHandleIntent(Intent intent) {String message = intent.getStringExtra("message");intent.setAction(MainActivity.FILTER_ACTION_KEY);SystemClock.sleep(3000);String echoMessage = "IntentService after a pause of 3 seconds echoes " + message;LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent.putExtra("broadcastMessage", echoMessage));}
}

To return the data to the activity we use the sendBroadcast method. It passes the data to the BroadcastReceiver. The BroadcastReceiver eventually passes the data to the Activity.

要将数据返回到活动,我们使用sendBroadcast方法。 它将数据传递到BroadcastReceiver。 广播接收器最终将数据传递给活动。

You must declare the Service inside the Manifest file. Without the LocalBroadcastManager the above data won’t be passed.
您必须在清单文件中声明服务。 如果没有LocalBroadcastManager,则不会传递上述数据。

The output of the above application in action is given below:

上面应用程序的输出如下:

This brings an end to this tutorial. You can download the project from the link below.

本教程到此结束。 您可以从下面的链接下载项目。

Download Android IntentService Project下载Android IntentService项目
GitHub Repository.GitHub Repository下载项目代码。

翻译自: https://www.journaldev.com/20735/android-intentservice-broadcastreceiver

使用BroadcastReceiver的Android IntentService相关推荐

  1. Android IntentService解析

    Android IntentService解析 在开发安卓应用程序时,除非你指定,否则绝大部分执行动作都运行UI线程中.这种机制会引发一些问题,因为耗时操作会妨碍用户交互行为.这会让用户感到懊恼,甚至 ...

  2. Android IntentService使用

    概述 演示使用Android 中IntentService的方法.IntentService一般情况下,用于后台处理一些耗资源的任务.本例子有演示使用这个IntentService类的代码,并可运行. ...

  3. android service 构造函数,Android IntentService无法实例化类;没有空构造函数

    我有一个MainActivity类,需要访问在线API(因此使用网络资源).这需要我在单独的文件HttpRequestService.java中创建的后台线程. MainActivity.java: ...

  4. 使用ResultReceiver的Android IntentService

    In this tutorial, we'll be using IntentService with a ResultReceiver in our Android Application. We' ...

  5. Android:IntentService的学习

    在Android的四大组件中,Service排行老二,在Android中的主要作用是后台服务,进行与界面无关的操作.由于Service运行在主线程,所以进行异步操作需要在子线进行.为此Android为 ...

  6. 转 如何使android录音实现内录功能,BroadcastReceiver实现android来去电录音功能(外录)...

    因为原生android没有提供来去电内录功能,所以只能通过麦克进行通话录音, /** * 来去电录音,因为去电没有接听的状态,只要拨出就会开始录音 * * @author jauken * @date ...

  7. android IntentService

    参考: http://blog.163.com/xueli_007/blog/static/71533607201272044636529/ http://blog.csdn.net/zhf19890 ...

  8. android IntentService生命周期问题

    假设须要在onHandleIntent之前运行一些操作.比方须要停止当前正在运行的任务.可在onStart做这个操作. 须要注意的是必须在onStart函数的最后(运行完我的操作后)调用super.o ...

  9. Android - Intentservice源码解析

    https://blog.csdn.net/javazejian/article/details/52426425 转载于:https://www.cnblogs.com/qlky/p/1067562 ...

最新文章

  1. docker查看现有容器_如何使用Docker将现有应用程序推送到容器中
  2. Tomcat遇到”Error listenerStart”或”Error filterStart”问题且无详细日志时的log配置...
  3. Web服务器启动端口冲突问题
  4. 单目标识别下的以中心点定位为目标值的yolo改进算法措施
  5. 给Ubuntu 16.04更换更新源
  6. LiveVideoStackCon深圳 - VR/AR基础技术更成熟
  7. 基于事件驱动架构构建微服务第9部分:处理更新
  8. python爬虫与django_请问django和爬虫程序如何整合?
  9. 39 FI配置-财务会计-固定资产-组织结构-定义号码范围间隔
  10. java buqi_Java 异常
  11. iOS开发笔记 2、Cocoa简明
  12. 安装tensorflow时候报错ImportError: DLL load failed: 找不到指定的模块。Failed to load the native TensorFlow runtime.
  13. 关于网络的命令及介绍
  14. 关于app的几个核心功能的设计想法
  15. HDOJ 4622 Reincarnation (hash)
  16. Jbuilder2005破解补丁使用方法和下载地址
  17. 爬取笔趣阁小说网站上的所有小说(二)
  18. 尼康d850相机参数测试软件,新功能介绍二:景深合成与自动调焦_尼康 D850_数码影像评测-中关村在线...
  19. 10个最佳iOS Photo App模板
  20. Cache与主存的地址映像

热门文章

  1. Rabbit-音乐欣赏
  2. [转载] Python数学实验与建模 课后习题第1章解析
  3. [转载] python 遍历字符串 字符_python 遍历字符串(含汉字)实例详解
  4. [转载] python怎么将十进制转换为二进制_python十进制和二进制的转换方法(含浮点数)
  5. [转载] Python面向对象编程系列第一篇
  6. hidden field implements session
  7. 实验三 密码破解技术 201521410010
  8. 时序数据库技术体系-时序数据存储模型设计
  9. .NET开源 Visual Studio支持Android和iOS 编程
  10. exchange EWS 开发随笔二