How to integrate Disqus in my Android App? - android

I am developing an android app for a web-site. The web-site supports Disqus for commenting service. I want to support the same in my application. I got APIs from Disqus docs but still I am not clear how to integrate them in my application. Please help me understand the implementation. Is anyone integrated Disqus comment service into their Android App?

I ran into the same problem with having my web site disqus threads linked up with my android app. I wrote a little walkthrough if you are interested I will link to my walkthrough below. Basically in your android app you want to use a WebView and use a separate php file that can take your disqus identifier.
http://globeotter.com/blog/disqus-android-code/

Thanks ndgreen. Seeing your idea I created a something different without a PHP file necesity:
https://gist.github.com/bichotll/5563926
This script just create the html from a simple function and load th.

You can use this code :
Google Login is working.
I did not tested Facebook yet.
static void setupDisqus(Context context, WebView disqus) {
try {
String URL = ""; // URL must be unique like identifier! Because Disqus, is using the url instead of identifier.
String identifier = "";
String shortName = "";
String commentsUri = "https://captainsp.github.io/disqus_comments_dark_gray.html?" + "shortname=" + shortName +
"&url=" + URLEncoder.encode(URL, "UTF-8") +
"&title=" + URLEncoder.encode("Comments", "UTF-8") +
"&identifier=" + URLEncoder.encode(identifier, "UTF-8");
/*
* You can use this colors in my Github Account:
* disqus_comments_dark_gray.html
* disqus_comments.html
* disqus_comments_dark.html
*
*
*/
disqus.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
new Handler().postDelayed(disqus::reload, 2000); // Reload Comments
super.onReceivedError(view, request, error);
}
});
CookieManager.getInstance().setAcceptThirdPartyCookies(disqus, true); // Accept Cookies to login (If you forget this part users need to login every single time)
disqus.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // Google / Facebook Login
disqus.getSettings().setSupportMultipleWindows(true); // Google / Facebook Login
CookieManager.getInstance().setAcceptCookie(true); // Accept Cookies to login 2
disqus.setWebChromeClient(new WebChromeClient() {
#SuppressLint("SetJavaScriptEnabled")
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
WebView newWebView = new WebView(context); // Create new WebView
WebSettings webSettings = newWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUserAgentString(webSettings.getUserAgentString().replace("; wv", "")); // Hide WebView User Agent
final Dialog dialog = new Dialog(context); // Create Dialog
dialog.setContentView(newWebView);
dialog.show();
CookieManager.getInstance().acceptThirdPartyCookies(newWebView);
newWebView.setWebViewClient(new WebViewClient());
newWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
dialog.dismiss(); // Close the dialog after logged in
}
});
((WebView.WebViewTransport) resultMsg.obj).setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
disqus.getSettings().setJavaScriptEnabled(true); // Enable JavaScript
disqus.getSettings().setAppCacheEnabled(true);
disqus.getSettings().setDomStorageEnabled(true);
disqus.loadUrl(commentsUri);
} catch (Exception e) {
e.printStackTrace();
}
}
First create a new WebView or find it with findViewById(R.id.webView);
Then setup Disqus to your WebView: setupDisqus(this,webView);
More information : https://help.disqus.com/en/articles/1717165-javascript-embed-in-native-apps

Related

Android webview detect specific page change

