I have created webview app, and the app opens up with a with a blank white screen. It does not load anything even on reloading the webpage using swipetorefresh
MainActivity.java
package app.freeairdrop.io;
import ...
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
// webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
webView.loadUrl("https://freeairdrop.io/");
mySwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
// ATTENTION: This was auto-generated to handle app links.
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
webView.loadUrl(String.valueOf(appLinkData));
}
private class WebViewClientDemo extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
// finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (this.webView.canGoBack()) {
this.webView.goBack();
return;
}
Builder dialog = new Builder(this);
// dialog.setTitle((CharSequence) "Exit App");
dialog.setMessage((CharSequence) "Do You Want To Exit The App ?");
dialog.setPositiveButton((CharSequence) "YES", (OnClickListener) new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
});
dialog.setCancelable(false);
dialog.setNegativeButton((CharSequence) "CANCEL", (OnClickListener) new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
AndroidManifest.xml File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="app.freeairdrop.io"
>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:appCategory="productivity"
android:hardwareAccelerated="true"
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="app.freeairdrop.io.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="freeairdrop.io" />
</intent-filter>
</activity>
</application>
</manifest>
The deeplinks to app are working perfectly great, just the app opens everytime with a blank screen.
try
webView.getSettings().setDomStorageEnabled(true)
First, please you check HAXM /hrdware accelerate is Run and installed on android studio.
Second, please use chrome browser as default client browser for your webview on your device.
Third, uninstall your apk installed for this project, and restart device, and then , create new build/install this project or your device....
and you can follow the instruction for other like, enable hardware accelerate in manifest, using webchromeclient and etc... it work for me
Related
I have created an Android app. Whenever someone opens the website through the app, it goes to the exact link. But if the user opens another link, the app is still on the previous opened link. You can check the app here: https://play.google.com/store/apps/details?id=app.freeairdrop.io
Send these 2 link to yourself on Telegram, or Whatsapp:
https://freeairdrop.io/airdrop/morpher.html
https://freeairdrop.io/airdrop/simbcoin.html
Now open the first link in my app, when prompted to choose application. Switch back to Telegram/whatsapp, and click on second link. My app will open, but it's still on that page(first link).Nothing happens, the app is not able to load second link, unless app is closed.
MainActivity.java code:
package app.freeairdrop.io;
import...
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
private boolean mShouldPause;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
mySwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
// ATTENTION: This was auto-generated to handle app links.
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
if (getIntent().getExtras() != null) {
if (appLinkData == null){
webView.loadUrl("https://freeairdrop.io/");
}else
webView.loadUrl(String.valueOf(appLinkData));
} else if (getIntent().getExtras() == null){
webView.loadUrl("https://freeairdrop.io/");
}webView.reload();
}
private class WebViewClientDemo extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toasty.error(getApplicationContext(), "No Internet, pull down to refresh when you're connected to internet", Toast.LENGTH_LONG, true).show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (this.webView.canGoBack()) {
this.webView.goBack();
return;
}
else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
AndroidManifest Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="app.freeairdrop.io">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:appCategory="productivity"
android:hardwareAccelerated="true"
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".ApplicationClass"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="app.freeairdrop.io.MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize|screenLayout"
android:resizeableActivity="false"
android:supportsPictureInPicture="false"
android:launchMode="singleInstance"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="freeairdrop.io" />
</intent-filter>
</activity>
</application>
</manifest>
Setting android:launchMode="singleInstance" to the activity will cause only one instance of that activity to run. Meaning when your activity has been opened once via deeplink that instance is running. When you open the second link you expect your UI to get updated but since the instance was still running the activity's onCreate does not get called, which is why you see the views from earlier link.( Another point is when singleInstance is set it won't allow any other activity in stack.)
You can get more info in the official docs .
Now, even though onCreate is never called but onResume and onNewIntent methods do get called when singleInstance is set. Though onNewIntent is usually mentioned to work with singleTop, from my experience it does get called on when any of the three single flags are set.
So you need to override either of the two and write the code to update your UI in these. Also note that onResume does get called when your activity is created the very first time after onCreate so if that's where you place the code you might want to optimize to avoid reloading the same thing twice and everytime onResume gets called like after returning from background. In which case onNewIntent() does seem like a better option.
Hope this was of some help to you.
Update: As requested, you can find the edited code below
package app.freeairdrop.io;
import...
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
private boolean mShouldPause;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
mySwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
// call your method here to manage the intent
manageIntent(getIntent());
}
/* Simply moved your code which handles the intent to a common method
* Call this method from onCreate so that when first instance of activity gets created it handles it
* Similarly call it from onNewIntent to manage the new link you get
* You just need to pass the respective intents from the methods
*/
public void manageIntent(Intent intent) {
// ATTENTION: This was auto-generated to handle app links.
Intent appLinkIntent = intent;
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
if (getIntent().getExtras() != null) {
if (appLinkData == null){
webView.loadUrl("https://freeairdrop.io/");
}else
webView.loadUrl(String.valueOf(appLinkData));
} else if (getIntent().getExtras() == null){
webView.loadUrl("https://freeairdrop.io/");
}
}
// override to get the new intent when this activity has an instance already running
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// again call the same method here with the new intent received
manageIntent(intent);
}
private class WebViewClientDemo extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toasty.error(getApplicationContext(), "No Internet, pull down to refresh when you're connected to internet", Toast.LENGTH_LONG, true).show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (this.webView.canGoBack()) {
this.webView.goBack();
return;
}
else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
See if this works for you and let me know.
When the app is installed for first time, everything works fine, but after closing the app and opening again, there is only white screen. The website does not load.
MainActivity.java file
package app.freeairdrop.io;
import ....
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
private boolean doubleBackToExitPressedOnce;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
// webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
mySwipeRefreshLayout =
(SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
private class WebViewClientDemo extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (this.webView.canGoBack()) {
this.webView.goBack();
return;
}
else {
// Let the system handle the back button
super.onBackPressed();
}
}
#Override
protected void onStart() {
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
if (getIntent().getExtras() != null) {
webView.loadUrl(String.valueOf(appLinkData));
} else if (getIntent().getExtras() == null){
webView.loadUrl("https://freeairdrop.io/");
}else {
webView.loadUrl("https://freeairdrop.io/");
}
super.onStart();
}
#Override
protected void onResume() {
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
if (getIntent().getExtras() != null) {
webView.loadUrl(String.valueOf(appLinkData));
} else if (getIntent().getExtras() == null){
webView.loadUrl("https://freeairdrop.io/");
}else {
webView.loadUrl("https://freeairdrop.io/");
}
super.onResume();
}
}
AndroidMamifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="app.freeairdrop.io">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:appCategory="productivity"
android:hardwareAccelerated="true"
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".ApplicationClass"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="app.freeairdrop.io.MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="freeairdrop.io" />
</intent-filter>
</activity>
</application>
</manifest>
Whenever I go to the app using website link , using deeplink it works everytime, i.e if someone gets a link to my website on whatsapp and he clicks on it and open that link using my app, it is opening perfectly. Just like we can open youtube app if we gets video link on whatsapp.
getIntent().getExtras() might not be null but having a non URL value. Go an extra step to check the value before passing it to webview using URLUtil
Modify block onResume and onStart
String gotoUrl = String.valueOf(appLinkData);
if(URLUtil.isValidUrl(gotoUrl))
webView.loadUrl(gotoUrl);
else webView.loadUrl("https://freeairdrop.io/");
May This Repo Help You Check it to see if
I want to associate my website (https://freeairdrop.io) with my app, such that when anyone gets a link to my website, it should prompt user to open the link in app(if installed) or open in browser(if app not installed)
This is AndroidManifest.xml file:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="https"
android:host="freeairdrop.io" />
</intent-filter>
MyActivity.java file
package app.freeairdrop.io;
import android.annotation.SuppressLint;
import....
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
webView.loadUrl("https://freeairdrop.io/");
mySwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
// ATTENTION: This was auto-generated to handle app links.
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
}
private class WebViewClientDemo extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
// finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if (this.webView.canGoBack()) {
this.webView.goBack();
return;
}
Builder dialog = new Builder(this);
// dialog.setTitle((CharSequence) "Exit App");
dialog.setMessage((CharSequence) "Do You Want To Exit The App ?");
dialog.setPositiveButton((CharSequence) "YES", (OnClickListener) new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
});
dialog.setCancelable(false);
dialog.setNegativeButton((CharSequence) "CANCEL", (OnClickListener) new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
By adding link through link assistant, whenever I click on sub links of my website (https://freeairdrop.io/airdrop/discoin.html), it prompts the user to open link in app, but it just opens the homepage(https://freeairdrop.io).
Deeplinking is pretty simple to do.
Grab the intent inside of your Activity, get the data from the intent, load it into the website.
Intent intent = getIntent();
Uri data intent.getData();
webview.loadURL(data);
This isnt tested, you may have to add your url before the data.
webview.loadURL("URL_HERE" + data);
I want to connect to Twitter using Twitter4J. MainActivity call TwitterLoginActivity. TwitterLoginActivity show a WebView then get the accessToken throught OnNewIntent(). The problem is WebView show "web page not available" after I "SignIn" Twitter. This is my code.
MainActivity calls TwitterLoginActivity:
final Intent intent = new Intent(MainActivity.this, TwitterLoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, Constant.LOGIN_REQUEST);
TwitterLoginActivity shows a WebView.
final WebView twitterSite = new WebView(this);
final ViewGroup viewGroup = (ViewGroup)findViewById(R.id.twitterLoginRoot);
viewGroup.addView(twitterSite);
// Open keyboard when focusing on Twitter login form.
twitterSite.requestFocus(View.FOCUS_DOWN);
twitterSite.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(final View v, final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
twitterSite.setWebViewClient(new CustomWebViewClient());
try {
final RequestToken requestToken = twitter.getOAuthRequestToken(Constant.CALLBACK_URL);
twitterSite.loadUrl(requestToken.getAuthenticationURL());
} catch (final TwitterException e) {
e.printStackTrace();
}
onNewIntent:
#Override
protected void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
System.out.println("HIEU=================================");
setResult(RESULT_OK);
finish();
}
I use this to prevent default browser loading.
private class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
view.loadUrl(url);
return true;
}
}
Manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.twitterapitest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission
android:name="android.permission.INTERNET" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".TwitterLoginActivity"
android:label="#string/title_activity_main"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="test123"/>
</intent-filter>
</activity>
</application>
</manifest>
Callback URI:
public static final String CALLBACK_URL = "test123:///";
I guess you want the "oauth_verifier" that twitter returns when your loggin is successful, right?
You can get it from the url that returns the shouldOverrideUrlLoading method. Do something like this:
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
}
#Override
public void onPageFinished(WebView view, final String url) {
progressDialog.dismiss();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String oauthVerifier = url.substring(url.indexOf("oauth_verifier=") + 15);
Intent intent = new Intent(context);
Bundle bundle = new Bundle();
bundle.putString("oauth_verifier", oauthVerifier);
intent.putExtras(bundle);
((Activity) ctx).setResult(RESULT_OK, intent);
return true;
}
});
I had a problem similar to yours. I didn't know how to call the onNewIntent into the WebViewClient so I had to rethink what really needed and in my conclusion I realized I just needed the oauth_verifier and I could get it from the returned URL.
I hope this help you :
Use below URL as your callback url, it will solve your problem.
public static final String CALLBACK_URL = "x-oauthflow-twitter://callback";
I've in the following code the progressbar working on the first page load. after when I click on other links, the progrss bar is not shown ?
If somebody can tell me how to change this code to have the progress bar working on all loading ?
Thanks,
André.
public class Android_Activity extends Activity {
WebView webview;
#Override
protected void onSaveInstanceState(Bundle outState) {
WebView webview = (WebView) findViewById(R.id.webview);
webview.saveState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the main content view
setContentView(R.layout.main);
// check if an instance is stored and so restore it
if (savedInstanceState != null){
((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
}
final ProgressDialog progressBar = ProgressDialog.show(this, getString(R.string.progress_title),
getString(R.string.progress_msg));
webview = (WebView)findViewById(R.id.webview);
webview.setHttpAuthUsernamePassword(getString(R.string.kdg_host),
getString(R.string.kdg_realm),
getString(R.string.kdg_user_name),
getString(R.string.kdg_password)
);
//webview.setWebViewClient(new myWebViewClient());
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setRenderPriority(RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url) {
if (!progressBar.isShowing()) {
progressBar.show();
}
}
public void onPageFinished(WebView view, String url) {
//super.onPageFinished(view, url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webview.loadUrl(getString(R.string.base_url));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean error = false;
// check if it's an MAILTO URL
if(url.substring(0, 6).equalsIgnoreCase("mailto")){
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent .setType("plain/text");
emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{url.substring(7)});
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
return true;
}
// check if it's an EXT:// (Call Web Browser)
else if(url.substring(0, 6).equalsIgnoreCase("ext://")){
Uri uriUrl = Uri.parse(url.substring(6));
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
return true;
}
// check if it's an RTSP URL
else if(url.substring(0, 4).equalsIgnoreCase("rtsp")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
// else if it's an MP4 file link
else if(url.endsWith(".mp4")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);
return true;
}
// else if it's a 3GP file link
else if(url.endsWith(".3gp")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/3gp");
startActivity(intent);
return true;
}
// else if it's a MP3 file link
else if(url.endsWith(".mp3")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
return true;
}
// else if it's a page URL
else{
URL Url;
try {
Url = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) Url
.openConnection();
int response = httpURLConnection.getResponseCode();
if ((response >= 200)&&(response < 400))
//view.loadUrl(url);
error = false;
else
error = true;
} catch (Exception e) {
error = true;
}
}
// if an error occurred
if (error) {
showErrorDialog();
}
view.loadUrl(url);
return true;
}
}
#Override
public void onResume() {
super.onResume();
webview.reload();
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
showErrorDialog();
}
public void showErrorDialog(){
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(getString(R.string.error_title));
alertDialog.setMessage(getString(R.string.error_msg));
alertDialog.setButton(getString(R.string.ok_btn),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
alertDialog.show();
}
}
Use below working code ::
public class Android_Activity extends Activity {
private Android_Activity _activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
_activity = this;
setContentView(R.layout.main);
mwebview=(WebView)view.findViewById(R.id.webview);
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
if(checkInternetConnection(_activity)==true){
if(savedInstanceState==null)
mwebview.loadUrl(URL);
else
mwebview.restoreState(savedInstanceState);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
builder.setMessage("Please check your network connection.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
mwebview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(mwebview.getVisibility()==View.VISIBLE)
{
_activity.setProgress(progress * 100);
}
}
});
mwebview.setWebViewClient(new HelloWebViewClient());
}
//HelloWebViewClient class for webview
private class HelloWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
view.loadUrl(url);
return true;
}
} //HelloWebViewClient-class
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && mwebview.canGoBack() ){
mwebview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//To check whether network connection is available on device or not
public static boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}//checkInternetConnection()
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.KDG_EPG_Iphone"
android:versionCode="1"
android:versionName="1.00.00" android:installLocation="auto">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<supports-screens
android:resizeable="false"
android:smallScreens = "false"
android:normalScreens = "true"
android:largeScreens = "false"
android:anyDensity = "true"/>
<uses-sdk android:minSdkVersion="8"/>
<application android:label="#string/app_name" android:icon="#drawable/icon">
<activity android:screenOrientation="portrait"
android:theme="#android:style/Theme.Black.NoTitleBar"
android:configChanges="keyboardHidden|orientation"
android:label="#string/app_label" android:name="com.KDG_EPG_Iphone.KDG_EPG_Iphone_Activity" android:icon="#drawable/icon">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>