Melaporkan status pekerjaan

Panduan ini menunjukkan cara melaporkan status permintaan pekerjaan yang berjalan di layanan latar belakang ke komponen yang mengirim permintaan. Hal ini memungkinkan Anda, misalnya, melaporkan status permintaan di UI objek Activity. Cara yang direkomendasikan untuk mengirim dan menerima status adalah dengan menggunakan LocalBroadcastManager, yang membatasi objek Intent siaran ke komponen dalam aplikasi Anda sendiri.

Melaporkan status dari JobIntentService

Untuk mengirim status permintaan pekerjaan dalam JobIntentService ke komponen lain, buat Intent yang berisi status dalam data yang diperluas terlebih dahulu. Sebagai opsi, Anda dapat menambahkan tindakan dan URI data ke Intent ini.

Selanjutnya, kirim Intent dengan memanggil LocalBroadcastManager.sendBroadcast(). Tindakan ini mengirimkan Intent ke komponen mana pun dalam aplikasi Anda yang telah terdaftar untuk menerimanya. Untuk mendapatkan instance LocalBroadcastManager, panggil getInstance().

Contoh:

Kotlin

...
// Defines a custom Intent action
const val BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST"
...
// Defines the key for the status "extra" in an Intent
const val EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS"
...
class RSSPullService : JobIntentService() {
    ...
    /*
     * Creates a new Intent containing a Uri object
     * BROADCAST_ACTION is a custom Intent action
     */
    val localIntent = Intent(BROADCAST_ACTION).apply {
        // Puts the status into the Intent
        putExtra(EXTENDED_DATA_STATUS, status)
    }
    // Broadcasts the Intent to receivers in this app.
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent)
    ...
}

Java

public final class Constants {
    ...
    // Defines a custom Intent action
    public static final String BROADCAST_ACTION =
        "com.example.android.threadsample.BROADCAST";
    ...
    // Defines the key for the status "extra" in an Intent
    public static final String EXTENDED_DATA_STATUS =
        "com.example.android.threadsample.STATUS";
    ...
}
public class RSSPullService extends JobIntentService {
...
    /*
     * Creates a new Intent containing a Uri object
     * BROADCAST_ACTION is a custom Intent action
     */
    Intent localIntent =
            new Intent(Constants.BROADCAST_ACTION)
            // Puts the status into the Intent
            .putExtra(Constants.EXTENDED_DATA_STATUS, status);
    // Broadcasts the Intent to receivers in this app.
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
...
}

Langkah berikutnya adalah menangani objek Intent siaran yang masuk pada komponen yang mengirim permintaan pekerjaan asli.

Menerima siaran status dari JobIntentService

Untuk menerima objek Intent siaran, gunakan subclass BroadcastReceiver. Di subclass, terapkan metode callback BroadcastReceiver.onReceive(), yang dipanggil LocalBroadcastManager saat menerima Intent. LocalBroadcastManager meneruskan Intent yang masuk ke BroadcastReceiver.onReceive().

Contoh:

Kotlin

// Broadcast receiver for receiving status updates from the IntentService.
private class DownloadStateReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        ...
        /*
         * Handle Intents here.
         */
        ...
    }
}

Java

// Broadcast receiver for receiving status updates from the IntentService.
private class DownloadStateReceiver extends BroadcastReceiver
{
    // Called when the BroadcastReceiver gets an Intent it's registered to receive
    @Override
    public void onReceive(Context context, Intent intent) {
...
        /*
         * Handle Intents here.
         */
...
    }
}

Setelah menentukan BroadcastReceiver, Anda dapat menentukan filter untuknya yang cocok dengan tindakan, kategori, dan data tertentu. Untuk melakukannya, buat IntentFilter. Cuplikan pertama ini menunjukkan cara menentukan filter:

Kotlin

// Class that displays photos
class DisplayActivity : FragmentActivity() {
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        super.onCreate(savedInstanceState)
        ...
        // The filter's action is BROADCAST_ACTION
        var statusIntentFilter = IntentFilter(BROADCAST_ACTION).apply {
            // Adds a data filter for the HTTP scheme
            addDataScheme("http")
        }
        ...

Java

// Class that displays photos
public class DisplayActivity extends FragmentActivity {
    ...
    public void onCreate(Bundle stateBundle) {
        ...
        super.onCreate(stateBundle);
        ...
        // The filter's action is BROADCAST_ACTION
        IntentFilter statusIntentFilter = new IntentFilter(
                Constants.BROADCAST_ACTION);

        // Adds a data filter for the HTTP scheme
        statusIntentFilter.addDataScheme("http");
        ...

Untuk mendaftarkan BroadcastReceiver dan IntentFilter pada sistem, dapatkan instance LocalBroadcastManager dan panggil metode registerReceiver()-nya. Cuplikan berikutnya ini menunjukkan cara mendaftarkan BroadcastReceiver dan IntentFilter-nya:

Kotlin

        // Instantiates a new DownloadStateReceiver
        val downloadStateReceiver = DownloadStateReceiver()
        // Registers the DownloadStateReceiver and its intent filters
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(downloadStateReceiver, statusIntentFilter)
        ...

Java

        // Instantiates a new DownloadStateReceiver
        DownloadStateReceiver downloadStateReceiver =
                new DownloadStateReceiver();
        // Registers the DownloadStateReceiver and its intent filters
        LocalBroadcastManager.getInstance(this).registerReceiver(
                downloadStateReceiver,
                statusIntentFilter);
        ...

Satu BroadcastReceiver dapat menangani lebih dari satu jenis objek Intent siaran, masing-masing dengan tindakannya sendiri. Fitur ini memungkinkan Anda menjalankan kode yang berbeda untuk setiap tindakan, tanpa harus menentukan BroadcastReceiver terpisah untuk setiap tindakan. Untuk menentukan IntentFilter lain bagi BroadcastReceiver yang sama, buat IntentFilter dan ulangi panggilan ke registerReceiver(). Contoh:

Kotlin

        /*
         * Instantiates a new action filter.
         * No data filter is needed.
         */
        statusIntentFilter = IntentFilter(ACTION_ZOOM_IMAGE)
        // Registers the receiver with the new filter
        LocalBroadcastManager.getInstance(this)
                .registerReceiver(downloadStateReceiver, statusIntentFilter)

Java

        /*
         * Instantiates a new action filter.
         * No data filter is needed.
         */
        statusIntentFilter = new IntentFilter(Constants.ACTION_ZOOM_IMAGE);
        // Registers the receiver with the new filter
        LocalBroadcastManager.getInstance(this).registerReceiver(
                downloadStateReceiver,
                statusIntentFilter);

Mengirim Intent siaran tidak memulai atau melanjutkan Activity. BroadcastReceiver untuk Activity menerima dan memproses objek Intent meskipun aplikasi berjalan di latar belakang, tetapi tidak memaksa aplikasi ke latar depan. Jika ingin memberi tahu pengguna tentang peristiwa yang terjadi di latar belakang saat aplikasi Anda tidak terlihat, gunakan Notification. Jangan pernah memulai Activity sebagai respons terhadap Intent siaran yang masuk.