Using reflection in Android for backwards compatibility - java

I was reading over at the Android development website about using reflections. But I'm really not grasping how to use it. I need this Java file to run on a 1.5 (SDK3) device but just ignore the new code and it works fine on a 2.0 (SDK5) or later phone. I have this Activity (posted below) and it's a simple webview. However, I want to have geolocation enabled (even if it is only for 2.0 and later phones), since these APIs weren't introduced until SDK 5, and I would like the webview to be able to, at the very least, to load on a 1.5 phone rather than just crashing. How do I take my code and set it up using reflections?
package com.my.app;
import com.facebook.android.R;
//NEEDS TO BE IGNORED**********************************************************
import android.webkit.GeolocationPermissions;
import android.webkit.GeolocationPermissions.Callback;
//END**************************************************************************
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
//GeolocationPermissionsCallback NEEDS TO BE IGNORED**********************************************************
public class Places extends Activity implements GeolocationPermissions.Callback {
private ProgressDialog progressBar;
public WebView webview;
private static final String TAG = "Main";
String geoWebsiteURL = "http://google.com";
#Override
public void onStart()
{
super.onStart();
CookieSyncManager.getInstance().sync();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new testClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.loadUrl("http://google.com");
progressBar = ProgressDialog.show(Places.this, "", "Loading Page...");
//START GROUP OF CODE THAT NEEDS TO BE IGNORED************************************************************
webview.getSettings().setGeolocationEnabled(true);
GeoClient geo = new GeoClient();
webview.setWebChromeClient(geo);
}
public void invoke(String origin, boolean allow, boolean remember) {
}
final class GeoClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
//END OF CODE THAT NEEDS TO BE IGNORED************************************************
}
private class testClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
if (url.startsWith("mailto:") || url.startsWith("geo:") ||
url.startsWith("tel:")) {
Intent intent = new Intent
(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
}
}
//What's here????
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
Intent z = new Intent(this, Search.class);
startActivity(z);
}
return super.onKeyDown(keyCode, event);
}
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent m = new Intent(this, Home.class);
startActivity(m);
return true;
case R.id.refresh:
webview.reload();
Toast.makeText(this, "Refreshing...", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void onStop()
{
super.onStop();
CookieSyncManager.getInstance().sync();
}
}

Step #1: Do not implement GeolocationPermissions.Callback on the activity. Use some other object for GeolocationPermissions.Callback, one implemented in a public Java class that you would not load if you are running on older versions of the OS.
Step #2: Read the answers and comments on the question you asked previously, which covers what you need to know for the rest. Notably, you would make GeoClient be a public Java class in its own file, so you can avoid loading it on older versions of the OS. Personally, I like the Stephen C answer, and I demonstrate its use here.

Related

Faster activity transition

