Google Analytic Android Example - java

Google has an example on analytic data for mobile devices. The code is provided here. I added the jar file and everything compiles fine, but I get an error up running the app.
I took out the UA ID for security reasons (not sure if that matters or not)
LogCat provides me with this information:
E/AndroidRuntime(1175): java.lang.NoClassDefFoundError: com.google.android.apps.analytics.GoogleAnalyticsTracker
AND
E/AndroidRuntime(1130):at com.google.android.apps.analytics.sample.TestActivity.onCreate(TestActivity.java:19)
From what it says, it can't find the googleAnalyticTracker? But if it compiles fine why can't it find it?
package com.google.android.apps.analytics.sample;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class TestActivity extends Activity {
GoogleAnalyticsTracker tracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker in manual dispatch mode...
// tracker.startNewSession("", this);
// ...alternatively, the tracker can be started with a dispatch interval
// (in seconds).
tracker.startNewSession("", 20, this);
setContentView(R.layout.main);
Button createEventButton = (Button) findViewById(R.id.NewEventButton);
createEventButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tracker.trackEvent("Clicks", // Category
"Button", // Action
"clicked", // Label
77); // Value
}
});
Button createPageButton = (Button) findViewById(R.id.NewPageButton);
createPageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Add a Custom Variable to this pageview, with name of "Medium"
// and value "MobileApp"
tracker.setCustomVar(1, "Medium", "Mobile App");
// Track a page view. This is probably the best way to track
// which parts of your application
// are being used.
// E.g.
// tracker.trackPageView("/help"); to track someone looking at
// the help screen.
// tracker.trackPageView("/level2"); to track someone reaching
// level 2 in a game.
// tracker.trackPageView("/uploadScreen"); to track someone
// using an upload screen.
tracker.trackPageView("/testApplicationHomeScreen");
}
});
Button quitButton = (Button) findViewById(R.id.QuitButton);
quitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Button dispatchButton = (Button) findViewById(R.id.DispatchButton);
dispatchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Manually start a dispatch, not needed if the tracker was
// started with a dispatch
// interval.
tracker.dispatch();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stopSession();
}
}

I too had the same problem after I updated my android SDK. I resolved it by doing the following:
Right Click on your project -> Build Path -> Configure Build Path -> Select Order and Export Tab -> Check the GoogleAnalyticsJar.jar -> Press OK.
This helped me resolve the problem. Hope it helps you also.

Create alalytics.xml in your your layout folder and paste the following code.
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<!--Replace placeholder ID with your tracking ID-->
<string name="ga_trackingId">UA-XXXX-Y</string>
<!--Enable automatic activity tracking-->
<bool name="ga_autoActivityTracking">true</bool>
<!--Enable automatic exception tracking-->
<bool name="ga_reportUncaughtExceptions">true</bool>
</resources>
Create Helper.java class and paste the following code.
import android.content.Context;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.google.tagmanager.DataLayer;
import com.google.tagmanager.TagManager;
public class Helper{
/**
* Push an "openScreen" event with the given screen name. Tags that match that event will fire.
*/
private static Tracker tracker;
public static void pushOpenScreenEvent(Context context, String screenName) {
// Instantiate the Tracker
tracker = EasyTracker.getInstance(context);
tracker.set(Fields.SCREEN_NAME, screenName);
// Send a screenview.
tracker.send(MapBuilder
.createAppView()
.build()
);
}
/**
* Push an "Button clicked" event with the given screen name. Tags that match that event will fire.
*/
public static void pushbtnClickedEvent(Context context, String clickE) {
tracker = EasyTracker.getInstance(context);
// Values set directly on a tracker apply to all subsequent hits.
tracker.set(Fields.SCREEN_NAME, "Home Screen");
// This screenview hit will include the screen name "Home Screen".
tracker.send(MapBuilder.createAppView().build());
// And so will this event hit.
tracker.send(MapBuilder
.createEvent("UI", "click", "my btn clicked", null)
.build()
);
}
/**
* Push a "closeScreen" event with the given screen name. Tags that match that event will fire.
*/
public static void pushCloseScreenEvent(Context context, String screenName) {
// Instantiate the Tracker
tracker = EasyTracker.getInstance(context);
tracker.set(Fields.SCREEN_NAME, screenName);
// Send a screenview.
tracker.send(MapBuilder
.createAppView()
.build()
);
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.analytics.tracking.android.EasyTracker;
public class MainActivity extends Activity {
Button btnClickEvent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClickEvent=(Button)findViewById(R.id.button1);
btnClickEvent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Helper.pushbtnClickedEvent(MainActivity.this, "Button Clicked");
}
});
}
#Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
Helper.pushOpenScreenEvent(this, "Main Activity");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
EasyTracker.getInstance(this).activityStop(this); // Add this method
}
}
Now,your application is ready ,simply press the "Button" then,open your Google analytics dashboard.
Dont forget to add these permissions in manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Refered from:http://velmuruganandroidcoding.blogspot.in/2014/08/google-analytics-in-android.html

