有三种方式 Intent 、 URL Scheme 、 AppLinks 可以唤醒Android App。 部分Android手机可能没有GMS服务,本文不讨论AppLinks方式。

配置 AndroidManifest.xml

在AndroidManifest.xml中配置以下信息,主要是暴露唤醒方式和scheme。

本文假设包名为 com.test.myapp 、自定义scheme为 testscheme、被唤醒的Activity为TestEntryActivity

<?xml version="1.0" encoding="utf-8"?>
<manifest >
    <application
       
        <!--  通过 INTENT  URL SCHEME  唤醒自己-->
        <activity
            android:name="com.test.myapp.TestEntryActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:exported="true"
            android:taskAffinity="com.test.myapp"
            android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="testscheme" />
            </intent-filter>
        </activity>

    </application>

</manifest>

创建 Activity

在包名com.test.myapp创建TestEntryActivity代码文件,代码内容如下:

public class TestEntryActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 全新唤醒
        Intent intent = getIntent();
        Uri uri = intent.getData();
        handleUri(uri,true);
        finish();
    }

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

        // 后台切前台
        Uri uri = intent.getData();
        handleUri(uri,false);
        finish();
    }
    private void handleUri(@NonNull Uri uri,boolean isColdLanuch)
    {
        if (isColdLanuch) {
            // 冷启动,应先运行App初始化业务逻辑,如Splash、检查账号权限、SDK初始化等
            // 待App业务初始化完成后,再处理外部唤醒事件
            return;
        }
        // 根据uri内容分发到对应的页面或者模块
    }
}

外部唤醒

以浏览器为例:

<!doctype html>
<html> 
    <head> 
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <title>唤醒测试</title>
    </head>
    <body> 
        <a href="intent://xxxx/yyy?zzz=123#Intent;scheme=testscheme;package=com.test.myapp;end">通过Intent唤醒</a>
        <a href="testscheme://xxxx/yyy?zzz=123">通过URL Scheme唤醒</a>
    </body>
</html>