I have created a basic Activity with a WebView. I have added a method in the WebView which loads an error.html page from the asset folder when the WebView receives a HTTP error. I wanted to hide the Share menu item when this error.html page was loaded and so, I moved this to a new Activity.
Now, what's happening is, when there's a connectivity error, the default connectivity error of Android loads first and then the Activity transition takes place. Thus, even though the transition is working fine, users can see the deault Android connectivity error page for a few milliseconds. Is there any way in which I can hide that error page completely as such the users can only see my custom error page.
Here's my MainActivity.java:
package com.ananya.brokenhearts;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity
{
private WebView WebView;
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
private String currentURL;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = findViewById(R.id.webView);
ProgressBar = findViewById(R.id.progressBar);
LinearLayout = findViewById(R.id.layout);
ProgressBar.setMax(100);
WebView.loadUrl("https://www.brokenhearts.ml/index.html");
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setUserAgentString("Broken Hearts/1.0");
WebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
LinearLayout.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
LinearLayout.setVisibility(View.GONE);
super.onPageFinished(view, url);
currentURL = url;
}
#Override
public void onReceivedError(WebView webview, int i, String s, String s1)
{
Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url2)
{
if (url2.contains("www.brokenhearts.ml"))
{
view.loadUrl(url2);
return false;
} else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url2));
startActivity(intent);
return true;
}
}
});
WebView.setWebChromeClient(new WebChromeClient()
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
ProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.backward:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
WebView.reload();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,currentURL);
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Copied URL");
startActivity(Intent.createChooser(shareIntent,"Share URL"));
break;
case R.id.update:
Intent intent = new Intent(MainActivity.this, UpdateActivity.class);
startActivity(intent);
finish();
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed()
{
if (WebView.canGoForward())
{
WebView.goForward();
} else
{
Toast.makeText(this, "Can't go further", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed ()
{
if (WebView.canGoBack())
{
WebView.goBack();
} else
{
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle("Are you sure you want to exit?")
.setMessage("Tapping 'Yes' will close the app. Tap 'No' to continue using the app")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
Prior to this, I was directly loading the error.html page in the MainActivity itself when there was an error and thus, the default error page wasn't visible. But, I wanted to hide the Share button when error.html page was loaded. I didn't know how to do and I didn't get any response to that question where I had posted it. Thus, I thought of creating a seperate Activity to load the error.html which can let me hide the Share menu icon.
Also, I've tried to add the WebView.loadUrl("file:///android_asset/error.html"); in the same method before that intent hoping that it'll load before the Activity transition, however, that didn't help. I can still see the default Android connectivity error page.
Just to clarify, this is the default error page that I'm talking about: https://i.stack.imgur.com/bMMHh.png
and there's a custom one that I've made that I'm displaying now in the ErrorActivity.java.
What can I do about this?
Hide the webview when an error occured.
#Override
public void onReceivedError(WebView webview, int i, String s, String s1)
{
WebView.setVisibility(View.GONE);**hide the webview when an error occured**
Intent intent = new Intent(MainActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
Regarding hiding the share menu icon, you could always use onPrepareOptionsMenu() to hide your share menu if there is any error flag.
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.share).setVisible(!isPageError);
return true;
}
which would require you to have a isPageError boolean set to true in your
#Override
public void onReceivedError(WebView webview, int i, String s, String s1{
isPageError = true;
}

Progress Bar only loads first time. On second page it does not show

Hello i have java code where progressBar Loads just for first time only.
second time when surfing inner pages it does not shows at all.
package ext.packagename.apk;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
OneSignal.startInit(this).init();
web = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//open in webview
//web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://example1.com");
// opening in browser instead of WebView
web.setWebViewClient(new MyAppWebViewClient());
}
public class MyAppWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("exmaple1.com") || Uri.parse(url).getHost().endsWith("example2.com") || Uri.parse(url).getHost().endsWith("example3.com") ) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Alert")
.setMessage("exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
return super.onKeyDown(keyCode, event);
}
}
Progressbar is loading very fine at first time when main page loads. after that it disappear.
Use
progressBar.setVisibility(View.VISIBLE);
in onPageStarted method

How to use go back in sites correct?

I have my WebViewFragment and of course i want to go back in the site im browsing but i have the error:
The method onBackPressed() is undefined for the type Fragment
Why? I don´t understand that?
What am i doing wrong?
Here´s my full webview code i´m using.
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Fragment {
WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Retrieving the currently selected item number
int position = getArguments().getInt("position");
String url = getArguments().getString("url");
// List of rivers
String[] menus = getResources().getStringArray(R.array.menus);
// Creating view corresponding to the fragment
View v = inflater.inflate(R.layout.fragment_layout, container, false);
// Updating the action bar title
getActivity().getActionBar().setTitle(menus[position]);
//Initializing and loading url in webview
webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(url);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
});
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
return v;
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}}
If i´m using:
public void onBackPressed() {
Fragment webview = getFragmentManager().findFragmentByTag("webview");
if (webview instanceof WebViewFragment) {
boolean goback = ((WebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}}
I have the errors:
The method canGoBack() is undefined for the type WebViewFragment
The method onBackPressed() is undefined for the type Fragment
Thank you dudes for your help!
Found the solution what is working for me in my fragment.
webView.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return v;

In Android Project, Single File has R errors [duplicate]

This question already has answers here:
Why are my resources suddenly unresolved in my Android project?
(2 answers)
Closed 9 years ago.
I have a project working perfectly on Windows in Eclipse. As most of my work is now on a Mac at my job, I'm switching over to Eclipse for Mac.
I have fixed all of the build path errors across the project, and all that remains are the "this_xml_name cannot be resolved or is not a field", in theory resulting in an error when building my R file.
However, this is the first I have encountered this problem appearing only in a single file, and it is not just id's or layouts. It happens in R.layout, R.id, R.menu, and R.drawable. All other references throughout my project are perfectly fine, only errors are found at each of the R. references in the linked file.
MapActivity.java
package com.example.android;
import java.util.Timer;
import java.util.TimerTask;
import android.R;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends FragmentActivity {
FragmentActivity activity = this;
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
protected GoogleMap mMap;
String locAddr;
String locName;
Double locLongitude;
Double locLatitude;
final Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
locAddr = extras.getString("address");
locName = extras.getString("name");
locLongitude = extras.getDouble("longitude");
locLatitude = extras.getDouble("latitude");
activity.setTitle(locName);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable()
{
public void run()
{
LatLng coordinates = new LatLng(locLatitude, locLongitude);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 14.0f));
Marker marker = mMap.addMarker(new MarkerOptions()
.position(coordinates)
.title(locName)
.snippet(locAddr)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker)));
marker.showInfoWindow();
/*mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(MapActivity.this, DetailsActivity.class);
intent.putExtra("userkey", "MattCoker");
intent.putExtra("geolat", "29.7530");
intent.putExtra("geolong", "geozip");
intent.putExtra("clientid", "0");
intent.putExtra("siteid", "0");
startActivity(intent);
}
});*/
}
});
}
}, 3000);
} else {
Toast.makeText(activity, "Something went wrong displaying this location!", Toast.LENGTH_LONG).show();
}
}
}
else {
setContentView(R.layout.no_available_maps);
}
//Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
activity.getActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, activity, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(activity, "Can't connect to Google Play Services", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag = null;
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
#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);
// Associate searchable configuration with the SearchView
/*SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));*/
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int selectedMenuItem = item.getItemId();
if (selectedMenuItem == R.id.action_settings) {
Intent settingsIntent = new Intent(activity, SettingsActivity.class);
startActivity(settingsIntent);
return true;
} else if (selectedMenuItem == R.id.send_feedback) {
Intent sendFeedback = new Intent(android.content.Intent.ACTION_SEND);
sendFeedback.setType("message/rfc822");
sendFeedback.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"usersupport#example.com"});
sendFeedback.putExtra(android.content.Intent.EXTRA_SUBJECT, "Feedback on example...");
startActivity(Intent.createChooser(sendFeedback, "Send Email"));
//TODO: Create Feedback Activity to send email
return true;
}
return false;
}
}
If you have errors in your resource files R.java will not be generated. Fix those errors and clean and build.
Looking at the code you have
import android.R;
Replace it with
import com.example.android.R;

