How to load url in webview in background while splashscreen is showing? - java

This is my splashscreen activity.
public class Splash extends Activity {
private static int SPLASH_TIME_OUT=10000;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Timer r=new Timer();
new Handler().postDelayed(r,SPLASH_TIME_OUT);
}
class Timer implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
Intent i=new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
}
This is my MainActivity. This activity Should be performed in background while splashscreen is on the front. Is it advisable to use AsyncTask. How to do that?
If not AsyncActivity, What can I use?
public class MainActivity extends Activity {
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.output);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAppCacheEnabled(false);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
}
);
webview.loadUrl("http://www.example.com");
}
//this is to go back to previous pages if exists
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack()){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If possible can I set the time for the splashscreen to view as long as the url is loaded without giving time?
The second attempt
public class MainActivity extends Activity {
WebView webview;
private boolean isSplashOn = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
webview = (WebView)findViewById(R.id.output);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadsImagesAutomatically(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setAppCacheEnabled(false);
webview.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
public void onPageFinished(WebView view, String url) {
if(isSplashOn) {
webview.setBackgroundDrawable(null);
webview.setBackgroundColor(0);
isSplashOn = false;
}
super.onPageFinished(view, url);
}
}
);
webview.loadUrl("http://www.example.com");
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack()){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
Guys. Still the problem is't solved. Need some help

You can use the simple trick -
I was showing a loading spinner till the page was being loaded in background.
Thus I had used two web views.
In your case, you can use ImageView or any other view.
XML file will like this -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
//Actual webview
<WebView
android:id="#+id/actual_webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
//Any view you want to show while webpage is loading
<WebView
android:id="#+id/spinner_webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
...
</RelativeLayout>
Now, in your JAVA file-
//initially, make actual_webview invisible
actual_webview.setVisibility(View.INVISIBLE);
Also, in
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// make spinner_webview invisible
spinner_webview.setVisibility(View.INVISIBLE);
// make actual_webview visible
actual_webview.setVisibility(View.VISIBLE);
}
Also,
shouldOverrideUrlLoading(...)
onPageStarted(...)
onPageFinished(...)
In all these methods, you get the URL and can check which URL is being loaded or finished loading.
According to the URL you can decide whether to show / hide the splash screen.

You can do it without AsyncTask and you can hide the splash screen when the page loaded without a timer.
WebViewClient class has a method onPageFinished() which will be called once the page has been loaded. You can make use of it.
In you project folder, place your splash screen images with name 'splash_screen.png' (or whatever name you want. If you want to use a different name then change this line webView.setBackgroundResource(R.drawable.splash_screen); to map to your splash screen image file) under res/drawable-xxx with corresponding resolutions.
For Eg:
I followed these resolutions for my app's splash screen.
hdpi - 400x800
ldpi - 240x320
mdpi - 320x480
xdpi - 640x960
And try this code:
public class MainActivity extends Activity {
final Activity activity = this;
private WebView webView;
private boolean isSplashOn = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setBackgroundColor(0);
webView.setBackgroundResource(R.drawable.splash_screen);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.setWebViewClient(new MyWebClient());
webView.loadUrl("http://www.google.com");
}
public class MyWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if(url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if(!isSplashOn) {
webView.setBackgroundDrawable(null);
webView.setBackgroundColor(0);
isSplashOn = true;
}
super.onPageFinished(view, url);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
if(webView.canGoBack()) {
webView.goBack();
return true;
}else {
activity.finish();
}
}
return super.onKeyDown(keyCode, event);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
</LinearLayout>
EDIT:
By the way i found the issue with your code. You are trying to set the splash screen to the webview before instantiating it.
Change your code from this:
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);
webview = (WebView)findViewById(R.id.output);
to this:
webview = (WebView)findViewById(R.id.output);
webview.setBackgroundColor(0);
webview.setBackgroundResource(R.drawable.activity_splash);

Why does the splash has to be an activity?
You can make it a full screen ImageView in the bottom of your layout and hide it using a handler:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isDestroyed())
return;
mSplashView.setVisibility(View.GONE);
}
},2000);

Related

Unable to open Google Maps link in Android web view app

I have created a webview app of my site in Android Studio. Could someone please look into the code and solve the issue. This is my code:
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url == null || url.startsWith("http://") || url.startsWith("https://")) return false;
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
} catch (Exception e) {
return true;
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("https://xyz.in/admin_login.php");
}
public void onBackPressed(){
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
When WhatsApp icon is clicked, it's opening in WhatsApp application,but when view location is clicked, the button is not responding. Please help on this issue.
Please find the attached image for your reference

JAVA/ANDROID - Open SecondActivity when url.endsWith(".html")) WebView