I have an android webview app with user authentication, the app allows users to register their devices by collecting the device's android id. When a user runs the mobile app, it will check if the mobile device is registered then validates the login details associated with the registered device. All works as designed with no issue.
My problem is that when the PHP session expires, users will be directed to the login page. If the user closes the app and re-open it, it will log the user without having to re-enter the login details. PHP session time-out can not be changed due to company policy.
I would like to know if I could detect the login page URL change and send the device android id with the login page URL similar to the app startup process. So, when the PHP session expires, users will be automatically logged back in without having to re-enter their login credentials.
Here is the current code I am using, some irrelevant codes have been removed to reduce the code lines. This is my first android app, and I have very limited experience when it comes to mobile programming and I have been searching for the last couple of day without any luck. Help and directions are highly appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean isConnct = false;
// code here to check internet connection
// end of internet connection code
if (isConnct){
// internet is ok
final WebView webView = (WebView)findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.imageLoading1).setVisibility(ImageView.GONE);
findViewById(R.id.webView).setVisibility(webView.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
// show error message
}
});
// using setWebChromeClient to enable javascript
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
// js confirm code
}
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
// js alert code
}
});
// enable javascript and other settings
String url = "https://www.domainname/login/" + android.provider.Settings.Secure.getString(getContentResolver(), Secure.ANDROID_ID);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setSupportZoom(true);
webSettings.setDefaultTextEncodingName("utf-8");
webView.loadUrl(url);
} else {
// show error message
}
}
try override shouldOverrideUrlLoading method in WebViewClient, check your login URL and start your auto-login from there
another approach is checking cookies expiration time, you may use CookieManager.getInstance() for this
This is what I ended up doing, and it seems working as expected, when PHP session expires, registered devices will be redirected to the index page with new session without having to re-enter user credentials.
If there is a logout button then you need to consider adding different procedure for the logout to allow users to logout and re-direct to login page.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(ImageView.GONE);
//show webview
findViewById(R.id.webView).setVisibility(webView.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
// show error message
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contentEquals("https://www.domainme/login")){
String url2 = "https://www.domainme/login/" + android.provider.Settings.Secure.getString(getContentResolver(), Secure.ANDROID_ID);
webView.loadUrl(url2);
return true;
}else {
return false;
}
}
// code truncated
}

Issue in loading URL in webview android

I need to show a login webpage link in webview and the link is something like below
url = "https://test-dev.test.com/as/authorization.oauth2?client_id=com.test.td&response=code&value=id test mail&redirect_uri=com.test.ap://oauth2/test";
[Modifed the actual URL with different names]
On this page, we have to enter username and password. Clicking on login will take you to OTP screen, after entering the OTP result will be a url response and from this I need to read the code. Using this code I have to make a request to get the authentication token for the session. For token request, response will be Json.
Now I need help in resolving the below:
Currently its opening in browser and not in webview. But other links are opening in webview within the app except the above link.
Which is the call back method for handling response from this transaction.
Below is my code:
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(getAuthorizationURL());
webView.setHorizontalScrollBarEnabled(false);
webView.setWebContentsDebuggingEnabled(true);
// webView.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
}
private String getAuthURL() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("test-dev.test.com")
.appendPath("ta/authorization.oauth2")
.appendQueryParameter("client_id", "com.test.td")
.appendQueryParameter("response", "code")
.appendQueryParameter("value", "id test mail").appendQueryParameter("redirect_uri", "com.test.ap://oauth2/test")
String url = Uri.decode(builder.build().toString());
//url = "https://www.google.com/";
// url = "https://developers.google.com/webmaster-tools/search-console-api/about";
return url;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
System.out.println(" shouldOverrideUrlLoading :============ " + Uri.parse(url).getHost() + " url " + url);
// if(url.contains("dev.test.com")){
// webView.loadUrl(url);
// return false;
// }
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
return true;
}
}
This sounds like you're doing an OpenID authentication. You're implementation of shouldOverrideUrlLoading() is both firing an intent which will most likely go to the default web browser, and returning true. The return value tells Android whether you're taking control of loading the page (true) or leaving it to the web view (false). If you don't take control of handling the URL, the web view will try to load it like a normal page.
You're also immediately directing the web view to your authorization URL in your onCreate code. I'm thinking this is part of the confusion over the navigation behavior you're seeing.
For this kind of authentication process, you don't want to override loading the OTP page. Let the web view handle that just like anything else. What you want to do is capture the URL response. Your if statement within shouldOverrideUrlLoading should trap the response URL, consume the contents, and respond true to let the web view know you've taken care of that URL. Everything else should be handled by the web view.
Finally, the commented version of the code looks to me like it would send you into an infinite loop, the way you have it written. You're telling the web view to load the authorization URL, which will lead back to your web client code, which will trap the URL, causing it to load the URL...

