Android socket,使用BroadcastReceiver的Android IntentService

 2023-11-19 阅读 28 评论 0

摘要: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框架的基本組件之

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)

Android socket?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.

Android使用自帶文件。 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)

android布局,.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.

Android10使用, 在服務中,當從活動傳遞意圖時,將調用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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/183143.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息