Related

where to instantiate an anonymous class?

I am trying to use a code from this link https://developer.android.com/training/connect-devices-wirelessly/nsd.html
"from Discover Services on the Network."
I copy and paste code as the following:
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button aButton = (Button) findViewById(R.id.MyButton);
aButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// there is an error in the next line, ";" expected.
// but I do not know where to put ; exactly
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
// Save the service name. Android may have changed it in order to
// resolve a conflict, so update the name you initially requested
// with the name Android actually used.
mServiceName = NsdServiceInfo.getServiceName();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Registration failed! Put debugging code here to determine why.
}
#Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
// Service has been unregistered. This only happens when you call
// NsdManager.unregisterService() and pass in this listener.
}
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Unregistration failed. Put debugging code here to determine why.
}
};
} }
});
}
}
But there is an error in the this Line "public void initializeRegistrationListener()", ";" expected. but I do not know where to put ";" exactly or there is something else wrong that I cannot see it, can someone guide me, please?
PS: I am trying to make my phone discovers Mdns service that I created on my laptop using javascript, I have no experience in Java but I need to run the previous code to test the service that I have created already.
First of all you need an xml that contains an Button(this button will have android:id="#+id/mybutton", and that's the id you have to use on findViewById(R.id.mybutton).
In onCreate method of your activity you will write that code that you showed us, and you are good to go.
Another small step, if you wrote your own xml, make sure to have this line in onCreate
setContentView(R.layout.yourxml)

Android bugs on device. What should I do to fix them? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my application I noticed these three things:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The problem is I don't want the user to click on Back at a certain point in my application. I don't want to disable the back button completely in my application, only when one intent is called. How can I do that?
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my application, some of the toast notifications are residual and are popping outside of my application. Is there a reason for that? Did I miss something in the activity lifecycle to handle the cancellation of toasts at a certain point?
Lastly, this one is rather tough to solve. How do I lock my screen so that when the user rotates the device, that the activity doesn't not get called again and the asynctask can still resume without starting over again?
Thanks a lot for your time. Just curious why these things happen and what should I look into?
Here's my code:
//Main Activity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.*;
public class MainActivity extends Activity {
//fields
private ProgressDialog progressBar;
private Context context;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_setup);
//Set the context
context = this;
//Initialize the start setup button and add an onClick event listener to the button
final Button start_setup_button = (Button) findViewById(R.id.start_setup_button);
start_setup_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Executes the AsyncTask
new RetrieveInfoTask().execute();
//Instantiates the intent to launch a new activity
Intent myIntent = new Intent(MainActivity.this, RetrieveInfoActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public class RetrieveInfoTask extends AsyncTask<Void, Void, Void> {
//Called on the UI thread to execute progress bar
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage(MainActivity.this.getString(R.string.retrieve_info));
progressBar.show();
}
//Methods that retrieves information from the user device. This is performed in the Background thread
private void retrieveInfo() {
try {
//Reading the drawable resource line by line
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = MainActivity.this.getResources().openRawResource(R.drawable.user_info);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//doInBackground calls retrieveInfo() to perform action in Background
#Override
protected Void doInBackground(Void... params) {
retrieveInfo();
return null;
}
//When the background task is done, dismiss the progress bar
#Override
protected void onPostExecute(Void result) {
if (progressBar!=null) {
progressBar.dismiss();
}
}
}
}
//RetrieveInfoActivity.java
package com.example.Patient_Device;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class RetrieveInfoActivity extends Activity {
private static String TAG = "RetrieveInfoActivity";
private Context context;
String fileLastSync = "09-18-2014 03:47 PM";
#Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.retrieve_info);
//Once the new activity is launched, the setup is complete
Toast.makeText(getApplicationContext(), "Setup Complete!",
Toast.LENGTH_LONG).show();
//Gets the 'last synced' string and sets to datetime of the last sync
Resources resources = context.getResources();
String syncString = String.format(resources.getString(R.string.last_sync), fileLastSync);
//Dynamically sets the datetime of the last sync string
TextView lastSyncTextView = ((TextView) findViewById(R.id.last_sync) );
lastSyncTextView.setText(syncString);
//calls registerReceiver to receive the broadcast for the state of battery
this.registerReceiver(this.mBatInfoReceiver,new
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
//Battery level
int level = intent.getIntExtra("level", 0);
//Dynamically sets the value of the battery level
TextView batteryTextView = ((TextView) findViewById(R.id.battery) );
batteryTextView.setText("Battery Level: " + String.valueOf(level)+ "%");
//If the battery level drops below 25%, then announce the battery is low
//TODO: Add 25 to constants file.
if(level < 25) {
Toast.makeText(getApplicationContext(), "Low Battery!",
Toast.LENGTH_LONG).show();
}
//Plugged in Status
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//Battery Status
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
//If the device is charging or contains a full status, it's charging
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
//If the device isCharging and plugged in, then show that the battery is charging
if(isCharging && plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
Toast.makeText(getApplicationContext(), "Charging.." + String.valueOf(level)+ "%",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unplugged!",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onDestroy() {
try {
super.onDestroy();
unregisterReceiver(this.mBatInfoReceiver);
}
catch (Exception e) {
Log.e(RetrieveInfoctivity.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
}
//StartSetupActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class StartSetupActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
//FragmentsActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentsActivity extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, container, false);
}
}
First of all whenever you want to disable back press just override onBackPressed() method and remove super. like this:
#Override
public void onBackPressed() {
//super.onBackPressed();
}
Second you'r using application context to show toast. use activity context.
Toast.makeText(this or YourActivity.this, "Setup Complete!", Toast.LENGTH_LONG).show();
Third just add this attribute into your manifest class. This will avoid recrating your activity when orientation change
android:configChanges="orientation"
I'll answer these in order:
Back Button
You can override onBackPressed in your Activity and determine if you want to consume it or let Android process it.
#Override
public void onBackPressed()
{
// Set this how you want based on your app logic
boolean disallowBackPressed = false;
if (!disallowBackPressed)
{
super.onBackPressed();
}
}
Toasts
Toasts are enqueued with the Notification Manager. If you show multiple Toasts in a row, they get queued up and shown one at a time until the queue is empty.
Locking Orientation For Activity
Use android:screenOrientation="landscape" or android:screenOrientation="portrait" on your activity element in your manifest to lock the orientation.
I think that these questions should be asked separately, because the answer in detail to every item of your question is too long, but I hope this helps:
-The back button is enabled when going from one activity to another enabling the user to click on back to the original activity. The
problem is I don't want the user to click on Back at a certain point
in my application. I don't want to disable the back button completely
in my application, only when one intent is called. How can I do that?
You can override the onBackPressed on the activities you don't want the user to go back.
#Override
public void onBackPressed() {
//Leave it blank so it doesn't do anything
}
-I noticed something strange... when a toast notification pops up in my application all is well until I exit my application. When I exit my
application, some of the toast notifications are residual and are
popping outside of my application. Is there a reason for that? Did I
miss something in the activity lifecycle to handle the cancellation of
toasts at a certain point?
I think that the reason behind that is that toast go into a que, and are showed in order, even if the app is no longer visible.
Lastly, this one is rather tough to solve. How do I lock my screen so
that when the user rotates the device, that the activity doesn't not
get called again and the asynctask can still resume without starting
over again?
For this, you can use the following code in your manifest
android:configChanges="orientation|screenSize"/>
However this is NOT recommended by google, I suggest you read the following link to get a little more information on how to handle orientation changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html

I want to make password protected android application

I want to make password protected android app, but when in this simple program system is not matching two strings.
package com.pokmgr;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainPM extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pm_layout);
final EditText pin = (EditText) findViewById(R.id.pinET);
final String pass = pin.getText().toString();
final String code = "ajaj";
Button enter = (Button) findViewById(R.id.enterBtn);
enter.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (pass.equals(code)) {
Intent in = new Intent(MainPM.this, Menu.class);
startActivity(in);
}
else {
Intent in = new Intent(MainPM.this, Menu2.class);
startActivity(in);
}
}
});
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pm_layout, menu);
return true;
}*/
}
I have made Menu and Menu2 class, but every time Menu2 class is accessed. Even if I enter same pass that is "ajaj" [in this code to test]
i have defined both activities in manifest file.
Can't understand why pass.eqals(code) is not working
The problem is that you are setting pass to the contents of the EditText when the activity gets created. Instead you have to retrieve the contents of your EditText inside the OnClickListener.
Like this:
public void onClick(View v) {
final String pass = pin.getText().toString();
if (pass.equals(code)) {
// do something
} else {
// do something different
}
}
Put pin.getText().toString(); inside onClick of button. You are setting variable pass before the user actually entered something in pinEt EditText.