How to parse webview for Oauth 2.0 code in android

I'm trying to allow users in my android app to log in to their google account so i can access their contacts for the purpose of creating a friends list, and I'm trying to use OAuth to do this.
So far I have formed the URL and have created the webview which loads the page. I proceed to sign in but i dont know how to assign the code from the URL to the code value in my activity. also i don't know whether my Onpagestarted method is working correctly
Can someone either tell me either an alternate method/technique to authenticate with google using OAuth2 or tell me what are the issues with my current way as once I reach the page with the code my view remains the WebView and not the textview with the code as I want it to?
I would like to automate the entire process after the User has signed into the google page in my WebView but so far my code keeps getting stuck at the page with the Authcode which leads me to believe that the Authcode is not being detected by my program.
NOTE: I do not want to simply use the account that is signed into the Android Device (unless obviously the user chooses to enter the same account)
This is the code from the Activity in which I want to acquire the Auth Code/Token and get the Contacts for my User though I don't mind displaying the contacts in a later activity.
WebView browser;
final String username = "gotsingh#gmail.com";
private myWebViewClient client;
String code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_friends);
browser = (WebView) findViewById(R.id.webview);
client = new myWebViewClient();
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
browser.setWebViewClient(client);
getAuthCode(client);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_friends, menu);
return true;
}
public void getAuthCode(myWebViewClient myClient){
browser.loadUrl(url4);
while (myClient.authCode!= null){
showCode(myClient);}
}
public void showCode(myWebViewClient myClient){
code = myClient.authCode;
TextView text = new TextView(this);
text.setText(code);
setContentView(text);
}
Below is my modified WebViewClient class
public class myWebViewClient extends WebViewClient{
boolean authComplete = false;
String authCode = null;
#Override public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
if (url.contains("?code=") && authComplete != true) {
int codeStart = url.indexOf("?code=")+6;
authCode = url.substring(codeStart);
Log.i("", "AUTHCODE : " + authCode);
authComplete = true;
System.out.println(authCode);
}else if(url.contains("error=access_denied")){
Log.i("", "ACCESS_DENIED_HERE");
authComplete = true;
}
}
}
Also, if I could get some general guidance on doing POST/GET requests in java to recieve JSON data from google. I am very new to android development and I have close to 0 experience dealing with html/http requests.
Take a look at this sample. It is not against Google, but the principles are the same. You may want to consider using the "implicit" flow in OAuth to avoid storing secrets in the device.

Blank empty page in android webview after facebook login using javascript

i am developing a new android application,and using a webview to view my website in one the website pages there is a link for login with facebook
after logging directly, it returns a blank and embty webview
i have seen couple of topics here regarding the same issue but it is not exactly like mine
please note that if i am using normal desktop browser the issue is not there
I assume that there is a property of the webview should be adjusted , below my webview code
webView1=(WebView)findViewById(R.id.webView1);
webView1.setWebViewClient(new MyWebViewClient());
WebView webView1 = (WebView) findViewById(R.id.webView1);
webView1.setWebChromeClient(new WebChromeClient());
webView1.getSettings().setAppCacheEnabled(true);
webView1.getSettings().setDatabaseEnabled(true);
webView1.getSettings().setDomStorageEnabled(true);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView1.getSettings().setGeolocationEnabled(true);
webView1.loadUrl("http://www.myactivepoint.com/mobile/maplp.asp");
i really approciate your support
I had a similar experience with you. I solved the problem by the following methods.
public class CustomWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
if(url.startsWith("https://m.facebook.com/dialog/oauth")){
String redirectUrl = "http://www.mydomain.com/myReturnUrl";
view.loadUrl(redirectUrl);
return;
}
super.onPageFinished(view, url);
}}
and just add it to your WebView
webview.setWebViewClient(new CustomWebViewClient());
This is my solution. After successfull login you have to redirect the page. You can get the address from refsrc parameter in the Facebook URL, but sometimes (e.g. next try to log in) refsrc is missing so I use domain parameter. You can override the URL address if you need. See the code:
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(final WebView view, final String url)
{
if(getActivity()!=null)
{
if(url.contains("facebook.com") && url.contains("dialog/oauth") &&
(url.contains("&refsrc") || url.contains("&domain")))
{
Uri uri = Uri.parse(url);
String callbackUrl = uri.getQueryParameter("refsrc");
if(callbackUrl==null)
callbackUrl = "http://" + uri.getQueryParameter("domain");
view.loadUrl(callbackUrl); // callback URL
}
}
}
}

