这是ViewPager
中使用的片段。它显示YouTube视频。
但是我正在泄漏错误。如何通过YouTubeThumbnailView
上的应用程序上下文?一些用户能够使用此修复程序来修复它:https://stackoverflow.com/a/19812942/1237175。我尝试了,但没有成功...
public class DetailFragment extends Fragment implements OnCancelListener, YouTubeThumbnailView.OnInitializedListener{
ConnectionDetector con;
private static final String ARG_POSITION = "position";
public ViewGroup root;
private int position;
private SharedPreferences sharedPrefs = null;
TopNewsSliderActivity homeActivity;
WebView webView = null;
Post data = null;
private static final int REQUEST_INVITE = 0;
MoPubView moPubView = null;
RelativeLayout detailBck = null;
private YouTubeThumbnailView thumbnailView;
private boolean canHideStatusBar = false;
private Dialog errorDialog;
public static final int REQ_START_STANDALONE_PLAYER = 101;
private static final int REQ_RESOLVE_SERVICE_MISSING = 2;
private static final int RECOVERY_DIALOG_REQUEST = 1;
Activity activity = null;
public static Fragment newInstance(int position) {
DetailFragment f = new DetailFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
@Override
public void onAttach(Context context) {
homeActivity = (TopNewsSliderActivity) context;
super.onAttach(context);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
root = (ViewGroup) inflater.inflate(R.layout.top_news_details, null);
con = new ConnectionDetector(getActivity());
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
detailBck = (RelativeLayout) root.findViewById(R.id.detailBck);
try{
data = homeActivity.list_feeds.get(position);
FrameLayout youtubeLayout = (FrameLayout) root.findViewById(R.id.youtubeLayout);
ImageView overlayVideoPlay = (ImageView) root.findViewById(R.id.overlayVideoPlay);
if (!"".equals(data.videoUrl)) {
overlayVideoPlay.setVisibility(View.VISIBLE);
thumbnailView = new YouTubeThumbnailView(homeActivity.getApplicationContext());
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
thumbnailView.setLayoutParams(lp);
youtubeLayout.addView(thumbnailView,0);
thumbnailView.initialize(Config.YOUTUBE_API_KEY, this);
thumbnailView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
// Launch standalone YoutTube player
Intent intent = null;
intent = YouTubeStandalonePlayer.createVideoIntent(homeActivity, Config.YOUTUBE_API_KEY, data.videoUrl, 0, true, true);
if (intent != null) {
if (canResolveIntent(intent)) {
canHideStatusBar = true;
startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
} else {
// Could not resolve the intent - must need to install or update the YouTube API service.
YouTubeInitializationResult
.SERVICE_MISSING
.getErrorDialog(homeActivity, REQ_RESOLVE_SERVICE_MISSING).show();
}
}
}});
}else{
overlayVideoPlay.setVisibility(View.GONE);
}
TextView title = (TextView) root.findViewById(R.id.title);
title.setTextSize(Integer.parseInt(sharedPrefs.getString("fontSizeSettings", getString(R.string.default_font_size))) + 2);
TextView newsCategory = (TextView) root.findViewById(R.id.newsCategory);
TextView newsPublisher = (TextView) root.findViewById(R.id.newsPublisher);
RelativeLayout adContainer = (RelativeLayout) root.findViewById(R.id.adContainer);
if (!AppConstants.isPurchased){
if(AppConstants.platform == Platform.GOOGLE_PLAY && moPubView == null){
moPubView = new MoPubView(homeActivity);
AdManager.showAd(homeActivity, adContainer, moPubView, new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}else if(AppConstants.platform == Platform.AMAZON){
homeActivity.showAd(true, adContainer);
}
}
if(homeActivity.tf!=null && !homeActivity.isTamilFontDefault) {
newsPublisher.setTypeface(homeActivity.tf);
}
newsPublisher.setText(data.getPublisher());
TextView newsColorCode = (TextView) root.findViewById(R.id.newsColor);
if(data.getCategories()!=null) {
if(homeActivity.tf!=null && !homeActivity.isTamilFontDefault) {
newsCategory.setTypeface(homeActivity.tf);
}
newsCategory.setText(data.getCategories());
newsCategory.setTextColor(Color.parseColor(data.getColor_code()));
newsColorCode.setText((position + 1) + "");
LayerDrawable bgDrawable = (LayerDrawable) newsColorCode.getBackground();
final GradientDrawable shape = (GradientDrawable) bgDrawable.findDrawableByLayerId(R.id.shape_id);
shape.setColor(Color.parseColor(data.getColor_code()));
}
getActivity().runOnUiThread(new Runnable() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void run() {
webView = (WebView) root.findViewById(R.id.feedDetail);
webView.setVisibility(View.GONE);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(false);
webView.setInitialScale(100);
//webView.setBackgroundColor(Color.parseColor("#3498db")); // Flicker of colors when the application loads
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
////webView.setVerticalScrollBarEnabled(false);
//webView.setHorizontalScrollBarEnabled(false);
//webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
/*if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}*/
webView.setScrollContainer(false);
webView.setFocusable(false);
webView.setFocusableInTouchMode(false);
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
webView.setLongClickable(false);
webView.setHapticFeedbackEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
//forceWebViewRedraw(view);
/* view.loadUrl("javascript:(function() { var select = document.getElementsByClassName('content')[0]rn" +
" if(select)" +
" select.style.display = 'block';})()");*/
super.onPageFinished(view, url);
}
});
homeActivity.fetchNewsData(position, data, webView);
}
});
if(homeActivity.tf!=null){
title.setTypeface(homeActivity.tf);
}else {
title.setTypeface(null);
}
if(homeActivity.pd.getNightMode()==1 || !AppConstants.isDayMode){
detailBck.setBackgroundColor(ContextCompat.getColor(homeActivity, R.color.black));
title.setTextColor(ContextCompat.getColor(homeActivity, R.color.white));
}else {
detailBck.setBackgroundColor(ContextCompat.getColor(homeActivity, R.color.white));
title.setTextColor(ContextCompat.getColor(homeActivity, R.color.default_webtext));
}
SpannableString spanTitle = new SpannableString(data.getTitle());
spanTitle.setSpan(new StyleSpan(Typeface.BOLD), 0, spanTitle.length(), 0);
title.setText(spanTitle);
/*ImageView photoView = (ImageView) root.findViewById(R.id.backdrop);
boolean needReload;
String image_url = null;
if (data.getThumbnail()!=null && !data.getThumbnail().equals("")) {
image_url = data.getThumbnail();
needReload = true;
photoView.setVisibility(View.VISIBLE);
} else {
needReload = false;
photoView.setVisibility(View.GONE);
}
Log.e("IMAGE-URL->", image_url + "");
if (needReload) {
// Load image, decode it to Bitmap and display Bitmap in ImageView
//imageLoader.displayImage(image_url, photoView, options, animateFirstListener);
homeActivity.imageLoader.DisplayImage(image_url, photoView);
}*/
}catch (Exception e) {
e.printStackTrace();
}
//((ApplicationManager) getActivity().getApplication()).sendGA(nlActivity.t, "GridList Screen");
return root;
}
private boolean canResolveIntent(Intent intent) {
List<ResolveInfo> resolveInfo = getActivity().getPackageManager().queryIntentActivities(intent, 0);
return resolveInfo != null && !resolveInfo.isEmpty();
}
private void forceWebViewRedraw(final WebView webView)
{
webView.post(new Runnable() {
@Override
public void run()
{
webView.invalidate();
if(!getActivity().isFinishing())
webView.postDelayed(this, 1000);
}
});
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if((isVisible() && isVisibleToUser) && (isResumed() || webView!=null)){
webView.setVisibility(View.VISIBLE);
}
}
@Override
public void onResume() {
ApplicationManager.setCurrentContext(getActivity());
super.onResume();
if(data!=null && (!data.getThumbnail().equals("") && data.videoUrl.equals(""))){
homeActivity.unlockAppBarOpen();
}else{
homeActivity.lockAppBarClosed();
}
boolean isLandscape = false;
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
isLandscape = true;
}
else {
isLandscape = false;
}
if (canHideStatusBar && this.isVisible() && isLandscape) {
//Utils.hideStatusBar(getActivity());
canHideStatusBar = false;
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
try {
if(moPubView!=null){
moPubView.setBannerAdListener(null);
moPubView.destroy();
moPubView = null;
}
if (homeActivity.clientXML != null) {
homeActivity.clientXML.cancelRequests(homeActivity, true);
Log.e("Aync -> OnDestroy ", position + "--> canceled!!!");
homeActivity.clientXML = null;
}
}catch (Exception e){
}
super.onDestroy();
}
@Override
public void onCancel(DialogInterface arg0) {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 303){
/*homeActivity.updateSettingsUI();
homeActivity.refreshListUI();*/
}
}
@Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader thumbnailLoader) {
thumbnailLoader.setVideo(data.videoUrl);
}
@Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
if (errorDialog == null || !errorDialog.isShowing()) {
errorDialog = errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST);
errorDialog.show();
}
} else {
String errorMessage = "error ";//String.format(getString(R.string.error_thumbnail_view), errorReason.toString());
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
}
}
}
这是生成的错误:
06-16 20:09:40.488 30636-30636/com.androplus.tamilnewsHD E/ActivityThread: Activity com.androplus.activity.TopNewsSliderActivity has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@95bae77 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.androplus.activity.TopNewsSliderActivity has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@95bae77 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1092)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:986)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1303)
at android.app.ContextImpl.bindService(ContextImpl.java:1286)
at android.content.ContextWrapper.bindService(ContextWrapper.java:604)
at com.google.android.youtube.player.internal.r.e(Unknown Source)
at com.google.android.youtube.player.YouTubeThumbnailView.initialize(Unknown Source)
at com.androplus.fragment.DetailFragment.onCreateView(DetailFragment.java:124)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18809)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2112)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1520)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:60
您的Fragment
必须连接到Activity
,并且活动可以通过使用getapplicationcontext()
从活动中访问应用程序上下文。因此,您需要将Activity
(本身)作为参数传递给片段,作为构造函数参数之一。从那里您可以按照之前的建议获取应用程序上下文。
例如:
如果您的活动称为MainActivity
,
Fragment detailFragment = DetailFragment.newInstance(pos, MainActivity.this);
那么您的片段的getInstance
也将具有新的参数。
public static Fragment newInstance(int position, Activity activity) {
DetailFragment f = new DetailFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
this.activity = activity; //getting the activity.
return f;
}
,然后您可以在任何地方访问上下文
activity.getApplicationContext;
然后,您可以使用App Context进行视图而不是FindViewById,并使用parentView.addView(thumbnailView)
,
thumbnailView = (YouTubeThumbnailView) root.findViewById(R.id.youtubethumbnailview);
to
thumbnailView = new YouTubeThumbnailView(activity.getApplicationContext);
// you will have to set attributes dynamically as well, like width and height etc.