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

Tạo shortcut màn hình chính Android

Tạo Shortcut (Lối tắt) trên Home Screen Android

Android cho phép ứng dụng tạo shortcut (lối tắt) trên màn hình chính của launcher. Từ Android 8.0 (API 26), sử dụng ShortcutManagerCompat để tương thích ngược.

Bước 1: Tạo dự án mới

Khởi tạo project Android Studio.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click to create shortcut"
        android:textSize="24sp"
        android:gravity="center"
        android:padding="24dp" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.pm.ShortcutInfoCompat;
import android.support.v4.content.pm.ShortcutManagerCompat;
import android.support.v4.graphics.drawable.IconCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final String PREF_SHORTCUT_ADDED = "shortcut_added";
    private 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) {
                createShortcut();
            }
        });
    }
    
    private void createShortcut() {
        // Kiểm tra launcher có hỗ trợ pin shortcut không
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(getApplicationContext())) {
            // Tạo ShortcutInfo
            ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(
                    getApplicationContext(), "shortcut_id_1")
                    .setShortLabel("My App Shortcut")
                    .setLongLabel("Open My Application")
                    .setIntent(new Intent(getApplicationContext(), MainActivity.class)
                            .setAction(Intent.ACTION_MAIN))
                    .setIcon(IconCompat.createWithResource(getApplicationContext(), R.mipmap.ic_launcher))
                    .build();
            
            // Yêu cầu launcher ghim shortcut
            ShortcutManagerCompat.requestPinShortcut(
                    getApplicationContext(), 
                    shortcutInfo, 
                    null // PendingIntent callback (optional)
            );
            
            // Lưu flag đã tạo (tránh tạo trùng)
            getSharedPreferences("app_prefs", MODE_PRIVATE)
                .edit()
                .putBoolean(PREF_SHORTCUT_ADDED, true)
                .apply();
                
            Toast.makeText(this, "Shortcut creation requested", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Launcher does not support pin shortcut", Toast.LENGTH_LONG).show();
        }
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">
    
    <!-- Quyền tạo shortcut (cần cho một số launcher cũ) -->
    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
    
    <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>
            
            <!-- Cho phép activity nhận CREATE_SHORTCUT (launcher cũ) -->
            <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Lưu ý quan trọng

  1. User consent: Android 8.0+ hiển thị dialog xác nhận từ launcher, user phải đồng ý
  2. Launcher support: Không phải launcher nào cũng hỗ trợ pin shortcut
  3. Icon: Nên dùng adaptive icon (mipmap) cho nhất quán
  4. Intent action: Phải set Intent.ACTION_MAIN cho shortcut launcher
  5. Duplicate: Kiểm tra SharedPreferences tránh yêu cầu tạo trùng lặp

Static vs Dynamic Shortcuts

Loại Static Shortcuts Dynamic Shortcuts Pinned Shortcuts
Định nghĩa XML (res/xml/shortcuts.xml) Runtime qua ShortcutManager User pin từ app (như ví dụ)
Số lượng max 5 (static + dynamic) 5 (static + dynamic) Không giới hạn (do user quản lý)
Cập nhật Cần update app Runtime bất kỳ lúc App có thể update/disable
Backup/restore Tự động Tự động Không backup

Static Shortcuts XML (res/xml/shortcuts.xml)

<shortcuts xmlns:android="https://schemas.android.com/apk/res/android">
    <shortcut
        android:shortcutId="compose"
        android:enabled="true"
        android:icon="@drawable/ic_compose"
        android:shortcutShortLabel="@string/compose_shortcut_short"
        android:shortcutLongLabel="@string/compose_shortcut_long">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.myapplication"
            android:targetClass="com.example.myapplication.ComposeActivity" />
    </shortcut>
</shortcuts>

Khai báo trong Manifest: <meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" /> trong <activity>