How to Ignore certain methods and code in a Class? Based on SDK

I was reading over http://android-developers.blogspot.com/2009/04/backward-compatibility-for-android.html But I'm really not grasping how to ignore certain lines of code. I have this Activity (posted below) and it's a simple webview. However, I want to have geolocation enabled(even if it is only for 2.0 and up phones), since these methods weren't introduced until SDK 5 (android 2.0) and I would like the webview to be able to at the very least be able to load on a 1.5 phone rather than just crashing. Could someone possibly show me how to take this code and make it ignore the lines of code that i pointed out with the starred comments when the users phone SDK is LESS than SDK 5?
package com.my.app;
import com.facebook.android.R;
//NEEDS TO BE IGNORED**********************************************************
import android.webkit.GeolocationPermissions;
import android.webkit.GeolocationPermissions.Callback;
//END**************************************************************************
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
//GeolocationPermissionsCallback NEEDS TO BE IGNORED**********************************************************
public class Places extends Activity implements GeolocationPermissions.Callback{
private ProgressDialog progressBar;
public WebView webview;
private static final String TAG = "Main";
String geoWebsiteURL = "http://google.com";
#Override
public void onStart()
{
super.onStart();
CookieSyncManager.getInstance().sync();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new testClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.loadUrl("http://google.com");
progressBar = ProgressDialog.show(Places.this, "", "Loading Page...");
//THIS NEEDS TO BE IGNORED************************************************************
webview.getSettings().setGeolocationEnabled(true);
GeoClient geo = new GeoClient();
webview.setWebChromeClient(geo);
}
public void invoke(String origin, boolean allow, boolean remember) {
}
final class GeoClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
//END OF CODE THAT NEEDS TO BE IGNORED************************************************
}
private class testClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
if (url.startsWith("mailto:") || url.startsWith("geo:") ||
url.startsWith("tel:")) {
Intent intent = new Intent
(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
Intent z = new Intent(this, Search.class);
startActivity(z);
}
return super.onKeyDown(keyCode, event);
}
public boolean onCreateOptionsMenu (Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent m = new Intent(this, Home.class);
startActivity(m);
return true;
case R.id.refresh:
webview.reload();
Toast.makeText(this, "Refreshing...", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
public void onStop()
{
super.onStop();
CookieSyncManager.getInstance().sync();
}
}
There are (at least) two possible solutions for your problem:
Different versions for different OS - create different builds of your software for different OS. This is a common approach, a lot of open source projects offer different builds for linux, windows, mac os. Your case is similiar, you could create different builds for android 1.5, 2.0, ...
One version for all Android OS - If you can find a way to detect the version of the OS at runtime, then you can redesign your code to run on different OS. You can add special classes for android 1.6 and 2.0 and make sure, that only the correct classes are loaded.
A quick example for your code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
progressBar = ProgressDialog.show(Places.this, "", "Loading Page...");
if (isGeolocationAvailable()) {
Android20Util.enableGeolocation(webview);
}
}
Android20Util contains some static methods, like:
public static void enableGeolocation(WebView webview) {
webview.getSettings().setGeolocationEnabled(true);
webview.setWebChromeClient(new GeoClient());
}

Categories