我有一个 Activity A,它启动自定义选项卡。我需要知道自定义选项卡打开时,任务( Activity 所属的)是进入后台还是进入前台。
我知道这个问题 How to detect when an Android app goes to the background and come back to the foreground .这个问题提到的解决方案对我不起作用,因为一旦启动自定义选项卡,就会收到 onbackground 回调,这不是我想要的。当包含 Activity A 的任务进入后台时,我想要 onbackground 回调。
最佳答案
使用 CustomTabsCallback您可以使用 TAB_HIDDEN
收听选项卡何时隐藏(进入后台)回调或 TAB_SHOWN
callback when the Tab becomes visible (goes into foreground).
从文档:
TAB_HIDDEN
Sent when the tab becomes hidden.
TAB_SHOWN
Sent when the tab becomes visible.
下面是一个完整的工作示例,说明如何使用上述回调:
public class CustomTabsActivity extends AppCompatActivity {
private CustomTabsServiceConnection mCustomTabsServiceConnection;
private CustomTabsClient mCustomTabsClient;
private CustomTabsSession mCustomTabsSession;
private CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.customTabsButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomTabs();
}
});
initCustomTabs();
}
@Override
protected void onStart() {
super.onStart();
CustomTabsClient.bindCustomTabsService(this, "com.android.chrome", mCustomTabsServiceConnection);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void initCustomTabs() {
mCustomTabsServiceConnection = new CustomTabsServiceConnection()
{
@Override
public void onCustomTabsServiceConnected(@NotNull ComponentName componentName, @NotNull CustomTabsClient customTabsClient)
{
mCustomTabsClient = customTabsClient;
mCustomTabsClient.warmup(0L);
mCustomTabsSession = mCustomTabsClient.newSession(new CustomTabsCallback()
{
@Override
public void onNavigationEvent(int navigationEvent, Bundle extras) {
switch (navigationEvent)
{
case CustomTabsCallback.TAB_SHOWN:
//Sent when the tab becomes visible (goes into foreground)
break;
case CustomTabsCallback.TAB_HIDDEN:
//Sent when the tab becomes hidden (goes into background)
break;
}
}
});
builder.setSession(mCustomTabsSession);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mCustomTabsClient = null;
}
};
CustomTabsClient.bindCustomTabsService(this, "com.android.chrome", mCustomTabsServiceConnection);
}
private void showCustomTabs(){
builder.setShowTitle(true);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse("https://stackoverflow.com/"));
}
}
关于android - 任务进入后台或进入前台时回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69985252/