11package at .xtools .pwawrapper ;
22
3- import android .annotation .TargetApi ;
4- import android .app .ActivityManager ;
5- import android .content .Context ;
6- import android .content .Intent ;
7- import android .content .res .Resources ;
8- import android .graphics .Bitmap ;
9- import android .graphics .BitmapFactory ;
10- import android .net .ConnectivityManager ;
11- import android .net .NetworkInfo ;
12- import android .net .Uri ;
13- import android .os .Build ;
14- import android .os .Message ;
153import android .support .v7 .app .AppCompatActivity ;
164import android .os .Bundle ;
17- import android .util .Log ;
18- import android .util .TypedValue ;
19- import android .view .View ;
20- import android .view .animation .AccelerateInterpolator ;
21- import android .view .animation .DecelerateInterpolator ;
22- import android .webkit .CookieManager ;
23- import android .webkit .WebChromeClient ;
24- import android .webkit .WebResourceError ;
25- import android .webkit .WebResourceRequest ;
26- import android .webkit .WebSettings ;
275import android .webkit .WebView ;
28- import android .webkit .WebViewClient ;
29- import android .widget .LinearLayout ;
30- import android .widget .ProgressBar ;
316
32- public class MainActivity extends AppCompatActivity {
7+ import at .xtools .pwawrapper .ui .UIManager ;
8+ import at .xtools .pwawrapper .webview .WebViewHelper ;
339
10+ public class MainActivity extends AppCompatActivity {
3411 // Globals
3512 private WebView webView ;
36- private WebSettings webSettings ;
37- private ProgressBar progressSpinner ;
38- private ProgressBar progressBar ;
39- private LinearLayout offlineContainer ;
40- private boolean pageLoaded = false ;
41- private static String TAG = "MainActivity" ;
13+ private UIManager uiManager ;
14+ private WebViewHelper webViewHelper ;
4215
4316 @ Override
4417 protected void onCreate (Bundle savedInstanceState ) {
4518 setTheme (R .style .AppTheme_NoActionBar );
4619 super .onCreate (savedInstanceState );
4720 setContentView (R .layout .activity_main );
4821
49- // UI references
50- progressBar = (ProgressBar ) this .findViewById (R .id .progressBarBottom );
51- progressSpinner = (ProgressBar ) this .findViewById (R .id .progressSpinner );
52- offlineContainer = (LinearLayout ) this .findViewById (R .id .offlineContainer );
22+ // Setup App
5323 webView = (WebView ) this .findViewById (R .id .webView );
54- webSettings = webView .getSettings ();
55-
56- setupWebView ();
57- changeRecentAppsIcon ();
58-
59- // set click listener for offline-screen
60- offlineContainer .setOnClickListener (new View .OnClickListener () {
61- @ Override
62- public void onClick (View v ) {
63- webView .reload ();
64- setOffline (false );
65- }
66- });
24+ uiManager = new UIManager (this );
25+ webViewHelper = new WebViewHelper (this , uiManager );
26+ webViewHelper .setupWebView ();
27+ uiManager .changeRecentAppsIcon ();
6728
6829 // load up the Web App
6930 webView .loadUrl (Constants .WEBAPP_URL );
@@ -78,8 +39,11 @@ protected void onPause() {
7839 @ Override
7940 protected void onResume () {
8041 webView .onResume ();
81- // retrieve content from cache primarily if not connected
82- useCache (!isNetworkAvailable ());
42+ // retrieve content from cache primarily if not connected,
43+ // fetch from web otherwise to get updates.
44+ webViewHelper .useCache (
45+ !webViewHelper .isNetworkAvailable ()
46+ );
8347 super .onResume ();
8448 }
8549
@@ -92,208 +56,4 @@ public void onBackPressed() {
9256 super .onBackPressed ();
9357 }
9458 }
95-
96- // Show loading animation screen while app is loading/caching the first time
97- private void setLoading (boolean isLoading ) {
98- if (isLoading ) {
99- progressSpinner .setVisibility (View .VISIBLE );
100- webView .animate ().translationX (Constants .SLIDE_EFFECT ).alpha (0.5F ).setInterpolator (new AccelerateInterpolator ()).start ();
101- } else {
102- webView .setTranslationX (Constants .SLIDE_EFFECT * -1 );
103- webView .animate ().translationX (0 ).alpha (1F ).setInterpolator (new DecelerateInterpolator ()).start ();
104- progressSpinner .setVisibility (View .INVISIBLE );
105- }
106- pageLoaded = !isLoading ;
107- }
108-
109- // Set Loading Progress for ProgressBar
110- private void setLoadingProgress (int progress ) {
111- // set progress in UI
112- if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .N ) {
113- progressBar .setProgress (progress , true );
114- } else {
115- progressBar .setProgress (progress );
116- }
117-
118- // hide ProgressBar if not applicable
119- if (progress >= 0 && progress < 100 ) {
120- progressBar .setVisibility (View .VISIBLE );
121- } else {
122- progressBar .setVisibility (View .INVISIBLE );
123- }
124-
125- // get app screen back if loading is almost complete
126- if (progress >= Constants .PROGRESS_THRESHOLD && !pageLoaded ) {
127- setLoading (false );
128- }
129- }
130-
131- // handle visibility of offline screen
132- private void setOffline (boolean offline ) {
133- if (offline ) {
134- setLoadingProgress (100 );
135- webView .setVisibility (View .INVISIBLE );
136- offlineContainer .setVisibility (View .VISIBLE );
137- } else {
138- webView .setVisibility (View .VISIBLE );
139- offlineContainer .setVisibility (View .INVISIBLE );
140- }
141- }
142-
143- // set icon in recent activity view to a white one to be visible in the app bar
144- private void changeRecentAppsIcon () {
145- if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .LOLLIPOP ) {
146- Bitmap iconWhite = BitmapFactory .decodeResource (getResources (), R .drawable .icon_appbar );
147-
148- TypedValue typedValue = new TypedValue ();
149- Resources .Theme theme = getTheme ();
150- theme .resolveAttribute (R .attr .colorPrimary , typedValue , true );
151- int color = typedValue .data ;
152-
153- ActivityManager .TaskDescription description = new ActivityManager .TaskDescription (
154- getResources ().getString (R .string .app_name ),
155- iconWhite ,
156- color
157- );
158- this .setTaskDescription (description );
159- iconWhite .recycle ();
160- }
161- }
162-
163- /**
164- * Simple helper method checking if connected to Network.
165- * Doesn't check for actual Internet connection!
166- * @return {boolean} True if connected to Network.
167- */
168- private boolean isNetworkAvailable () {
169- ConnectivityManager manager =
170- (ConnectivityManager ) getSystemService (Context .CONNECTIVITY_SERVICE );
171- NetworkInfo networkInfo = manager .getActiveNetworkInfo ();
172-
173- boolean isAvailable = false ;
174- if (networkInfo != null && networkInfo .isConnected ()) {
175- // Wifi or Mobile Network is present and connected
176- isAvailable = true ;
177- }
178-
179- return isAvailable ;
180- }
181-
182- // manipulate cache settings to make sure our PWA gets updated
183- private void useCache (Boolean use ) {
184- Log .d (TAG , "Cache turned on: " + use );
185- if (use ) {
186- webSettings .setCacheMode (WebSettings .LOAD_CACHE_ELSE_NETWORK );
187- } else {
188- webSettings .setCacheMode (WebSettings .LOAD_DEFAULT );
189- }
190- }
191-
192- private void setupWebView () {
193- // accept cookies
194- CookieManager .getInstance ().setAcceptCookie (true );
195- // enable JS
196- webSettings .setJavaScriptEnabled (true );
197- // must be set for our js-popup-blocker:
198- webSettings .setSupportMultipleWindows (true );
199-
200- // PWA settings
201- if (Build .VERSION .SDK_INT < Build .VERSION_CODES .KITKAT ) {
202- webSettings .setDatabasePath (getApplicationContext ().getFilesDir ().getAbsolutePath ());
203- }
204- if (Build .VERSION .SDK_INT < Build .VERSION_CODES .JELLY_BEAN_MR2 ) {
205- webSettings .setAppCacheMaxSize (Long .MAX_VALUE );
206- }
207- webSettings .setDomStorageEnabled (true );
208- webSettings .setAppCachePath (getApplicationContext ().getCacheDir ().getAbsolutePath ());
209- webSettings .setAppCacheEnabled (true );
210- webSettings .setDatabaseEnabled (true );
211-
212- // retrieve content from cache primarily if not connected
213- useCache (!isNetworkAvailable ());
214-
215- // set User Agent
216- if (Constants .OVERRIDE_USER_AGENT || Constants .POSTFIX_USER_AGENT ) {
217- String userAgent = "" ;
218- if (Constants .OVERRIDE_USER_AGENT ) {
219- userAgent = Constants .USER_AGENT ;
220- }
221- if (Constants .POSTFIX_USER_AGENT ) {
222- userAgent = userAgent + " " + Constants .USER_AGENT_POSTFIX ;
223- }
224- webSettings .setUserAgentString (userAgent );
225- }
226-
227- // enable HTML5-support
228- webView .setWebChromeClient (new WebChromeClient () {
229- //simple yet effective redirect/popup blocker
230- @ Override
231- public boolean onCreateWindow (WebView view , boolean isDialog , boolean isUserGesture , Message resultMsg ) {
232- Message href = view .getHandler ().obtainMessage ();
233- view .requestFocusNodeHref (href );
234- final String popupUrl = href .getData ().getString ("url" );
235- if (popupUrl != null ) {
236- //it's null for most rouge browser hijack ads
237- webView .loadUrl (popupUrl );
238- return true ;
239- }
240- return false ;
241- }
242-
243- // update ProgressBar
244- @ Override
245- public void onProgressChanged (WebView view , int newProgress ) {
246- setLoadingProgress (newProgress );
247- super .onProgressChanged (view , newProgress );
248- }
249- });
250-
251- // Set up Webview client
252- webView .setWebViewClient (new WebViewClient () {
253- @ Override
254- public void onPageStarted (WebView view , String url , Bitmap favicon ) {
255- // prevent loading content that isn't ours
256- if (!url .startsWith (Constants .WEBAPP_URL )) {
257- // stop loading
258- view .stopLoading ();
259-
260- // open external URL in Browser/3rd party apps instead
261- Intent intent = new Intent (Intent .ACTION_VIEW , Uri .parse (url ));
262- startActivity (intent );
263- }
264- // activate loading animation screen
265- setLoading (true );
266- super .onPageStarted (view , url , favicon );
267- }
268-
269- /*
270- @Override
271- public void onPageFinished(WebView view, String url) {
272- // nothing yet
273- super.onPageFinished(view, url);
274- }
275- */
276-
277- // handle loading error by showing the offline screen
278- @ Deprecated
279- @ Override
280- public void onReceivedError (WebView view , int errorCode , String description , String failingUrl ) {
281- if (Build .VERSION .SDK_INT < Build .VERSION_CODES .M ) {
282- setOffline (true );
283- }
284- }
285-
286- @ TargetApi (Build .VERSION_CODES .M )
287- @ Override
288- public void onReceivedError (WebView view , WebResourceRequest request , WebResourceError error ) {
289- if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .M ) {
290- // new API method calls this on every error for each resource.
291- // we only want to interfere if the page itself got problems.
292- if (view .getUrl ().equals (request .getUrl ().toString ())) {
293- setOffline (true );
294- }
295- }
296- }
297- });
298- }
29959}
0 commit comments