当活动恢复并且我从接收器应用程序收到消息时,对我的片段的引用为null。在活动的原始启动时,收到回调的消息可以在我的片段中调用一个方法而没有任何问题。但是,一旦应用程序关闭,恢复并重新附加消息回调,如果我尝试在onResume中保留对片段的引用,则片段似乎返回null或者我得到“片段未附加到活动”错误。令我感到困惑的是,片段在onResume函数中不为null,但它在messageReceived回调中...
这是我的代码:
class DashboardCastMainChannel implements Cast.MessageReceivedCallback {
public String getNamespace() {
return "urn:x-cast:myapp";
}
@Override
public void onMessageReceived(CastDevice castDevice, String namespace, String message) {
//Returns null only after activity resume
DashboardCastFragment fragment = (DashboardCastFragment) getFragmentManager().findFragmentById(R.id.dashboard_main_fragment);
JSONObject messageJSON;
try {
messageJSON= new JSONObject(message);
fragment.handleMediaMessage(messageJSON); //Crashes because fragment is null after resume
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
protected void onResume () {
super.onResume();
//Fragment exists and not null
mainFragment = (DashboardCastFragment) getFragmentManager().findFragmentById(R.id.dashboard_main_fragment); //Fragment exists and not null
int playServicesAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (playServicesAvailable == ConnectionResult.SUCCESS) {
mediaRouter.addCallback(mediaRouteSelector, mediaRouterCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
//Attach message listener back to activity
if (castChannel != null) {
try {
Cast.CastApi.setMessageReceivedCallbacks(
apiClient,
castChannel.getNamespace(),
castChannel);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
} catch (IllegalStateException e) {
Log.e(TAG, "Failed to setup media channel", e);
}
}
} else {
GooglePlayServicesUtil.getErrorDialog(playServicesAvailable, this, 1).show();
}
}
@Override
protected void onPause () {
mediaRouter.removeCallback(mediaRouterCallback);
if (castChannel != null) {
try {
Cast.CastApi.removeMessageReceivedCallbacks(
apiClient,
castChannel.getNamespace());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onPause();
}
这是我的错误日志:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.rir.dashboardcast.DashboardCastFragment.handleMediaMessage(org.json.JSONObject)' on a null object reference
at com.rir.dashboardcast.DashboardCastActivity$DashboardCastMainChannel.onMessageReceived(DashboardCastActivity.java:582)
at com.google.android.gms.internal.ij$c$4.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
提前谢谢