Android Webview Facebook Login

In my app, I want to make users be able to login with their Facebook account. After some searches, I am able to figure out this although I don't think this way is the best method. I used a webview in my UI, and a webviewclient to sense url switchings. As I understand, On Android, I must handle all redirections in my webviewclient (Facebook redirections, several redirections happen when user set the his/her email and password). But all I need is to parse my output xml and make a decision according to output result(redirect to my home activiy or failure etc). Here is my code, Please give your suggestions if more suitable method exists.
public class FbLoginActivity extends Activity {
String fbLoginBaseUrl = "{my server url}/facebook/redirector.jsp?";
private ProgressDialog progressBar;
WebView webView;
int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_login);
fbLoginBaseUrl += "usdId=NoSession:";
fbLoginBaseUrl += Subroutines.getInstance().getDeviceId() + "_L";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
progressBar = ProgressDialog.show(FbLoginActivity.this, "", "Page is loading...");
webView.setWebViewClient(new HelloWebViewClient());
webView.loadUrl(fbLoginBaseUrl);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.v(Subroutines.TAG, url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
Log.i(Subroutines.TAG, "Finished loading URL: " +url);
// if login screen loading finishes, cancel the progressdialog..
// twice redirecting happens to this sub url..
String subFace = "m.facebook.com/login.php";
if(url.indexOf(subFace) != -1 && ++count == 2){
if (progressBar.isShowing()) {
progressBar.cancel();
}
}
// Permission redirecting..
String loginSub = "www.facebook.com/connect/uiserver.php?method=permissions.request";
if(url.indexOf(loginSub) != -1){
progressBar = ProgressDialog.show(FbLoginActivity.this, "", "Logging in...");
}
// finally if my server makes a response..
String sub = "{my server url}/facebook/connect.jsp";
if(url.indexOf(sub) != -1){
Log.v(Subroutines.TAG, "my server makes a response..");
// xml parsing stuff..
// use url content to parse
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(Subroutines.TAG, "Error: " + description);
}
}
}
I would get the Facebook SDK and use their functions
In a nutshell you do this:
public Facebook facebook = new Facebook("appID");
Then in on create or wherever:
facebook.authorize(this,String[] YourNeededPermissions, new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
You can see this here: http://developers.facebook.com/docs/guides/mobile/#android
I have actually a similar problem in integrating the facebook registration with my own (but I'm not the android developer).
I asked the question here Facebook registration flow from Android
but I didn't know about the webview. That seems a good solution, can I contact you by chat or other means?
EDIT:
Facebook just updated their login procedure:
https://developers.facebook.com/docs/offline-access-deprecation/
as you can see, now the token you get from SSO (or any other client token) is linked only to your application (there is a validation token-app id-app secret).
The endpoint is now
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
So using the facebook sdk for android the steps are:
1) get the user signed
2) send the token to the server
3) server will validate the token against its app id and app secret
4) add your own security features

Categories

Resources