Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách chia sẻ Intent từ IntentService trong Android

Giới thiệu về IntentService

IntentService là Service chạy nền (background) xử lý các tác vụ bất đồng bộ theo hàng đợi (queue). Đặc điểm:

  • Tự động chạy trên worker thread (không block UI)
  • Xử lý tuần tự các Intent (mỗi startService() một lần)
  • Tự stop khi queue rỗng (hoặc gọi stopSelf())

Ví dụ: Chia sẻ nội dung từ IntentService

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 (src/MainActivity.java)

package com.example.andy.myapplication;

import android.content.Intent;
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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = findViewById(R.id.text);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity.this, ShareService.class));
            }
        });
    }
}

Bước 4: IntentService (ShareService.java)

package com.example.andy.myapplication;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;

public class ShareService extends IntentService {
    public static volatile boolean shouldStop = false;

    public ShareService() {
        super(ShareService.class.getSimpleName());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Chủ đề");
        sharingIntent.putExtra(Intent.EXTRA_TEXT, "Tutorialspoint.com");
        sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // BẮT BUỘC từ Service
        startActivity(Intent.createChooser(sharingIntent, "Chia sẻ qua"));

        if (shouldStop) {
            stopSelf();
            return;
        }
    }
}

Bước 5: Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.andy.myapplication">

    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <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">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".ShareService"/>

    </application>
</manifest>

⚠️ Lưu ý quan trọng

  • FLAG_ACTIVITY_NEW_TASK: Bắt buộc khi startActivity từ Service/Background context
  • IntentService deprecated API 30: Android 11+ khuyến nghị dùng WorkManager hoặc JobIntentService
  • Không nên hiển thị UI (Dialog, Share sheet) trực tiếp từ Service - có thể crash trên Android 10+ do giới hạn background activity launch

Chạy ứng dụng

Chạy app → Nhấn TextView "Khởi động Service" → Hộp thoại chia sẻ hệ thống hiện ra với nội dung "Tutorialspoint.com".