Intent Service là gì? Ví dụ minh họa Intent Service

Đăng bởi: Admin | Lượt xem: 4670 | Chuyên mục: Android

Trong bài bài viết này ta tìm hiểu về Intent Service , vòng đời, cách sử dụng và ví dụ minh họa sử dụng Intent Service


1. Intent Service

Intent Service được sử dụng để thực hiện các nhiệm vụ một lần duy nhất, nghĩa là khi nhiệm vụ hoàn thành Service tự hủy.

Vòng đời Intent Service:

2. Ví dụ Intent Service

Hình ảnh dưới đây minh họa cách giao tiếp giữa Client (Activity) và IntentService, Client khởi động dịch vụ, nó gửi yêu cầu của nó thông qua một đối tượng Intent, dịch vụ chạy và làm các công việc của nó, đồng thời nó có thể gửi thông tin liên quan tới tình trạng công việc của nó, chẳng hạn làm được bao nhiêu phần trăm. Tại client có thể sử dụng ProgressBar để hiển thị phần trăm công việc đã làm được.

Các IntentService được thiết kế để tự động stop một cách tự nhiên khi công việc hoàn thành, và chỉ sử dụng một lần, vì vậy bạn nên sử dụng nó trong các tình huống như vậy. Phương thức <context>.stopService(intentService) sẽ không hoạt động với IntentService. Hơn nữa, rất khó để bạn sử dụng UI của ứng dụng để tương tác với IntentService.

Tạo mới một project SimpleIntentService.

  • Name: SimpleIntentService
  • Package name: org.o7planning.simpleintentservice

Thiết kế giao diện:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">
 
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="25dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <TextView
        android:id="@+id/textView_percent"
        android:layout_width="0dp"
        android:layout_height="22dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="28dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:gravity="center"
        android:text="(Percent)"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progressBar" />
 
    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="27dp"
        android:text="Start"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView_percent" />
 
    <Button
        android:id="@+id/button_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:text="Stop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_start" />
</androidx.constraintlayout.widget.ConstraintLayout>

Tạo một IntentService bằng cách nháy phải chuột vào một package, chọn:

  • New > Service > Service (IntentService)

​​​​​​​

Bạn có thể nhìn thấy SimpleIntentService đã được khai báo với AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.o7planning.simpleintentservice">
 
    <application ...>
        <service
            android:name=".SimpleIntentService"
            android:exported="false"></service>
 
        ...
    </application>
 
</manifest>

Lớp SimpleIntentService đã được tạo ra, nó cũng đã được đăng ký với AndroidManifest.xml, code được tạo ra là một gợi ý cho bạn viết một IntentService, bạn có thể xóa hết các code được tạo ra.

SimpleIntentService.java

package org.o7planning.simpleintentservice;
 
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
 
public class SimpleIntentService extends IntentService {
 
    public static volatile boolean shouldStop = false;
 
    public static final String ACTION_1 ="MY_ACTION_1";
 
    public static final String PARAM_PERCENT = "percent";
 
    public SimpleIntentService() {
        super("SimpleIntentService");
    }
 
    @Override
    protected void onHandleIntent(Intent intent) {
 
        // Create Intent object (to broadcast).
        Intent broadcastIntent = new Intent();
 
        // Set Action name for this Intent.
        // A Intent can perform many different actions.
        broadcastIntent.setAction(SimpleIntentService.ACTION_1);
 
        // Loop 100 times broadcast of Intent.
        for (int i = 0; i <= 100; i++) {
 
            // Set data
            // (Percent of work)
            broadcastIntent.putExtra(PARAM_PERCENT, i);
 
            // Send broadcast
            sendBroadcast(broadcastIntent);
 
            // Sleep 100 Milliseconds.
            SystemClock.sleep(100);
 
            if(shouldStop) {
                stopSelf();
                return;
            }
        }
 
    }
}

MainActivity.java

package org.o7planning.simpleintentservice;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
 
    private Button buttonStart;
    private Button buttonStop;
    private TextView textViewPercent;
 
    private ProgressBar progressBar;
 
    private Intent serviceIntent;
 
    private ResponseReceiver receiver = new ResponseReceiver();
 
 
    // Broadcast component
    public class ResponseReceiver extends BroadcastReceiver {
 
        // On broadcast received
        @Override
        public void onReceive(Context context, Intent intent) {
 
            // Check action name.
            if(intent.getAction().equals(SimpleIntentService.ACTION_1)) {
                int value = intent.getIntExtra(SimpleIntentService.PARAM_PERCENT, 0);
 
                new ShowProgressBarTask().execute(value);
            }
        }
    }
 
    // Display value for the ProgressBar.
    class ShowProgressBarTask extends AsyncTask<Integer, Integer, Integer> {
 
        @Override
        protected Integer doInBackground(Integer... args) {
 
            return args[0];
        }
 
        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
 
            progressBar.setProgress(result);
 
            textViewPercent.setText(result + " % Loaded");
 
            if (result == 100) {
                textViewPercent.setText("Completed");
                buttonStart.setEnabled(true);
            }
 
        }
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        this.textViewPercent = (TextView) this.findViewById(R.id.textView_percent);
        this.progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
        this.buttonStart = (Button) this.findViewById(R.id.button_start);
        this.buttonStop = (Button)this.findViewById(R.id.button_stop);
 
        this.buttonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonStartClicked();
            }
        });
 
        this.buttonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonStopClicked();
            }
        });
    }
 
 
    // On Resume of MainActivity
    @Override
    protected void onResume() {
        super.onResume();
 
        // Register receiver with Activity.
        registerReceiver(receiver, new IntentFilter(
                SimpleIntentService.ACTION_1));
    }
 
    // On Stop of MainActivity
    @Override
    protected void onStop() {
        super.onStop();
 
        // Unregister receiver with Activity.
        unregisterReceiver(receiver);
    }
 
    // Method is called when the user clicks on the Start button.
    public void buttonStartClicked( )  {
        this.buttonStart.setEnabled(false);
 
        this.serviceIntent = new Intent(this, SimpleIntentService.class);
 
        startService(this.serviceIntent);
    }
 
 
    public void buttonStopClicked( )  {
        if(this.serviceIntent!= null)  {
            // stopService(this.serviceIntent) does not work with IntentService(s).
 
            // Mandatory stopping of an IntentService is not recommended.
            SimpleIntentService.shouldStop = true;
        }
    }
 
}

Chạy ứng dụng:

Và bạn có thể xem nguyên tắc hoạt động của ví dụ trên theo hình minh họa dưới đây:

​​​​​​​

vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!



Khóa học liên quan

Khóa học: Android

Học Kotlin cơ bản
Số bài học:
Lượt xem: 17067
Đăng bởi: Admin
Chuyên mục: Android

Học lập trình Flutter cơ bản
Số bài học:
Lượt xem: 55095
Đăng bởi: Admin
Chuyên mục: Android

Lập trình Android cơ bản
Số bài học:
Lượt xem: 22179
Đăng bởi: Admin
Chuyên mục: Android