You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过二维码启动Android健身App并打开指定训练项目?

Hey there! Let's break down how to get your Gym Assistant app to open specific training sessions via QR codes. I’ve implemented similar deep linking functionality for fitness apps before, so here’s a step-by-step solution:

1. What Your QR Code Should Contain

Instead of just gymassistant://, you need to add parameters or a path to identify the specific training item. There are two common patterns you can use:

Option A: Query Parameter Style

Great for numeric IDs (like database IDs for your training sessions):

gymassistant://trainingsession?id=123
  • gymassistant = your custom scheme (matches what you’ll configure in the Manifest)
  • trainingsession = a host name (you can name this anything, e.g., app or training)
  • id=123 = the unique identifier for your specific training item

Option B: Path Style

Better for human-readable training names (like "leg-day" or "push-workout"):

gymassistant://training/leg-day
2. Manifest Configuration

You need to update your AndroidManifest.xml to tell Android which Activity should handle these deep links. Make sure to set android:exported="true" (required for Android 12+ to allow external apps like QR scanners to launch your Activity).

Here’s the code for the target Activity (e.g., TrainingDetailActivity):

<activity
    android:name=".TrainingDetailActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <!-- Required to allow the Intent to be launched from other apps -->
        <category android:name="android.intent.category.DEFAULT" />
        <!-- Required to make the link browsable (for QR scanners/browsers) -->
        <category android:name="android.intent.category.BROWSABLE" />

        <!-- Handle query parameter style links -->
        <data
            android:scheme="gymassistant"
            android:host="trainingsession" />

        <!-- Optional: Handle path style links (uncomment if using option B) -->
        <!-- <data
            android:scheme="gymassistant"
            android:host="training"
            android:pathPattern="/.*" /> -->
    </intent-filter>
</activity>

Once the QR scanner launches your TrainingDetailActivity, you need to parse the incoming Intent to extract the training ID/name and load the corresponding content.

Kotlin Example

class TrainingDetailActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_training_detail)
        // Process the intent when the Activity is created
        handleDeepLink(intent)
    }

    // If the Activity is already running, onNewIntent will be called instead
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleDeepLink(intent)
    }

    private fun handleDeepLink(intent: Intent?) {
        intent?.data?.let { uri ->
            when (uri.host) {
                "trainingsession" -> {
                    // Extract the training ID from the query parameter
                    val trainingId = uri.getQueryParameter("id")
                    trainingId?.let {
                        // Load your training content using this ID (e.g., from a database/API)
                        loadTrainingSessionById(it)
                    } ?: run {
                        // Invalid or missing ID: redirect to home screen with error
                        showErrorAndGoHome()
                    }
                }
                "training" -> {
                    // Extract the training name from the path
                    val trainingName = uri.path?.removePrefix("/")
                    trainingName?.let {
                        loadTrainingSessionByName(it)
                    } ?: showErrorAndGoHome()
                }
                else -> showErrorAndGoHome()
            }
        } ?: showErrorAndGoHome()
    }

    private fun loadTrainingSessionById(id: String) {
        // Replace with your actual business logic:
        // 1. Fetch the training session from your data source
        // 2. Populate the UI with the training details (exercises, sets, reps, etc.)
        Toast.makeText(this, "Loading training session #$id", Toast.LENGTH_SHORT).show()
    }

    private fun loadTrainingSessionByName(name: String) {
        Toast.makeText(this, "Loading training: $name", Toast.LENGTH_SHORT).show()
    }

    private fun showErrorAndGoHome() {
        Toast.makeText(this, "Invalid training link", Toast.LENGTH_SHORT).show()
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }
}

Java Example (if you’re not using Kotlin)

public class TrainingDetailActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_training_detail);
        handleDeepLink(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleDeepLink(intent);
    }

    private void handleDeepLink(Intent intent) {
        if (intent != null && intent.getData() != null) {
            Uri uri = intent.getData();
            switch (uri.getHost()) {
                case "trainingsession":
                    String trainingId = uri.getQueryParameter("id");
                    if (trainingId != null) {
                        loadTrainingSessionById(trainingId);
                    } else {
                        showErrorAndGoHome();
                    }
                    break;
                case "training":
                    String trainingName = uri.getPath();
                    if (trainingName != null) {
                        trainingName = trainingName.substring(1); // Remove leading "/"
                        loadTrainingSessionByName(trainingName);
                    } else {
                        showErrorAndGoHome();
                    }
                    break;
                default:
                    showErrorAndGoHome();
                    break;
            }
        } else {
            showErrorAndGoHome();
        }
    }

    private void loadTrainingSessionById(String id) {
        Toast.makeText(this, "Loading training session #" + id, Toast.LENGTH_SHORT).show();
    }

    private void loadTrainingSessionByName(String name) {
        Toast.makeText(this, "Loading training: " + name, Toast.LENGTH_SHORT).show();
    }

    private void showErrorAndGoHome() {
        Toast.makeText(this, "Invalid training link", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}
4. Testing Tips
  • Use an online QR code generator to create a QR code with your custom URI (e.g., gymassistant://trainingsession?id=123).
  • Test with a QR scanner app or your phone’s built-in camera (most modern Android phones can scan QR codes directly from the camera app).
  • If the app doesn’t open, double-check:
    • android:exported="true" is set on the Activity.
    • The intent-filter in the Manifest matches your QR code’s URI scheme/host.
    • You’re handling the Intent correctly in the Activity.

内容的提问来源于stack exchange,提问作者user9313301

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:37:08