setOnClickListener in simple Android does not work

I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.

When Getting GPS Location, load another URL

I have a little problem... I have made an Android application which extends the webview. The webview Html page with a map on like this: Map example, it was also here I got my inspiration. My onCreate method looks like this:
super.onCreate(savedInstanceState);
//Removes the title bar in the application
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Creation of the Webview found in the XML Layout file
browserView = (WebView)findViewById(R.id.webkit);
//Removes both vertical and horizontal scroll bars
browserView.setVerticalScrollBarEnabled(false);
browserView.setHorizontalScrollBarEnabled(false);
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Enable Javascripts
url = "http://www.my-homepage.dk/map_example.html";
browserView.getSettings().setJavaScriptEnabled(true);
//The website which is wrapped to the webview
browserView.loadUrl(url);
So when My application gets a GPS location, it invokes this method:
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
StringBuilder buf=new StringBuilder(url);
buf.append("?");
buf.append("lon=");
buf.append(String.valueOf(location.getLongitude()));
buf.append("&");
buf.append("lat=");
buf.append(String.valueOf(location.getLatitude()));
browserView.loadUrl(buf.toString());
}
So it basically just loads another URL.... But, my problem is, 1. it keeps the orignal website "map image", i imagined it would "unload" the page, and 2. When the second url is loaded, it takes quite a long time before it is finished, and when i am testing on my HTC Desire, it sometimes doesnt show the second loaded page (the map with location) before it turns the screen off and lock, or if i go out and in the application, that sometimes helps too...
Hope you can help :)
A suggestion - in onLocationChanged, make locationFound(); the first statement instead of the last.
It would be good to stop the listener immediately, as the loadUrl statement could take some time to complete, while the provider could be sending more updates.
Here is the solution... The GPS listener apparently broadcast more than once ;) so, when the GPS finds a location it loads the url and then stops broadcasting.
So the problem before was, that it sent loads of URL's to the html page, and therefore never just loaded 1 single url. And i just simplified the onLocationChanged a bit.
public void locationFound(){
myLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
String lon = "lon="+String.valueOf(location.getLongitude());
String lat = "lat="+String.valueOf(location.getLatitude());
browserView.loadUrl(url+"?"+lon+"&"+lat);
locationFound();
}
Here is the SourceCode for the application:
package com.webview;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewTest extends Activity implements LocationListener{
private WebView browserView;
private static String PROVIDER="gps";
private LocationManager myLocationManager=null;
private String url;
private boolean LocFound = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Removes the title bar in the application
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Creation of the Webview found in the XML Layout file
browserView = (WebView)findViewById(R.id.webkit);
//Removes both vertical and horizontal scroll bars
browserView.setVerticalScrollBarEnabled(false);
browserView.setHorizontalScrollBarEnabled(false);
myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
//Enable Javascripts
url = "http://www.test.dk/test.html";
browserView.getSettings().setJavaScriptEnabled(true);
//The website which is wrapped to the webview
browserView.loadUrl(url);
}
#Override
public void onResume() {
super.onResume();
myLocationManager.requestLocationUpdates(PROVIDER, 0,
0,
this);
}
#Override
public void onPause() {
super.onPause();
myLocationManager.removeUpdates(this);
}
public void locationFound(){
myLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
String lon = "lon="+String.valueOf(location.getLongitude());
String lat = "lat="+String.valueOf(location.getLatitude());
browserView.loadUrl(url+"?"+lon+"&"+lat);
locationFound();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Categories