如何在WebView中对多个URL进行Facebook评论活动?

时间:2019-04-20 16:19:57

标签: android android-activity webview android-fragmentactivity facebook-sdk-4.0

我正在尝试构建Webview应用程序,以便用户可以使用Facebook评论活动在网页上发布评论。如果URL在Webview中不断变化,如何获取URL到FbCommentActivity.java。请注意,所有网页上均已安装Facebook Comment Plugin。

我尝试在Webview片段中使用“ TAG_LINK”,该片段在按下书签按钮时仍存储应用程序链接,但仍然无法正常工作。另请注意,如果我使用mWebViewComments.loadDataWithBaseURL(“ http://www.example.com”)注释正在加载,因为注释用于定义HTTP BaseURL方法失败的不同页面。 例如::i有两个网页http://example/page1http://example/page2。有多个网页时如何进行评论活动。 我也尝试过webview.getUrl()方法 例如:postUrl = webview.getUrl();但是当我单击注释fab按钮时,应用程序崩溃了。  请分享您的宝贵意见。我是android的新手,请帮帮我。

FbCommentsActivity.java

 package seacoders.abhilash.bogguru;


 import android.net.Uri;
 import android.net.http.SslError;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.support.v7.app.AppCompatActivity;
 import android.support.v7.widget.Toolbar;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.ViewGroup;
 import android.webkit.ConsoleMessage;
 import android.webkit.CookieManager;
 import android.webkit.SslErrorHandler;
 import android.webkit.WebChromeClient;
 import android.webkit.WebSettings;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
 import android.widget.FrameLayout;
 import android.widget.ProgressBar;
 import android.widget.Toast;
 import seacoders.abhilash.bogguru.HomeFragment;

 public class FbCommentsActivity extends AppCompatActivity {
  private static String TAG = FbCommentsActivity.class.getSimpleName();
  private WebView mWebViewComments;
  private FrameLayout mContainer;
  private ProgressBar progressBar;
  boolean isLoading;
  private WebView mWebviewPop;
  private String postUrl;
  //    public String webUrl = getIntent().getExtras().getString("webUrl");
  // error is coming from here, according the the error log.

  // the default number of comments should be visible
  // on page load.
  private static final int NUMBER_OF_COMMENTS = 8;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_fb_comments);
   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);
   getSupportActionBar().setDisplayHomeAsUpEnabled(true);

   mWebViewComments = (WebView) findViewById(R.id.commentsView);
   mContainer = (FrameLayout) findViewById(R.id.webview_frame);
   progressBar = (ProgressBar) findViewById(R.id.progressBar);
   progressBar.setVisibility(View.VISIBLE);

   postUrl = getIntent().getStringExtra("TAG_LINK");
   // finish the activity in case of empty url
   if (TextUtils.isEmpty(postUrl)) {
    Toast.makeText(getApplicationContext(), "The web url shouldn't be empty", Toast.LENGTH_LONG).show();
    finish();
    return;
   }

   setLoading(true);
   loadComments();
  }

  private void loadComments() {
   mWebViewComments.setWebViewClient(new UriWebViewClient());
   mWebViewComments.setWebChromeClient(new UriChromeClient());
   mWebViewComments.getSettings().setJavaScriptEnabled(true);
   mWebViewComments.getSettings().setAppCacheEnabled(true);
   mWebViewComments.getSettings().setDomStorageEnabled(true);
   mWebViewComments.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
   mWebViewComments.getSettings().setSupportMultipleWindows(true);
   mWebViewComments.getSettings().setSupportZoom(false);
   mWebViewComments.getSettings().setBuiltInZoomControls(false);
   CookieManager.getInstance().setAcceptCookie(true);
   if (Build.VERSION.SDK_INT >= 21) {
    mWebViewComments.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    CookieManager.getInstance().setAcceptThirdPartyCookies(mWebViewComments, true);
   }

   // facebook comment widget including the article url
   String html = "<!doctype html> <html lang=\"en\"> <head></head> <body> " +
    "<div id=\"fb-root\"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = \"//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6\"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> " +
    "<div class=\"fb-comments\" data-href=\"" + postUrl + "\" " +
    "data-numposts=\"" + NUMBER_OF_COMMENTS + "\" data-order-by=\"reverse_time\">" +
    "</div> </body> </html>";

   mWebViewComments.loadDataWithBaseURL(postUrl, html, "text/html", "UTF-8", null);
   mWebViewComments.setMinimumHeight(200);
  }

  private void setLoading(boolean isLoading) {
   this.isLoading = isLoading;

   if (isLoading)
    progressBar.setVisibility(View.VISIBLE);
   else
    progressBar.setVisibility(View.GONE);

   invalidateOptionsMenu();
  }

  private class UriWebViewClient extends WebViewClient {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {

    String host = Uri.parse(url).getHost();

    return !host.equals("m.facebook.com");

   }

   @Override
   public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    String host = Uri.parse(url).getHost();
    setLoading(false);
    if (url.contains("/plugins/close_popup.php?reload")) {
     final Handler handler = new Handler();
     handler.postDelayed(new Runnable() {
      @Override
      public void run() {
       //Do something after 100ms
       mContainer.removeView(mWebviewPop);
       loadComments();
      }
     }, 600);
    }
   }

   @Override
   public void onReceivedSslError(WebView view, SslErrorHandler handler,
    SslError error) {
    setLoading(false);
   }
  }

  class UriChromeClient extends WebChromeClient {

   @Override
   public boolean onCreateWindow(WebView view, boolean isDialog,
    boolean isUserGesture, Message resultMsg) {
    mWebviewPop = new WebView(getApplicationContext());
    mWebviewPop.setVerticalScrollBarEnabled(false);
    mWebviewPop.setHorizontalScrollBarEnabled(false);
    mWebviewPop.setWebViewClient(new UriWebViewClient());
    mWebviewPop.setWebChromeClient(this);
    mWebviewPop.getSettings().setJavaScriptEnabled(true);
    mWebviewPop.getSettings().setDomStorageEnabled(true);
    mWebviewPop.getSettings().setSupportZoom(false);
    mWebviewPop.getSettings().setBuiltInZoomControls(false);
    mWebviewPop.getSettings().setSupportMultipleWindows(true);
    mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
     ViewGroup.LayoutParams.MATCH_PARENT));
    mContainer.addView(mWebviewPop);
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(mWebviewPop);
    resultMsg.sendToTarget();

    return true;
   }

   @Override
   public boolean onConsoleMessage(ConsoleMessage cm) {
    Log.i(TAG, "onConsoleMessage: " + cm.message());
    return true;
   }

   @Override
   public void onCloseWindow(WebView window) {}
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
   if (!isLoading) {
    getMenuInflater().inflate(R.menu.fb_comments, menu);
   }

   return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
   if (item.getItemId() == android.R.id.home) {
    onBackPressed();
    return true;
   }

   if (item.getItemId() == R.id.action_refresh) {
    mWebViewComments.reload();
   }

   return super.onOptionsItemSelected(item);
  }
 }

