Giới thiệu
Ví dụ này minh họa cách dừng một IntentService cụ thể bằng stopSelf() sau khi hoàn thành công việc và gửi kết quả về Activity qua Broadcast.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?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">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Khởi động Service"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Bước 3: MainActivity với Dynamic BroadcastReceiver (src/MainActivity.java)
package com.example.andy.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String data = intent.getStringExtra("DATAPASSED");
text.setText(data);
}
};
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.andy.myapplication");
registerReceiver(broadcastReceiver, filter); // registerReceiver thường (không LocalBroadcastManager)
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(v -> startService(new Intent(MainActivity.this, StoppableService.class)));
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
}
Bước 4: Service tự dừng sau khi gửi broadcast (StoppableService.java)
package com.example.andy.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
public class StoppableService extends IntentService {
public static volatile boolean shouldStop = false;
public StoppableService() {
super(StoppableService.class.getSimpleName());
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
Intent resultIntent = new Intent();
resultIntent.setAction("com.example.andy.myapplication");
resultIntent.putExtra("DATAPASSED", "Tutorialspoint.com");
sendBroadcast(resultIntent); // Broadcast toàn cục (system-wide)
if (shouldStop) {
stopSelf(); // Dừng service ngay lập tức
return;
}
// Service tự dừng sau onHandleIntent hoàn thành (do IntentService cơ chế)
}
}
Giải thích stopSelf()
stopSelf(): Yêu cầu hệ thống dừng Service này- IntentService tự động dừng sau khi
onHandleIntentxong (queue rỗng) stopSelf()hữu ích khi muốn dừng sớm trong vòng lặp hoặc có điều kiệnstopSelf(startId): Dừng chỉ cho startId cụ thể (tránh dừng request mới)
Manifest
<service android:name=".StoppableService"/>
Chạy ứng dụng
Chạy app → Nhấn TextView → Service chạy → Gửi broadcast → TextView cập nhật "Tutorialspoint.com" → Service tự dừng.
💡 Lưu ý: Code dùng
registerReceiver (global) thay vì LocalBroadcastManager. Cả 2 đều hoạt động nhưng LocalBroadcastManager an toàn/nhanh hơn cho trong-app.