我正在尝试实现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"
。这有什么不对吗?
您将在以下行获得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;
}
});