![[Android căn bản] Bài 10: Service trong Android-phần 4 Intent Service](https://tuandc.com/wp-content/uploads/2017/08/Android.jpg)
[Android căn bản] Bài 10: Service trong Android-phần 4 Intent Service

Chào các bạn chúng ta lại gặp nhau trong series lập trình Android căn bản. Ở những bài trước tôi đã giới thiệu với các bạn hai loại Service là Unbound Service và Buond Service và ở phần này tôi sẽ giới thiệu cách sử dụng loại service cuối cùng là Intent Service.
Như đã giới thiệu ở những bài trước thì loaiji service này được sử dụng cho những tác vụ chỉ chạy một lần duy nhất và dịch vụ sẽ tự hủy khi hoàn thành tác vụ.
Intent Service.
Ở ví dụ này tôi sẽ mô phỏng quá trình download một file PDF từ trên mạng về.
Đầu tiên ta làm cái giao diện cơ bản như thế này.

Giao diện
Giao diện nhìn rất dễ dàng phải không nào.
Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.tuandc.akinosora.intentservice.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<Button
android:id="@+id/DownloadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tải xuống"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="57dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/HuyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hủy"
tools:layout_constraintTop_creator="1"
android:layout_marginStart="5dp"
android:layout_marginTop="48dp"
app:layout_constraintTop_toBottomOf="@+id/DownloadButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="@+id/DownloadButton" />
</android.support.constraint.ConstraintLayout>
Sau đó bạn hãy tạo một lớp service tên là DowloadService lớp này sẽ kế thừa từ lớp IntentService
.
Code:
package com.tuandc.akinosora.intentservice;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Akinosora on 16/10/2017.
*/
public class DowloadService extends IntentService {
public DowloadService() {
super("Download");// Nhớ đặt tên cho service
}
// Bạn phải Impliment phương thức là onHandleIntent phương thức này sẽ được khởi chạy khi dihj vụ được khởi chạy.
@Override
protected void onHandleIntent(@Nullable Intent intent) {
try {
int result = DownloadFile(new URL("http://www.amazon.com/somefile.pdf"));
Log.e("Download from ", "http://www.amazon.com/somefile.pdf"+result +" MB");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private int DownloadFile(URL URLDownload) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 100;
}
}
Và tại MainActivity
ta sẽ làm như sau:
Code:
package com.tuandc.akinosora.intentservice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button DownloadButton, HuyButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadButton = (Button) findViewById(R.id.DownloadButton);
HuyButton = (Button) findViewById(R.id.HuyButton);
initEvent();
}
private void initEvent() {
DownloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(new Intent(getBaseContext(), DowloadService.class));// Gọi service bàng phuong thước startservice
}
});
HuyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(new Intent(getBaseContext(), DowloadService.class)); // Hủy dịch vụ.
}
});
}
}
Nhớ khai báo dịch vụ của mình vào manifrest
.
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tuandc.akinosora.intentservice">
<application
android: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">
<service android:name=".DowloadService"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Xong bạn hãy thử chạy chương trình và xem kết quả trong Logcat nhé.
Vậy là tôi đã giới thiệu với các bạn cách sử dụng IntentService rồi và đây cũng là phần cuối trong bài về các loại service trong Android cảm ơn các bạn đã theo dõi và hẹn gặp lại các bạn trong những bài tiếp theeo.
