Zak*_*kir 8 android chrome-custom-tabs
在我的应用中,我通过Chrome自定义标签打开了一个网址.我们知道,当用户点按设备后退按钮或自定义后退按钮时,Chrome自定义标签将会关闭.是否可以通过编程方式关闭Chrome自定义标签,无需用户干预.
Fan*_*ock 14
目前没有这样的支持以编程方式关闭chrome自定义选项卡.但是,如果需要,可以通过启动Chrome自定义选项卡的上一个活动来关闭它.
让我们从" MainActivity " 打开chrome自定义标签,Chrome自定义标签中有一个选项菜单项" 关闭 ",在" 关闭 "菜单项单击中,您要关闭Chrome自定义标签并返回" MainActivity ",那么你可以通过启动" MainActivity "来实现.为此,请将您的活动launchMode设置为singleTask,然后FLAG_ACTIVITY_CLEAR_TOP在单击按钮时启动您的活动.
检查我的演示代码了解详细信息,希望它能帮助想要这样的人.
AndroidManifest.xml:
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".CustomTabReceiver"
android:enabled="true" />
Run Code Online (Sandbox Code Playgroud)
MainActivity.java:
public class MainActivity extends Activity {
public static String CHROME_PACKAGE_NAME = "com.android.chrome";
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
}
public void onClick(final View view) {
switch (view.getId()) {
case R.id.btnOpenChromeCustomTab:
launchChromeCustomTab();
break;
default:
return;
}
}
private void launchChromeCustomTab() {
Uri uri = Uri.parse("http://www.google.com/");
Intent intent = new Intent(mContext, CustomTabReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
CustomTabsIntent.Builder customTabsBuilder = new CustomTabsIntent.Builder();
customTabsBuilder.addMenuItem("Close", pendingIntent);
CustomTabsIntent customTabsIntent = customTabsBuilder.build();
customTabsIntent.intent.setPackage(CHROME_PACKAGE_NAME);
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
customTabsIntent.launchUrl(mContext, uri);
}
}
Run Code Online (Sandbox Code Playgroud)
CustomTabReceiver.java:
public class CustomTabReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
Run Code Online (Sandbox Code Playgroud)
activity_main.xml中:
<Button
android:id="@+id/btnOpenChromeCustomTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="onClick"
android:text="Open Chrome Custom Tab" />
Run Code Online (Sandbox Code Playgroud)
注意:在测试此代码之前
,请确保Chrome通过显式检查在设备上安装了已更新.因为在此演示代码中,Chrome自定义选项卡已通过设置硬编码包打开,com.android.chrome并且app可能会在未Chrome安装的系统上中断.
因此,请按照最佳做法启动Chrome自定义标签.
| 归档时间: |
|
| 查看次数: |
7579 次 |
| 最近记录: |