i use one signal to send notificition vai firebase
i added this code to mainactivity
// Logging set to help debug issues, remove before releasing your app.
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.init();
and it work
but i create bottomnavigation bar witf fragments
and the notifiction now didnt work
i tried added it to TrackFragment.java but it didnt work
this is TrackFrgament
package mypacgae.name.com;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
/**
* A simple {#link Fragment} subclass.
* Use the {#link TrackFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TrackFragment extends Fragment {
LinearLayout eLinearLayout;
WebView webView;
ProgressBar mProgressBar;
SwipeRefreshLayout swipeRefreshLayout;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment TrackFragment.
*/
// TODO: Rename and change types and number of parameters
public static TrackFragment newInstance(String param1, String param2) {
TrackFragment fragment = new TrackFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public TrackFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_track, container, false);
webView = (WebView) v.findViewById(R.id.webview);
eLinearLayout = (LinearLayout) v.findViewById(R.id.LinearWebView);
mProgressBar = (ProgressBar) v.findViewById(R.id.progressBar);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipeweb);
webView.loadUrl("the url of webview no need to show it");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
eLinearLayout.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url) {
if (url.startsWith("tel:") || url.startsWith("whatsapp:")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressBar.setVisibility(View.GONE);
}
});
// pull to refresh
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("the url . no need to show it");
}
}, 1500);
}
});
swipeRefreshLayout.setColorSchemeColors(
getResources().getColor(android.R.color.holo_blue_dark),
getResources().getColor(android.R.color.holo_orange_dark),
getResources().getColor(android.R.color.holo_green_dark),
getResources().getColor(android.R.color.holo_red_dark)
);
return v;
}
}
and this mainactivityt
please help and thank you all
Try to make application class in your main package:
class ApplicationClass : Application() {
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(this);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.init()
}
}
then declare it in your manifest then try :
<application
android:allowBackup="true"
android:icon="#mipmap/appicon"
android:label="#string/app_name"
android:largeHeap="true"
android:roundIcon="#mipmap/appicon"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:name=".ApplicationClass">
and make sure you implemented the libraries and manifest placeholders well in your build.gradle:
defaultConfig {
applicationId "com.codediversity.doodhwale"
minSdkVersion 16
targetSdkVersion 29
versionCode 6
versionName "1.0.5"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [
onesignal_app_id: '4xxxxxxx4-8bcd-xxxxx-8c6d-3xxxx7155d',
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: 'REMOTE'
]
}
implementation 'com.onesignal:OneSignal:[3.15.0, 3.99.99]'
implementation 'com.google.firebase:firebase-analytics:17.2.2'
Related
I thought it was a very easy problem... but I haven't solved for quite some time.
For now, pressing back button will turn off the app. I want to go back by pressing the back button.
Fragment containing the webview.
HomeFragment.java
public class HomeFragment extends Fragment {
WebView webView;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.home_webview);
String url = "https://galaxyhub.kr/starcitizen";
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"", "Loading", true);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toast.makeText(getActivity(), "URL ERROR", Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dialog.dismiss();
}
});
}
}
I heard that I should also write in the MainActivity.
I'll post it right away if needed.
package com.example.starcitizen.fragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.starcitizen.R;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
WebView webView;
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
//use this if you need to call the Activity
//backpress for default back action
requireActivity().onBackPressed();
}
}
};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.home_webview);
String url = "https://galaxyhub.kr/starcitizen";
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"", "Loading",
true);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toast.makeText(getActivity(), "URL ERROR", Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dialog.dismiss();
}
});
}
}
Now this code is running!
Add the fragment to the back stack if you need to navigate back from your fragment when the WebView can't go back more.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
Then in your fragment:
public class HomeFragment extends Fragment {
private WebView webView;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
//use this if you need to call the Activity
//backpress for default back action
requireActivity().onBackPressed();
}
}
};
requireActivity().getOnBackPressedDispatcher()
.addCallback(getViewLifecycleOwner(), callback);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.home_webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
//callbacks omitted...
});
String url = "https://galaxyhub.kr/starcitizen";
//call this after WebViewClient setup
webView.loadUrl(url);
}
}
Remember that Activity on onBackPressed will be called before the one added in the Fragment.
More info on back press handling here: https://developer.android.com/guide/navigation/navigation-custom-back#java
For this to work use at least:
androidx.fragment:fragment:1.1.0
The features are enabled once the onCreate() methood is executed for the first time, but after i do a screen rotation none of the features get saved, even though I've overridden the onSaveInstanceState() method and I've also tried using the onRestoreInstanceState() method.
Kindly help me out.
I'll attach the code below.
Activity file
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main3Activity extends AppCompatActivity implements LoaderManager.LoaderCallbacks{
Toolbar toolbar;
WebView webView;
ProgressDialog progressDialog;
final String urld="https://www.google.co.in/";
final int LOADER_ID=1;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
webView = (WebView)findViewById(R.id.wb1);
progressDialog = new ProgressDialog(Main3Activity.this);
progressDialog.setTitle("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(true);
if(savedInstanceState!=null)
{
webView.restoreState(savedInstanceState);
webView.getSettings().setJavaScriptEnabled(true);
}
else {
webView.getSettings().setJavaScriptEnabled(true);
webView.setFocusable(true);
webView.setFocusableInTouchMode(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//webView.setInitialScale(1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setBackgroundColor(Color.WHITE);
//webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
//webView.setWebChromeClient(new WebChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if( URLUtil.isNetworkUrl(url) ) {
return false;
}
if (appInstalledOrNot(url)) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
} else {
// do something if app is not installed
}
return true;*/
if (Uri.parse(url).getHost().endsWith("google.co.in")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
super.onPageFinished(view, url);
}
});
}
bundle = savedInstanceState;
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(LOADER_ID, null, this);
}
/*private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}*/
#Override
public void onBackPressed() {
if(webView.canGoBack())
{
webView.goBack();
}
else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader onCreateLoader(int i, Bundle bundle) {
return new LoadingPageInBackground(this,urld,bundle,webView,progressDialog);
}
#Override
public void onLoadFinished(Loader loader, Object o) {
}
#Override
public void onLoaderReset(Loader loader) {
//webView.setVisibility(WebView.GONE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
Toast.makeText(Main3Activity.this,"Saved",Toast.LENGTH_SHORT).show();
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
webView.restoreState(state);
Toast.makeText(Main3Activity.this,"Restored",Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(state);
}
}
restoreState is not reliable, based on the documentation for restoreState :
If it is called after this WebView has had a chance to build state
(load pages, create a back/forward list, etc.) there may be
undesirable side-effects. Please note that this method no longer
restores the display data for this WebView.
Based on the documentation for saveState:
Please note that this method no longer stores the display data for
this WebView
You have to reload your WebView in onCreate(). You can store the URL in SharedPreference and load it in onCreate().
Another alternative is to handle the Orientation by your self and keep WebView unchanged. You can handle the orientation change by adding android:configChanges="orientation" in your manifest and Overriding onConfigurationChanged().
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
This code is not working inside my fragment to back the webpage in webview
Use setOnKeyListener() on your WebView to listen to any event because onBackPreesed() is not the member of a Fragment
myWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()==KeyEvent.ACTION_DOWN &&keyCode==KeyEvent.KEYCODE_BACK&&myWebView.canGoBack()) {
myWebView.goBack();
}
return true;
}
});
You need to attach the fragment in the corresponding activity.
after you can implement onBackPressed method from your activty
package com.cornicore.dream11statistics;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Tab1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Tab1#newInstance} factory method to
* create an instance of this fragment.
*/
public class Tab1 extends Fragment {
AdView adView_Banner;
WebView myWebView;
ProgressBar progressBar;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Tab1() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab1.
*/
// TODO: Rename and change types and number of parameters
public static Tab1 newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab1, container, false);
myWebView = (WebView) v.findViewById(R.id.webViewHome);
progressBar = (ProgressBar) v.findViewById(R.id.progressBarFragment);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true);
myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
myWebView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
myWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
myWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
myWebView.loadUrl("https://cornicore.com/cricket-news/");
myWebView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
myWebView.loadUrl("file:///android_asset/internet.html");
}
});
myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.OnNavFragmentInteractionListener(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void OnNavFragmentInteractionListener(Uri uri);
}
public interface OnNavFragmentInteractionListener {
}
public void setInteractionListener(OnFragmentInteractionListener mListener){
this.mListener = mListener;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
}
I have a WebView that is supposed to load the mobile version of a website, but when I try to load it inside the WebView it only appears as a white screen. I have tried loading the same URL in my android browser, and on my desktop with a User-Agent Switcher. I know the page is done loading also, because I have a method onPageFinished() that displays a toast when the page is displayed. Every time I load the application I am greeted with a white screen and then a few seconds later, the Toast message.
EDIT: I have tried different mobile web sites, and they all work in the WebView, the only one that is giving me trouble is this one: https://zangleweb01.clovisusd.k12.ca.us/StudentConnect/Home/Login
MainActivity.java
package com.student.connect;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements
ActionBar.OnNavigationListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current dropdown position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#SuppressWarnings("unused")
private WebView student_zangle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Set up the dropdown list navigation in the action bar.
actionBar.setListNavigationCallbacks(
// Specify a SpinnerAdapter to populate the dropdown list.
new ArrayAdapter<String>(getActionBarThemedContextCompat(),
android.R.layout.simple_list_item_1,
android.R.id.text1, new String[] {
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3), }), this);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if
* <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi")
#Override
public boolean onNavigationItemSelected(int position, long id)
{
WebView student_zangle = (WebView) findViewById(R.id.student_zangle);
student_zangle.setWebViewClient( new YourWebClient());
student_zangle.loadUrl("https://zangleweb01.clovisusd.k12.ca.us/StudentConnect/Home/Login");
student_zangle.setDrawingCacheEnabled(false);
WebSettings settings = student_zangle.getSettings();
student_zangle.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
student_zangle.setDownloadListener(new DownloadListener()
{
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/x-rar-compressed");
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keyCode, event);
}
private class YourWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("mailto"))
{
String mail = url.replaceFirst("mailto:", "");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, mail );
startActivity(intent);
return true;
}
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url)
{
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
}
}
Try buildDrawingCache with following changes:
student_zangle.setDrawingCacheEnabled(true);
student_zangle.buildDrawingCache();
Note : You should avoid calling this method when hardware acceleration is enabled
I need to read elements from an HTML file. I loaded them from webview but I haven't found the best way to read.
Code: content_html
package com.android.webview;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ViewLink extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
/*
read elements in content_html
*/
}
});
browser.loadUrl("http://vnexpress.net/gl/rss/");
}
final Context myApp = this;
Builder builder;
String content_html;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
builder = new AlertDialog.Builder(myApp);
builder.setTitle("HTML")
.setMessage(html)
.setPositiveButton(android.R.string.ok, null)
.setCancelable(false)
.create()
.show();
content_html = html;
Log.i("html", html+" ");
}
}
Try this one that work for me
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void showHTML(String html)
{
System.out.println("Html...."+html);
}
}
In Activity
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setPluginsEnabled(true);
browser.getSettings().setSupportZoom(true);
browser.getSettings().setBuiltInZoomControls(true);
browser.setBackgroundColor(Color.TRANSPARENT);
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
browser.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
browser.loadUrl(link);