I just wanted to open a second activity (webview) when user click on links whitch ends like .html.
MainActivity, and SecondActivity are the same
Code looks as follow:
if (url.endsWith(".html")) {
try {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch (Exception e) {
// error
}
return true;
}
Of course this opens the content into webbrowser outside the app.
Can you please help me in this?
First of all add this to your manifest
<uses-permission android:name="android.permission.INTERNET"/>
And add this activity as well
<activity android:name=".WebViewClientDemoActivity"/>
Now in your mainActivity you create intent like this
startActivity(new Intent(this, WebViewClientDemoActivity.class));
Now create this class
public class WebViewClientDemoActivity extends Activity {
WebView web;
#Override #SuppressLint("SetJavaScriptEnabled")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = findViewById(R.id.web_view);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
//for example i used this web page
web.loadUrl("https://stackoverflow.com/questions/69032318/java-android-open-secondactivity-when-url-endswith-html-webview");
}
public static class myWebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()){
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
By the way there is a probelm using the emulator with webview you can use your phone or you can see this solution

SwipeRefreshLayout with Webview not working

This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.
Below is my activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:id="#+id/webView"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
And this is my MainActivity.java file
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipe;
#Override
public boolean onCreateOptionsMenu (Menu manu){
getMenuInflater().inflate(R.menu.main, manu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id=item.getItemId();
if(id==R.id.id_about){
Intent intentabout=new Intent(MainActivity.this, About.class);
startActivity(intentabout);
return true;
}
if(id==R.id.id_terms){
return true;
}
if(id==R.id.id_privacy){
return true;
}
return true;
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webView.loadUrl("https://google.com");
swipe.setRefreshing(true);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("file:///android_asset/error.html");
}
public void onPagefinished(WebView view, String url){
swipe.setRefreshing(false);
}
});
}
}
You gotta put your WebView inside SwipeRefreshLayout:
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipeRefreshLayout;
String currentUrl = "https://www.google.co.in/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
webView.loadUrl(currentUrl);
webView.setWebViewClient(new MyWebViewClient());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl(currentUrl);
}
});
}
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
}
swipeRefreshLayout.setRefreshing(false) stops the animation.
you can put your Webview inside a NestedScrollView to make this work.
Example:
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.NestedScrollView>
You should add
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
swipe.setRefreshing(true); //add
LoadWeb();
}
LoadWeb();

Android webview app won't load my form

Hi i've been searching a lot but couldn't find anything that could help.
I am creating an android app for our existing website. The website itself will load, but the main form where users can sign in won't load. Does anyone have any idea how this happens?
The website is https://app.one-2-ten.com/v2
p.s. This is the first time I am making an android app so sorry if its an obvious solution.
ProgressBar progressBar;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webView);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
}
else{
webView.getSettings() .setJavaScriptEnabled(true);
webView.getSettings() .setSupportZoom(false);
webView.getSettings() .setBuiltInZoomControls(false);
webView.getSettings() .setLoadWithOverviewMode(true);
webView.getSettings() .setUseWideViewPort(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new ourViewClient());
webView.Settings.AllowContentAccess = true;
webView.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged (WebView view, int progress){
progressBar.setProgress(progress);
if(progress < 100 && progressBar.getVisibility() == ProgressBar.GONE){
progressBar.setVisibility(ProgressBar.VISIBLE);
}if(progress == 100){
progressBar.setVisibility(ProgressBar.GONE);
}
}
}
);}
String data = getIntent() .getDataString();
if(Intent.ACTION_VIEW.equals(getIntent() .getAction())){
webView.loadUrl(data);
}else{
webView.loadUrl("https://one2ten-system.parseapp.com/v2");
}
}
public class ourViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
if (url.contains("one2ten-system.parseapp.com/v2")) {
v.loadUrl(url);
CookieManager.getInstance().setAcceptCookie(true);
} else {
Uri uri = Uri.parse(url);
startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
}
I've found what my issue was, I forgot to add the following line: webView.getSettings().setDomStorageEnabled(true);
This enables the browser to store user data from forms for example, which it needs because you land on a login page.
If my answer is incomplete please let me know!
Thanks

Splash Screen for Android Webview

I have a WebView app and would like to add a splash screen to show either while loading the page, or for a set amount of time. I have tried some other solutions but could not find one that worked. If necessary to know, my splash image is splash.png, located in the drawable folder.
Here is my MainActivity.java
public class MainActivity extends Activity {
private GoogleApiClient client;
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView);
if(webView.canGoBack()){
webView.goBack();
}
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap Twice To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyBrowser());
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
if(isNetworkStatusAvialable (getApplicationContext())) {
view.loadUrl("file:///android_asset/index.html");
} else {
view.loadUrl("file:///android_asset/error.html");
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
#Override
public void onStart() {
super.onStart();
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"MLINKS",
Uri.parse("http://host/path"),
Uri.parse("android-app://PACKAGE-NAME/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"MLINKS",
Uri.parse("http://host/path"),
Uri.parse("android-app://PACKAGE-NAME/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
}
Thank you for any help!
EDIT:
Define a Progress Dialog:
private ProgressDialog pd;
Then inside your:
view.setWebViewClient(new MyBrowser() {
Insert this:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
I did something like this at one time. IIRC, it went like this:
First, I created a special ImageView subclass that overrode onTouchEvent() and threw away all the events.
Then for my layout, I had my ImageView subclass overlay the WebView then made it hidden, like this (for example):
<FrameLayout
...
>
<WebView
...
/>
<com.example.TouchHandlerImageView
....
android:src="R.drawable.splash"
android:visibility="gone"
/>
....
</FrameLayout>
Then my code went like this:
Show the splash imageview. (The onTouchEvent() would keep touch events from going through to the WebView underneath)
Start the page loading (In my case, I also had to run some javascript to set up the page)
In WebViewClient onPageFinshed(), hide the splash imageview, displaying the WebView with page fully loaded.
at first thing make a background and show it im main screen till the data is being ready.
use AsyncTask Class because it has 3 methods which them
1- onPreExecute() //don't do anything here
2- doInBackgroundProcess()// fetch your data here
3- onPostExecute()//get back the original background

Categories

Resources