How to Make Webview Application in Android using (JAVA)

 Android Adda News is Launch WebView Application With Source Code .How to Back Pressed Working in Application And All Post Clicked Then redirect to another page Just Like Activity.  


XML CODE
Splash Screen Code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="#ea2e2d"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">

<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/logo"
android:layout_width="250dp"
android:layout_height="150dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="170dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"

android:background="@drawable/logo"
/>

<ProgressBar
android:id="@+id/idPBLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="140dp"
android:indeterminateTint="@color/white" />

</androidx.constraintlayout.widget.ConstraintLayout>


with Also Using ProgressBar In Splash Screen 

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// on below line we are
// creating a new intent
Intent i = new Intent(MainActivity.this, introscreen.class);

// on below line we are
// starting a new activity.
startActivity(i);

// on the below line we are finishing
// our current activity.
finish();
}
}, 2000);


}
}


                                                           Beautifull IntroScreen 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:showIn="@layout/activity_introscreen">


<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<LinearLayout
android:id="@+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="@dimen/dots_height"
android:layout_alignParentBottom="true"
android:layout_marginBottom="@dimen/dots_margin_bottom"
android:gravity="center"
android:orientation="horizontal">

</LinearLayout>

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="@id/layoutDots"
android:background="@android:color/white" />

<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"

android:background="@color/colorPrimary"
android:drawableEnd="@drawable/ic_next_24"
android:text="NEXT"
android:textColor="@android:color/white" />

<Button
android:id="@+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:background="@color/colorPrimary"
android:text="SKIP"
android:drawableEnd="@drawable/ic_baseline_skip_next_24"
android:textColor="@android:color/white" />

</RelativeLayout>


Java Code IntroScreen 


public class introscreen extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}

// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_introscreen);

viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);


// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_slide1,
R.layout.welcome_slide2,
R.layout.welcome_slide3};

// adding bottom dots
addBottomDots(0);

// making notification bar transparent
changeStatusBarColor();

myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

btnSkip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchHomeScreen();
}
});

btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}

private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];

int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);

dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("&#8226;"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}

if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}

private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}

private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(introscreen.this, dashbord.class));
finish();
}

// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
addBottomDots(position);

// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {

}

@Override
public void onPageScrollStateChanged(int arg0) {

}
};

/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}

/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;

public MyViewPagerAdapter() {
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);

return view;
}

@Override
public int getCount() {
return layouts.length;
}

@Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}


@Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}

}
}


                                                           WebView Layout
dashbord_layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".MainActivity">

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_behavior="@string/appbar_scrolling_view_behavior">



<WebView
android:id="@+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent"/>


</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


<ProgressBar
android:id="@+id/progress"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
style="?android:attr/progressBarStyle"
/>

</RelativeLayout>



Java DashBord Code


public class dashbord extends AppCompatActivity {

WebView webView;
ProgressBar progressBar;
SwipeRefreshLayout swipeRefreshLayout;

String url = "https://vidhannews.in/";

// final String filename= URLUtil.guessFileName(URLUtil.guessUrl(url));

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashbord);



webView = findViewById(R.id.web);
progressBar = findViewById(R.id.progress);
swipeRefreshLayout = findViewById(R.id.swipe);


webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebViewClient(new myWebViewclient());
webView.loadUrl(url);

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
webView.loadUrl(url);
}
}, 3000);
}
});

swipeRefreshLayout.setColorSchemeColors(
getResources().getColor(android.R.color.holo_blue_bright),
getResources().getColor(android.R.color.holo_orange_dark),
getResources().getColor(android.R.color.holo_green_dark),
getResources().getColor(android.R.color.holo_red_dark)
);

// ==================== START HERE: THIS CODE BLOCK IS TO ENABLE FILE DOWNLOAD FROM THE WEB. YOU CAN COMMENT IT OUT IF YOUR APPLICATION DOES NOT REQUIRE FILE DOWNLOAD. IT WAS ADDED ON REQUEST ======//

webView.setDownloadListener(new DownloadListener() {
String fileName = MimeTypeMap.getFileExtensionFromUrl(url);
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {

DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));

request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();

}
});
// ==================== END HERE: THIS CODE BLOCK IS TO ENABLE FILE DOWNLOAD FROM THE WEB. YOU CAN COMMENT IT OUT IF YOUR APPLICATION DOES NOT REQUIRE FILE DOWNLOAD. IT WAS ADDED ON REQUEST ======//



}


public class myWebViewclient extends WebViewClient{

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}

@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
webView.loadUrl("file:///android_asset/lost.html");
}

@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
handler.cancel();
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
final androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this, R.style.AlertDialogCustom);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.dismiss();
}
});
final AlertDialog alert = builder.create();
alert.show();

}


}


PrefManager Code



public class PrefManager {

SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;

// shared pref mode
int PRIVATE_MODE = 0;

// Shared preferences file name
private static final String PREF_NAME = "androidhive-welcome";

private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}

public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}

public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}

}




















Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.