作者:shao4224 | 来源:互联网 | 2023-02-01 16:55
如何解决《Chrome自定义标签:为什么CustomTabsClient.bindCustomTabsService()无法正常运行?》经验,为你挑选了1个好方法。
我正在尝试实现chrome自定义标签,但遇到以下运行时错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nirvan.customtabsexample/com.example.nirvan.customtabsexample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.customtabs.CustomTabsClient.warmup(long)' on a null object reference
这是我的代码:
CustomTabsClient mClient;
String packageName = "com.android.chrome";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Binds to the service.
CustomTabsClient.bindCustomTabsService(this, packageName, new CustomTabsServiceConnection() {
@Override
public void onCustomTabsServiceConnected(ComponentName name, CustomTabsClient client) {
// mClient is now valid.
Log.e("TAG","onCustumServiceConnected");
mClient = client;
}
@Override
public void onServiceDisconnected(ComponentName name) {
// mClient is no longer valid. This also invalidates sessions.
Log.e("TAG","onServiceDisconnected");
mClient = null;
}
});
mClient.warmup(0);
CustomTabsSession session = mClient.newSession(new CustomTabsCallback());
session.mayLaunchUrl(Uri.parse("https://www.google.com"), null, null);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.facebook.com/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
}
});
}
该应用程序一启动就会崩溃。另外,我没有获得2个日志输出中的任何一个,因此CustomTabsClient.bindCustomTabsService()
永远不会调用下面的两个方法。可能是什么问题?我认为这是我要传递给的软件包名称CustomTabsClient.bindCustomTabsService()
。我不知道要通过什么,所以我通过了"com.android.chrome"
。这是什么问题吗?
1> andreban..:
您NullPointerException
在以下行得到一个:
mClient.warmup(0);
这样做的原因是,一旦调用CustomTabsClient.bindCustomTabsService
,回调将异步运行。发生预热调用时,服务没有足够的时间连接并为分配一个值mClient
。将预热调用和mayLaunchUrl移到onConnected回调内部,它应该可以工作。
// Binds to the service.
CustomTabsClient.bindCustomTabsService(this, packageName, new CustomTabsServiceConnection() {
@Override
public void onCustomTabsServiceConnected(ComponentName name, CustomTabsClient client) {
// mClient is now valid.
Log.e("TAG","onCustomTabsServiceConnected");
mClient = client;
mClient.warmup(0);
CustomTabsSession session = mClient.newSession(new CustomTabsCallback());
session.mayLaunchUrl(Uri.parse("https://www.google.com"), null, null);
}
@Override
public void onServiceDisconnected(ComponentName name) {
// mClient is no longer valid. This also invalidates sessions.
Log.e("TAG","onServiceDisconnected");
mClient = null;
}
});