要在应用程序中打开一个简单的 Trusted Web Activity(TWA),您需要进行以下步骤:
build.gradle
文件中,确保您已经引入了 AndroidX 的支持库。确保以下行在 dependencies
块中存在:implementation 'androidx.browser:browser:1.3.0'
TwaActivity
。import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.browser.customtabs.CustomTabsIntent;
public class TwaActivity extends AppCompatActivity {
private static final String TWA_URL = "https://example.com"; // 替换为您的 TWA URL
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twa);
// 创建一个 CustomTabsIntent 对象
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
// 设置 TWA URL 和 Toolbar 颜色
builder.setToolbarColor(getResources().getColor(R.color.colorPrimary));
builder.setShowTitle(true);
// 构建 CustomTabsIntent 并启动 TWA Activity
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(TWA_URL));
finish(); // 结束当前 Activity,使用户无法通过返回按钮返回到此处
}
}
请确保将 TWA_URL
替换为您打算在 TWA 中加载的网址。
AndroidManifest.xml
文件中,将 TwaActivity
添加为一个新的
:
现在您可以通过启动 TwaActivity
来打开您的 TWA。请确保将 TwaActivity
的 theme
设置为没有 ActionBar
,以便 TWA 可以显示在全屏模式下。
请注意,为了使您的应用程序支持 TWA,您需要将 Digital Asset Links 文件发布到您的网站,并在应用程序和网站之间建立信任关系。您可以在 Android 开发者文档中了解更多关于 TWA 的详细信息。