HomeFragment.java

package seacoders.abhilash.bogguru;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.net.URI;
import java.util.ArrayList;
import seacoders.abhilash.bogguru.FavFragment;
import static seacoders.abhilash.bogguru.FavFragment.TAG_LINK;

public class HomeFragment extends Fragment {
 static WebView wv, cv = null;
 TextView txt;
 ProgressBar pbar;
 FloatingActionButton cmt, fav;
 Context mcontext;



 public static final String PREFERENCES = "PREFERENCES_NAME";
 String WEB_LINKS = "links";
 String WEB_TITLE = "title";
 //String PageURL = getActivity().getIntent().getStringExtra("url");
 public String current_page_url;
 public static final String TITLE = "Home";


 public static HomeFragment newInstance() {

  return new HomeFragment();
 }

 @Nullable
 @Override
 public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
  //return inflater.inflate(R.layout.fragment_home, container, false);
  setHasOptionsMenu(true);
  final View v = inflater.inflate(R.layout.fragment_home, container, false);
  wv = (WebView) v.findViewById(R.id.webview);
  wv.loadUrl("http://bogguru.we.bs/bogguru-android-mobile-application/webapp/index.html");
  current_page_url = "http://bogguru.we.bs/bogguru-android-mobile-application/webapp/";
  SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
  String links = sharedPreferences.getString(WEB_LINKS, null);
  if (links != null) {
   Gson gson = new Gson();
   ArrayList < String > linkList = gson.fromJson(links, new TypeToken < ArrayList < String >> () {}.getType());
  }

  if (getActivity().getIntent().getExtras() != null) {
   TAG_LINK = getActivity().getIntent().getStringExtra("url");
  }
  //facebook comment
  cmt = (FloatingActionButton) v.findViewById(R.id.fabcmt);
  cmt.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    // launching facebook comments activity
    Intent intent = new Intent(getActivity(), FbCommentsActivity.class);

    //fb comment passing the article url
    intent.putExtra("TAG_LINK", "http://www.bogguru.we.bs/");
    startActivity(intent);
   }
  });
  // end of fb comment
 }
}

activity_fb_comment.xml

<
android.support.design.widget.CoordinatorLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: fitsSystemWindows = "true"
tools: context = ".FbCommentsActivity" >

 <
 android.support.design.widget.AppBarLayout
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: theme = "@style/AppTheme.AppBarOverlay" >

 <
 android.support.v7.widget.Toolbar
android: id = "@+id/toolbar"
android: layout_width = "match_parent"
android: layout_height = "?attr/actionBarSize"
android: background = "?attr/colorPrimary"
app: popupTheme = "@style/AppTheme.PopupOverlay" / >

 <
 /android.support.design.widget.AppBarLayout>

 <
 LinearLayout
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: orientation = "vertical"
app: layout_behavior = "@string/appbar_scrolling_view_behavior" >

 <
 FrameLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android: id = "@+id/webview_frame"
android: layout_width = "match_parent"
android: layout_height = "match_parent" >

 <
 WebView
android: id = "@+id/commentsView"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: layout_gravity = "center_horizontal" / >

 <
 ProgressBar
android: id = "@+id/progressBar"
android: layout_width = "30dp"
android: layout_height = "30dp"
android: layout_alignParentBottom = "true"
android: layout_centerHorizontal = "true"
android: layout_gravity = "center"
android: layout_marginBottom = "10dp"
android: indeterminateTint = "@color/colorPrimary"
android: indeterminateTintMode = "src_atop" / >

 <
 /FrameLayout> <
 /LinearLayout>

 <
 /android.support.design.widget.CoordinatorLayout>

1 个答案:

答案 0 :(得分:0)

宾果!!!终于这对我有用。我在 FbCommentsActivity.java

中添加了以下几行
 WebView wv = (WebView) findViewById(R.id.webview);// my HomeFragment WEBVIEW
    postUrl = HomeFragment.wv.getUrl(); //get Url from Homefragment webview