Android Tutorial - Hardware : Location
Location service and LocationManager
package app.Test; import java.util.List; import android.app.Activity; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.widget.TextView; public class appTest extends Activity implements LocationListener { private static final String[] A = { "n/a", "fine", "coarse" }; private static final String[] P = { "n/a", "low", "medium", "high" }; private static final String[] S = { "out of service","temporarily unavailable", "available" }; private LocationManager mgr; private TextView output; private String best; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mgr = (LocationManager) getSystemService(LOCATION_SERVICE); output = (TextView) findViewById(R.id.output); log("Location providers:"); List<String> providers = mgr.getAllProviders(); for (String provider : providers) { dumpProvider(provider); } Criteria criteria = new Criteria(); best = mgr.getBestProvider(criteria, true); log("\nBest provider is: " + best); Location location = mgr.getLastKnownLocation(best); dumpLocation(location); } @Override protected void onResume() { super.onResume(); mgr.requestLocationUpdates(best, 15000, 1, this); } @Override protected void onPause() { super.onPause(); mgr.removeUpdates(this); } public void onLocationChanged(Location location) { dumpLocation(location); } public void onProviderDisabled(String provider) { log("\nProvider disabled: " + provider); } public void onProviderEnabled(String provider) { log("\nProvider enabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { log("\nProvider status changed: " + provider + ", status=" + S[status] + ", extras=" + extras); } private void log(String string) { output.append(string + "\n"); } private void dumpProvider(String provider) { LocationProvider info = mgr.getProvider(provider); StringBuilder builder = new StringBuilder(); builder.append("LocationProvider[").append("name=") .append(info.getName()).append(",enabled=") .append(mgr.isProviderEnabled(provider)) .append(",getAccuracy=").append(A[info.getAccuracy()]) .append(",getPowerRequirement=") .append(P[info.getPowerRequirement()]) .append(",hasMonetaryCost=").append(info.hasMonetaryCost()) .append(",requiresCell=").append(info.requiresCell()) .append(",requiresNetwork=").append(info.requiresNetwork()) .append(",requiresSatellite=").append(info.requiresSatellite()) .append(",supportsAltitude=").append(info.supportsAltitude()) .append(",supportsBearing=").append(info.supportsBearing()) .append(",supportsSpeed=").append(info.supportsSpeed()) .append("]"); log(builder.toString()); } private void dumpLocation(Location location) { if (location == null) log("\nLocation[unknown]"); else log("\n" + location.toString()); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/output" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ScrollView>
Location service
package apt.tutorial; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class DetailForm extends Activity { EditText name=null; EditText address=null; EditText notes=null; EditText feed=null; RadioGroup types=null; RestaurantHelper helper=null; String restaurantId=null; TextView location=null; LocationManager locMgr=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail_form); locMgr=(LocationManager)getSystemService(LOCATION_SERVICE); helper=new RestaurantHelper(this); name=(EditText)findViewById(R.id.name); address=(EditText)findViewById(R.id.addr); notes=(EditText)findViewById(R.id.notes); types=(RadioGroup)findViewById(R.id.types); feed=(EditText)findViewById(R.id.feed); location=(TextView)findViewById(R.id.location); restaurantId=getIntent().getStringExtra(LunchList.ID_EXTRA); if (restaurantId!=null) { load(); } } @Override public void onPause() { save(); locMgr.removeUpdates(onLocationChange); super.onPause(); } @Override public void onDestroy() { helper.close(); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.details_option, menu); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (restaurantId==null) { menu.findItem(R.id.location).setEnabled(false); } return(super.onPrepareOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==R.id.feed) { if (isNetworkAvailable()) { Intent i=new Intent(this, FeedActivity.class); i.putExtra(FeedActivity.FEED_URL, feed.getText().toString()); startActivity(i); } else { Toast .makeText(this, "Sorry, the Internet is not available", Toast.LENGTH_LONG) .show(); } return(true); } else if (item.getItemId()==R.id.location) { locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, onLocationChange); return(true); } return(super.onOptionsItemSelected(item)); } private boolean isNetworkAvailable() { ConnectivityManager cm=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); NetworkInfo info=cm.getActiveNetworkInfo(); return(info!=null); } private void load() { Cursor c=helper.getById(restaurantId); c.moveToFirst(); name.setText(helper.getName(c)); address.setText(helper.getAddress(c)); notes.setText(helper.getNotes(c)); feed.setText(helper.getFeed(c)); if (helper.getType(c).equals("sit_down")) { types.check(R.id.sit_down); } else if (helper.getType(c).equals("take_out")) { types.check(R.id.take_out); } else { types.check(R.id.delivery); } location.setText(String.valueOf(helper.getLatitude(c)) +", " +String.valueOf(helper.getLongitude(c))); c.close(); } private void save() { if (name.getText().toString().length()>0) { String type=null; switch (types.getCheckedRadioButtonId()) { case R.id.sit_down: type="sit_down"; break; case R.id.take_out: type="take_out"; break; default: type="delivery"; break; } if (restaurantId==null) { helper.insert(name.getText().toString(), address.getText().toString(), type, notes.getText().toString(), feed.getText().toString()); } else { helper.update(restaurantId, name.getText().toString(), address.getText().toString(), type, notes.getText().toString(), feed.getText().toString()); } } } LocationListener onLocationChange=new LocationListener() { public void onLocationChanged(Location fix) { helper.updateLocation(restaurantId, fix.getLatitude(), fix.getLongitude()); location.setText(String.valueOf(fix.getLatitude()) +", " +String.valueOf(fix.getLongitude())); locMgr.removeUpdates(onLocationChange); Toast .makeText(DetailForm.this, "Location saved", Toast.LENGTH_LONG) .show(); } public void onProviderDisabled(String provider) { // required for interface, not used } public void onProviderEnabled(String provider) { // required for interface, not used } public void onStatusChanged(String provider, int status, Bundle extras) { // required for interface, not used } }; } package apt.tutorial; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } package apt.tutorial; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Messenger; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.mcsoxford.rss.RSSItem; import org.mcsoxford.rss.RSSFeed; public class FeedActivity extends ListActivity { public static final String FEED_URL="apt.tutorial.FEED_URL"; private InstanceState state=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); state=(InstanceState)getLastNonConfigurationInstance(); if (state==null) { state=new InstanceState(); state.handler=new FeedHandler(this); Intent i=new Intent(this, FeedService.class); i.putExtra(FeedService.EXTRA_URL, getIntent().getStringExtra(FEED_URL)); i.putExtra(FeedService.EXTRA_MESSENGER, new Messenger(state.handler)); startService(i); } else { if (state.handler!=null) { state.handler.attach(this); } if (state.feed!=null) { setFeed(state.feed); } } } @Override public Object onRetainNonConfigurationInstance() { if (state.handler!=null) { state.handler.detach(); } return(state); } private void setFeed(RSSFeed feed) { state.feed=feed; setListAdapter(new FeedAdapter(feed)); } private void goBlooey(Throwable t) { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder .setTitle("Exception!") .setMessage(t.toString()) .setPositiveButton("OK", null) .show(); } private static class InstanceState { RSSFeed feed=null; FeedHandler handler=null; } private class FeedAdapter extends BaseAdapter { RSSFeed feed=null; FeedAdapter(RSSFeed feed) { super(); this.feed=feed; } @Override public int getCount() { return(feed.getItems().size()); } @Override public Object getItem(int position) { return(feed.getItems().get(position)); } @Override public long getItemId(int position) { return(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row=convertView; if (row==null) { LayoutInflater inflater=getLayoutInflater(); row=inflater.inflate(android.R.layout.simple_list_item_1, parent, false); } RSSItem item=(RSSItem)getItem(position); ((TextView)row).setText(item.getTitle()); return(row); } } private static class FeedHandler extends Handler { FeedActivity activity=null; FeedHandler(FeedActivity activity) { attach(activity); } void attach(FeedActivity activity) { this.activity=activity; } void detach() { this.activity=null; } @Override public void handleMessage(Message msg) { if (msg.arg1==RESULT_OK) { activity.setFeed((RSSFeed)msg.obj); } else { activity.goBlooey((Exception)msg.obj); } } }; } package apt.tutorial; import android.app.Activity; import android.app.IntentService; import android.content.Intent; import android.os.Message; import android.os.Messenger; import android.util.Log; import org.mcsoxford.rss.RSSItem; import org.mcsoxford.rss.RSSFeed; import org.mcsoxford.rss.RSSReader; public class FeedService extends IntentService { public static final String EXTRA_URL="apt.tutorial.EXTRA_URL"; public static final String EXTRA_MESSENGER="apt.tutorial.EXTRA_MESSENGER"; public FeedService() { super("FeedService"); } @Override public void onHandleIntent(Intent i) { RSSReader reader=new RSSReader(); Messenger messenger=(Messenger)i.getExtras().get(EXTRA_MESSENGER); Message msg=Message.obtain(); try { RSSFeed result=reader.load(i.getStringExtra(EXTRA_URL)); msg.arg1=Activity.RESULT_OK; msg.obj=result; } catch (Exception e) { Log.e("LunchList", "Exception parsing feed", e); msg.arg1=Activity.RESULT_CANCELED; msg.obj=e; } try { messenger.send(msg); } catch (Exception e) { Log.w("LunchList", "Exception sending results to activity", e); } } } package apt.tutorial; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class LunchList extends ListActivity { public final static String ID_EXTRA="apt.tutorial._ID"; Cursor model=null; RestaurantAdapter adapter=null; RestaurantHelper helper=null; SharedPreferences prefs=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); helper=new RestaurantHelper(this); prefs=PreferenceManager.getDefaultSharedPreferences(this); initList(); prefs.registerOnSharedPreferenceChangeListener(prefListener); } @Override public void onDestroy() { super.onDestroy(); helper.close(); } @Override public void onListItemClick(ListView list, View view, int position, long id) { Intent i=new Intent(LunchList.this, DetailForm.class); i.putExtra(ID_EXTRA, String.valueOf(id)); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.option, menu); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==R.id.add) { startActivity(new Intent(LunchList.this, DetailForm.class)); return(true); } else if (item.getItemId()==R.id.prefs) { startActivity(new Intent(this, EditPreferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } private void initList() { if (model!=null) { stopManagingCursor(model); model.close(); } model=helper.getAll(prefs.getString("sort_order", "name")); startManagingCursor(model); adapter=new RestaurantAdapter(model); setListAdapter(adapter); } private SharedPreferences.OnSharedPreferenceChangeListener prefListener= new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key) { if (key.equals("sort_order")) { initList(); } } }; class RestaurantAdapter extends CursorAdapter { RestaurantAdapter(Cursor c) { super(LunchList.this, c); } @Override public void bindView(View row, Context ctxt, Cursor c) { RestaurantHolder holder=(RestaurantHolder)row.getTag(); holder.populateFrom(c, helper); } @Override public View newView(Context ctxt, Cursor c, ViewGroup parent) { LayoutInflater inflater=getLayoutInflater(); View row=inflater.inflate(R.layout.row, parent, false); RestaurantHolder holder=new RestaurantHolder(row); row.setTag(holder); return(row); } } static class RestaurantHolder { private TextView name=null; private TextView address=null; private ImageView icon=null; RestaurantHolder(View row) { name=(TextView)row.findViewById(R.id.title); address=(TextView)row.findViewById(R.id.address); icon=(ImageView)row.findViewById(R.id.icon); } void populateFrom(Cursor c, RestaurantHelper helper) { name.setText(helper.getName(c)); address.setText(helper.getAddress(c)); if (helper.getType(c).equals("sit_down")) { icon.setImageResource(R.drawable.ball_red); } else if (helper.getType(c).equals("take_out")) { icon.setImageResource(R.drawable.ball_yellow); } else { icon.setImageResource(R.drawable.ball_green); } } } } package apt.tutorial; import android.content.Context; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; class RestaurantHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME="lunchlist.db"; private static final int SCHEMA_VERSION=3; public RestaurantHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT, feed TEXT, lat REAL, lon REAL);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion<2) { db.execSQL("ALTER TABLE restaurants ADD COLUMN feed TEXT"); } if (oldVersion<3) { db.execSQL("ALTER TABLE restaurants ADD COLUMN lat REAL"); db.execSQL("ALTER TABLE restaurants ADD COLUMN lon REAL"); } } public Cursor getAll(String orderBy) { return(getReadableDatabase() .rawQuery("SELECT _id, name, address, type, notes, lat, lon FROM restaurants ORDER BY "+orderBy, null)); } public Cursor getById(String id) { String[] args={id}; return(getReadableDatabase() .rawQuery("SELECT _id, name, address, type, notes, feed, lat, lon FROM restaurants WHERE _ID=?", args)); } public void insert(String name, String address, String type, String notes, String feed) { ContentValues cv=new ContentValues(); cv.put("name", name); cv.put("address", address); cv.put("type", type); cv.put("notes", notes); cv.put("feed", feed); getWritableDatabase().insert("restaurants", "name", cv); } public void update(String id, String name, String address, String type, String notes, String feed) { ContentValues cv=new ContentValues(); String[] args={id}; cv.put("name", name); cv.put("address", address); cv.put("type", type); cv.put("notes", notes); cv.put("feed", feed); getWritableDatabase().update("restaurants", cv, "_ID=?", args); } public void updateLocation(String id, double lat, double lon) { ContentValues cv=new ContentValues(); String[] args={id}; cv.put("lat", lat); cv.put("lon", lon); getWritableDatabase().update("restaurants", cv, "_ID=?", args); } public String getName(Cursor c) { return(c.getString(1)); } public String getAddress(Cursor c) { return(c.getString(2)); } public String getType(Cursor c) { return(c.getString(3)); } public String getNotes(Cursor c) { return(c.getString(4)); } public String getFeed(Cursor c) { return(c.getString(5)); } public double getLatitude(Cursor c) { return(c.getDouble(6)); } public double getLongitude(Cursor c) { return(c.getDouble(7)); } } //res\xml\preferences.xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <ListPreference android:key="sort_order" android:title="Sort Order" android:summary="Choose the order the list uses" android:entries="@array/sort_names" android:entryValues="@array/sort_clauses" android:dialogTitle="Choose a sort order" /> </PreferenceScreen> //res\values\arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="sort_names"> <item>By Name, Ascending</item> <item>By Name, Descending</item> <item>By Type</item> <item>By Address, Ascending</item> <item>By Address, Descending</item> </string-array> <string-array name="sort_clauses"> <item>name ASC</item> <item>name DESC</item> <item>type, name ASC</item> <item>address ASC</item> <item>address DESC</item> </string-array> </resources> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LunchList</string> </resources> //res\menu\details_option.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/feed" android:title="RSS Feed" android:icon="@drawable/ic_menu_friendslist" /> <item android:id="@+id/location" android:title="Save Location" android:icon="@drawable/ic_menu_compass" /> </menu> //res\menu\option.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/add" android:title="Add" android:icon="@drawable/ic_menu_add" /> <item android:id="@+id/prefs" android:title="Settings" android:icon="@drawable/ic_menu_preferences" /> </menu> //res\layout-land\detail_form.xml <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="2" > <TableRow> <TextView android:text="Name:" /> <EditText android:id="@+id/name" android:layout_span="2" /> </TableRow> <TableRow> <TextView android:text="Address:" /> <EditText android:id="@+id/addr" android:layout_span="2" /> </TableRow> <TableRow> <TextView android:text="Type:" /> <RadioGroup android:id="@+id/types"> <RadioButton android:id="@+id/take_out" android:text="Take-Out" /> <RadioButton android:id="@+id/sit_down" android:text="Sit-Down" /> <RadioButton android:id="@+id/delivery" android:text="Delivery" /> </RadioGroup> <LinearLayout android:orientation="vertical"> <EditText android:id="@+id/notes" android:singleLine="false" android:gravity="top" android:lines="2" android:scrollHorizontally="false" android:maxLines="2" android:maxWidth="140sp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Notes" /> <EditText android:id="@+id/feed" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Feed URL" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:text="Location:" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/location" android:text="(not set)" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> </TableRow> </TableLayout> //res\layout\detail_form.xml <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1" > <TableRow> <TextView android:text="Name:" /> <EditText android:id="@+id/name" /> </TableRow> <TableRow> <TextView android:text="Address:" /> <EditText android:id="@+id/addr" /> </TableRow> <TableRow> <TextView android:text="Type:" /> <RadioGroup android:id="@+id/types"> <RadioButton android:id="@+id/take_out" android:text="Take-Out" /> <RadioButton android:id="@+id/sit_down" android:text="Sit-Down" /> <RadioButton android:id="@+id/delivery" android:text="Delivery" /> </RadioGroup> </TableRow> <TableRow> <TextView android:text="Location:" /> <TextView android:id="@+id/location" android:text="(not set)" /> </TableRow> <EditText android:id="@+id/notes" android:singleLine="false" android:gravity="top" android:lines="2" android:scrollHorizontally="false" android:maxLines="2" android:maxWidth="200sp" android:layout_span="2" android:hint="Notes" android:layout_marginTop="4dip" /> <EditText android:id="@+id/feed" android:layout_span="2" android:hint="Feed URL" /> </TableLayout> //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> //res\layout\row.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="4dip" > <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_marginRight="4dip" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:textStyle="bold" android:singleLine="true" android:ellipsize="end" /> <TextView android:id="@+id/address" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:singleLine="true" android:ellipsize="end" /> </LinearLayout> </LinearLayout>
Using LocationManager
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.widget.TextView; public class Test extends Activity { LocationManager manager; Location currentLocation; String selectedProvider; TextView locationView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); locationView = new TextView(this); setContentView(locationView); manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } @Override public void onResume() { super.onResume(); if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Location Manager"); builder.setMessage("GPS is currently disabled.\nWould you like to change these settings now?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.create().show(); } currentLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); updateDisplay(); int minTime = 5000; float minDistance = 0; manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, listener); } @Override public void onPause() { super.onPause(); manager.removeUpdates(listener); } private void updateDisplay() { if (currentLocation == null) { locationView.setText("Determining Your Location..."); } else { locationView.setText(String.format("Your Location:\n%.2f, %.2f", currentLocation.getLatitude(), currentLocation.getLongitude())); } } private LocationListener listener = new LocationListener() { @Override public void onLocationChanged(Location location) { currentLocation = location; updateDisplay(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }; }
My location
//AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.examples.mapper" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="3" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MyActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-library android:name="com.google.android.maps"></uses-library> </application> </manifest> //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="Map Of Your Location" /> <com.google.android.maps.MapView android:id="@+id/map" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:clickable="true" android:apiKey="YOUR_API_KEY_HERE" /> </LinearLayout> package com.examples.mapper; import android.os.Bundle; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; public class MyActivity extends MapActivity { MapView map; MapController controller; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); map = (MapView)findViewById(R.id.map); controller = map.getController(); ArrayList<GeoPoint> locations = new ArrayList<GeoPoint>(); ArrayList<Drawable> images = new ArrayList<Drawable>(); //Google HQ 37.427,-122.099 locations.add(new GeoPoint(37427222,-122099167)); images.add(getResources().getDrawable(R.drawable.logo)); //Subtract 0.01 degrees locations.add(new GeoPoint(37426222,-122089167)); images.add(getResources().getDrawable(R.drawable.icon)); //Add 0.01 degrees locations.add(new GeoPoint(37428222,-122109167)); images.add(getResources().getDrawable(R.drawable.icon)); LocationOverlay myOverlay = new LocationOverlay(this, getResources().getDrawable(R.drawable.icon)); myOverlay.setItems(locations, images); map.getOverlays().add(myOverlay); controller.setCenter(locations.get(0)); controller.setZoom(15); } @Override protected boolean isRouteDisplayed() { return false; } } import android.os.Bundle; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; public class MyActivity extends MapActivity { MapView map; MapController controller; MyLocationOverlay myOverlay; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); map = (MapView)findViewById(R.id.map); myOverlay = new MyLocationOverlay(this, map); map.getOverlays().add(myOverlay); } @Override public void onResume() { super.onResume(); myOverlay.enableMyLocation(); } @Override public void onPause() { super.onResume(); myOverlay.disableMyLocation(); } @Override protected boolean isRouteDisplayed() { return false; } }
Display GEO location
package app.test; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class Test extends Activity { private EditText lat; private EditText lon; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Button btn=(Button)findViewById(R.id.map); lat=(EditText)findViewById(R.id.lat); lon=(EditText)findViewById(R.id.lon); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String _lat=lat.getText().toString(); String _lon=lon.getText().toString(); Uri uri=Uri.parse("geo:"+_lat+","+_lon); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }); } } //main.cml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1,2" > <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="2dip" android:paddingRight="4dip" android:text="Location:" /> <EditText android:id="@+id/lat" android:layout_width="fill_parent" android:layout_height="wrap_content" android:cursorVisible="true" android:editable="true" android:singleLine="true" android:layout_weight="1" /> <EditText android:id="@+id/lon" android:layout_width="fill_parent" android:layout_height="wrap_content" android:cursorVisible="true" android:editable="true" android:singleLine="true" android:layout_weight="1" /> </TableRow> </TableLayout> <Button android:id="@+id/map" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show Me!" /> </LinearLayout>
Using location service for the weather
package com.commonsware.android.internet; import android.app.Activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.webkit.WebView; import android.widget.Toast; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.client.ResponseHandler; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class WeatherDemo extends Activity { private LocationManager mgr=null; private String format; private WebView browser; private HttpClient client; private List<Forecast> forecasts=new ArrayList<Forecast>(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mgr=(LocationManager)getSystemService(Context.LOCATION_SERVICE); format=getString(R.string.url); browser=(WebView)findViewById(R.id.webkit); client=new DefaultHttpClient(); } @Override public void onResume() { super.onResume(); mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10000.0f, onLocationChange); } @Override public void onPause() { super.onPause(); mgr.removeUpdates(onLocationChange); } private void updateForecast(Location loc) { String url=String.format(format, loc.getLatitude(), loc.getLongitude()); HttpGet getMethod=new HttpGet(url); try { ResponseHandler<String> responseHandler=new BasicResponseHandler(); String responseBody=client.execute(getMethod, responseHandler); buildForecasts(responseBody); String page=generatePage(); browser.loadDataWithBaseURL(null, page, "text/html", "UTF-8", null); } catch (Throwable t) { android.util.Log.e("WeatherDemo", "Exception fetching data", t); Toast .makeText(this, "Request failed: "+t.toString(), 4000) .show(); } } void buildForecasts(String raw) throws Exception { DocumentBuilder builder=DocumentBuilderFactory .newInstance() .newDocumentBuilder(); Document doc=builder.parse(new InputSource(new StringReader(raw))); NodeList times=doc.getElementsByTagName("start-valid-time"); for (int i=0;i<times.getLength();i++) { Element time=(Element)times.item(i); Forecast forecast=new Forecast(); forecasts.add(forecast); forecast.setTime(time.getFirstChild().getNodeValue()); } NodeList temps=doc.getElementsByTagName("value"); for (int i=0;i<temps.getLength();i++) { Element temp=(Element)temps.item(i); Forecast forecast=forecasts.get(i); forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue())); } NodeList icons=doc.getElementsByTagName("icon-link"); for (int i=0;i<icons.getLength();i++) { Element icon=(Element)icons.item(i); Forecast forecast=forecasts.get(i); forecast.setIcon(icon.getFirstChild().getNodeValue()); } } String generatePage() { StringBuilder bufResult=new StringBuilder("<html><body><table>"); bufResult.append("<tr><th width=\"50%\">Time</th>"+ "<th>Temperature</th><th>Forecast</th></tr>"); for (Forecast forecast : forecasts) { bufResult.append("<tr><td align=\"center\">"); bufResult.append(forecast.getTime()); bufResult.append("</td><td align=\"center\">"); bufResult.append(forecast.getTemp()); bufResult.append("</td><td><img src=\""); bufResult.append(forecast.getIcon()); bufResult.append("\"></td></tr>"); } bufResult.append("</table></body></html>"); return(bufResult.toString()); } LocationListener onLocationChange=new LocationListener() { public void onLocationChanged(Location location) { updateForecast(location); } public void onProviderDisabled(String provider) { // required for interface, not used } public void onProviderEnabled(String provider) { // required for interface, not used } public void onStatusChanged(String provider, int status, Bundle extras) { // required for interface, not used } }; class Forecast { String time=""; Integer temp=null; String iconUrl=""; String getTime() { return(time); } void setTime(String time) { this.time=time.substring(0,16).replace('T', ' '); } Integer getTemp() { return(temp); } void setTemp(Integer temp) { this.temp=temp; } String getIcon() { return(iconUrl); } void setIcon(String iconUrl) { this.iconUrl=iconUrl; } } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webkit" android:layout_width="fill_parent" android:layout_height="fill_parent" />
Using Intent to go to a geo location
package app.test; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; class MyBrowserActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.row); Uri url = getIntent().getData(); WebView webView = (WebView) findViewById(R.id.WebView01); webView.setWebViewClient(new Callback()); webView.loadUrl(url.toString()); } private class Callback extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return (false); } } } public class Test extends Activity { Button b1, b2, b3, b4, b5; int request_Code = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1 = (Button) findViewById(R.id.btn_webbrowser); b1.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent("android.intent.action.VIEW"); i.setData(Uri.parse("http://www.amazon.com")); startActivity(i); } }); b2 = (Button) findViewById(R.id.btn_makecalls); b2.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_CALL, Uri.parse("tel:+651234567")); startActivity(i); } }); b3 = (Button) findViewById(R.id.btn_showMap); b3.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri .parse("geo:37.827500,-122.481670")); startActivity(i); } }); b4 = (Button) findViewById(R.id.btn_chooseContact); b4.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(android.content.Intent.ACTION_PICK); i.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); startActivityForResult(i, request_Code); } }); b5 = (Button) findViewById(R.id.btn_launchMyBrowser); b5.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent i = new Intent("app.test.MyBrowser", Uri .parse("http://www.amazon.com")); i.addCategory("app.test.OtherApps"); i.addCategory("app.test.SomeOtherApps"); startActivity(i); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == request_Code) { if (resultCode == RESULT_OK) { Toast.makeText(this, data.getData().toString(), Toast.LENGTH_SHORT).show(); Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(data.getData().toString())); startActivity(i); } } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn_webbrowser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Web Browser" /> <Button android:id="@+id/btn_makecalls" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Make Calls" /> <Button android:id="@+id/btn_showMap" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Show Map" /> <Button android:id="@+id/btn_chooseContact" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose Contact" /> <Button android:id="@+id/btn_launchMyBrowser" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Launch My Browser" /> </LinearLayout> //row.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:id="@+id/WebView01" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Location based service
package app.test; import android.os.Bundle; import android.location.LocationManager; import android.view.View; import android.widget.TextView; import android.content.Context; import android.widget.Button; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.Point; import com.google.android.maps.MapController; public class Test extends MapActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final MapView myMap = (MapView) findViewById(R.id.myMap); final MapController myMapController = myMap.getController(); final Button zoomIn = (Button) findViewById(R.id.buttonZoomIn); zoomIn.setOnClickListener(new Button.OnClickListener() { public void onClick(View v){ ZoomIn(myMap,myMapController); }}); final Button zoomOut = (Button) findViewById(R.id.buttonZoomOut); zoomOut.setOnClickListener(new Button.OnClickListener() { public void onClick(View v){ ZoomOut(myMap,myMapController); }}); final Button gpsButton = (Button) findViewById(R.id.gpsButton); gpsButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v){ LoadProviders(myMap,myMapController); }}); final Button viewMap = (Button) findViewById(R.id.buttonMapView); viewMap.setOnClickListener(new Button.OnClickListener() { public void onClick(View v){ ShowMap(myMap,myMapController); }}); final Button viewSat = (Button) findViewById(R.id.buttonSatView); viewSat.setOnClickListener(new Button.OnClickListener() { public void onClick(View v){ ShowSat(myMap,myMapController); }}); } public void LoadProviders(MapView mv, MapController mc){ TextView latText = (TextView) findViewById(R.id.latText); TextView lngText = (TextView) findViewById(R.id.lngText); LocationManager myManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Double latPoint = myManager.getCurrentLocation("gps").getLatitude()*1E6; Double lngPoint = myManager.getCurrentLocation("gps").getLongitude()*1E6; latText.setText(latPoint.toString()); lngText.setText(lngPoint.toString()); Point myLocation = new Point(latPoint.intValue(),lngPoint.intValue()); mc.centerMapTo(myLocation, false); mc.zoomTo(9); mv = null; } public void ZoomIn(MapView mv, MapController mc){ if(mv.getZoomLevel()!=21){ mc.zoomTo(mv.getZoomLevel()+ 1); } } public void ZoomOut(MapView mv, MapController mc){ if(mv.getZoomLevel()!=1){ mc.zoomTo(mv.getZoomLevel()- 1); } } public void ShowMap(MapView mv, MapController mc){ if (mv.isSatellite()){ mv.toggleSatellite(); } } public void ShowSat(MapView mv, MapController mc){ if (!mv.isSatellite()){ mv.toggleSatellite(); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/gpsButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Where Am I" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/latLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Latitude: " /> <TextView android:id="@+id/latText" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/lngLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Longitude: " /> <TextView android:id="@+id/lngText" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <view class="com.google.android.maps.MapView" android:id="@+id/myMap" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/buttonZoomIn" style="?android:attr/buttonStyleSmall" android:text="+" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonMapView" style="?android:attr/buttonStyleSmall" android:text="Map" android:layout_alignRight="@+id/myMap" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonSatView" style="?android:attr/buttonStyleSmall" android:text="Sat" android:layout_alignRight="@+id/myMap" android:layout_alignBottom="@+id/myMap" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonZoomOut" style="?android:attr/buttonStyleSmall" android:text="-" android:layout_alignBottom="@+id/myMap" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> </LinearLayout>
My location and Google Map
package app.test; import android.os.Bundle; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; public class MyLocationDemoActivity extends MapActivity { MapView mapView = null; MapController mapController = null; MyLocationOverlay whereAmI = null; @Override protected boolean isLocationDisplayed() { return whereAmI.isMyLocationEnabled(); } @Override protected boolean isRouteDisplayed() { return false; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView)findViewById(R.id.geoMap); mapView.setBuiltInZoomControls(true); mapController = mapView.getController(); mapController.setZoom(15); whereAmI = new MyLocationOverlay(this, mapView); mapView.getOverlays().add(whereAmI); mapView.postInvalidate(); } @Override public void onResume() { super.onResume(); whereAmI.enableMyLocation(); whereAmI.runOnFirstFix(new Runnable() { public void run() { mapController.setCenter(whereAmI.getMyLocation()); } }); } @Override public void onPause() { super.onPause(); whereAmI.disableMyLocation(); } } <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/main.xml --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/geoMap" android:clickable="true" android:layout_width="fill_parent" android:layout_height="fill_parent" android:apiKey="yourKey" /> </RelativeLayout>
Custom Location Overlay
package app.test; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import android.os.Bundle; import android.content.Context; import android.location.Location; import android.util.Log; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; class MyCustomLocationOverlay extends MyLocationOverlay { MapView mMapView = null; public MyCustomLocationOverlay(Context ctx, MapView mapView) { super(ctx, mapView); mMapView = mapView; } public void onLocationChanged(Location loc) { super.onLocationChanged(loc); GeoPoint newPt = new GeoPoint((int) (loc.getLatitude()*1E6), (int) (loc.getLongitude()*1E6)); Log.v("MyCustomLocationOverlay", "Got new location: " + newPt); mMapView.getController().animateTo(newPt); } } public class MyLocationDemoActivity extends MapActivity { MapView mapView = null; MapController mapController = null; MyLocationOverlay whereAmI = null; @Override protected boolean isLocationDisplayed() { return whereAmI.isMyLocationEnabled(); } @Override protected boolean isRouteDisplayed() { return false; } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView)findViewById(R.id.geoMap); mapView.setBuiltInZoomControls(true); mapController = mapView.getController(); mapController.setZoom(15); whereAmI = new MyCustomLocationOverlay(this, mapView); mapView.getOverlays().add(whereAmI); mapView.postInvalidate(); } @Override public void onResume() { super.onResume(); whereAmI.enableMyLocation(); whereAmI.runOnFirstFix(new Runnable() { public void run() { mapController.setCenter(whereAmI.getMyLocation()); } }); } @Override public void onPause() { super.onPause(); whereAmI.disableMyLocation(); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/main.xml --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/geoMap" android:clickable="true" android:layout_width="fill_parent" android:layout_height="fill_parent" android:apiKey="yourMapKey" /> </RelativeLayout>
Get my location
package app.test; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); LocationManager locationManager; locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); updateWithNewLocation(location); } /** Update UI with a new location */ private void updateWithNewLocation(Location location) { TextView myLocationText = (TextView)findViewById(R.id.myLocationText); String latLongString; if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); latLongString = "Lat:" + lat + "\nLong:" + lng; } else { latLongString = "No location found"; } myLocationText.setText("Your Current Position is:\n" + latLongString); } } //layout/main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/myLocationText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
Geo location and Google Map
package app.test; import java.io.IOException; import java.util.List; import java.util.Locale; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import android.content.Context; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; public class Test extends MapActivity { MapController mapController; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); MapView myMapView = (MapView)findViewById(R.id.myMapView); mapController = myMapView.getController(); // Configure the map display options myMapView.setSatellite(true); myMapView.setStreetView(true); // Zoom in mapController.setZoom(17); LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); updateWithNewLocation(location); locationManager.requestLocationUpdates(provider, 2000, 10, locationListener); } private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } public void onProviderDisabled(String provider){ updateWithNewLocation(null); } public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; /** Update the map with a new location */ private void updateWithNewLocation(Location location) { // Update the map location. Double geoLat = location.getLatitude()*1E6; Double geoLng = location.getLongitude()*1E6; GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue()); mapController.animateTo(point); TextView myLocationText = (TextView)findViewById(R.id.myLocationText); String latLongString; String addressString = "No address found"; if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); latLongString = "Lat:" + lat + "\nLong:" + lng; Geocoder gc = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = gc.getFromLocation(lat, lng, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) sb.append(address.getAddressLine(i)).append("\n"); sb.append(address.getLocality()).append("\n"); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); } addressString = sb.toString(); } catch (IOException e) {} } else { latLongString = "No location found"; } myLocationText.setText("Your Current Position is:\n" + latLongString + "\n" + addressString); } @Override protected boolean isRouteDisplayed() { return false; } } //layout/main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/myLocationText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <com.google.android.maps.MapView android:id="@+id/myMapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:clickable="true" android:apiKey="myAPIKey" /> </LinearLayout>
Location Tracking
package app.test; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.widget.TextView; public class Test extends Activity implements LocationListener { LocationManager lm; TextView tv; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) this.findViewById(R.id.location); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000l, 5.0f, this); } public void onPause() { super.onPause(); lm.removeUpdates(this); } public void onLocationChanged(Location location) { tv.setText(location.getLatitude() + " " + location.getLongitude()); } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status, Bundle extras) { if (status == LocationProvider.AVAILABLE) { } else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) { } else if (status == LocationProvider.OUT_OF_SERVICE) { } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:id="@+id/location" /> </LinearLayout>
A light pool of objects that can be resused to avoid allocation.
import java.util.ArrayList; /** * A light pool of objects that can be resused to avoid allocation. * Based on Nathan Sweet pool implementation */ abstract class Pool<T> { private final ArrayList<T> objects; public Pool (int initCapacity) { objects = new ArrayList<T>(initCapacity); } protected abstract T getNew(); public T get() { return objects.isEmpty() ? getNew() : objects.remove(objects.size()-1); } public void free(T obj) { if (!objects.contains(obj)) objects.add(obj); } public void clear() { objects.clear(); } public int size() { return objects.size(); } }
extends android.location.Location
import android.location.Location; class CuhkLocation extends Location{ private static final double latitude = 22.419005; private static final double longitude = 114.206904; public static final double CUHK_RANGE = 1000; public static final double CUHK_CLOSE_RANGE = 5000; public static final int INSIDE = 1; public static final int CLOSE = 2; public static final int FAR = 3; private static CuhkLocation cuhkLocation = null; public static CuhkLocation getInstance(){ if(cuhkLocation==null) cuhkLocation = new CuhkLocation(); return cuhkLocation; } private CuhkLocation() { super("CUBT"); this.setLatitude(latitude); this.setLongitude(longitude); } public int getDistanceDescriptionTo(Location location){ double distance = this.distanceTo(location); if(distance < CUHK_RANGE) return INSIDE; if(distance < CUHK_CLOSE_RANGE) return CLOSE; else return FAR; } }
LocationUtil.java
package com.hci.pwf; import java.util.List; import java.util.Locale; import android.content.Context; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import com.google.android.maps.GeoPoint; public class LocationUtil { public static String getBestProvider(LocationManager lm) { Criteria mCriteria = new Criteria(); mCriteria.setAccuracy(Criteria.ACCURACY_FINE); mCriteria.setAltitudeRequired(false); mCriteria.setBearingRequired(false); mCriteria.setCostAllowed(true); mCriteria.setPowerRequirement(Criteria.POWER_LOW); String strLocationProvider = lm.getBestProvider(mCriteria, true); return strLocationProvider; } public static Location getLocationProvider(LocationManager lm) { Location location = lm.getLastKnownLocation(LocationUtil.getBestProvider(lm)); return location; } public static GeoPoint getGeoByLocation(Location location) { GeoPoint gp = null; try { if (location != null) { double geoLatitude = location.getLatitude() * 1E6; double geoLongitude = location.getLongitude() * 1E6; gp = new GeoPoint((int) geoLatitude, (int) geoLongitude); } } catch (Exception e) { e.printStackTrace(); } return gp; } public static Address getAddressbyGeoPoint(Context cntext, GeoPoint gp) { Address result = null; try { if (gp != null) { Geocoder gc = new Geocoder(cntext, Locale.getDefault()); double geoLatitude = (int) gp.getLatitudeE6() / 1E6; double geoLongitude = (int) gp.getLongitudeE6() / 1E6; List<Address> lstAddress = gc.getFromLocation(geoLatitude, geoLongitude, 1); if (lstAddress.size() > 0) { result = lstAddress.get(0); } } } catch (Exception e) { e.printStackTrace(); } return result; } }
upload Data with Geo location
//package usar.mobile; import android.location.Location; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; class DataTransferUtil { public static void uploadData(Location location) { String url = "http://urbansearchrescue.appspot.com/upload"; HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); try { if (location == null) { return; } double longitude = location.getLongitude(); double latitude = location.getLatitude(); //ResponseHandler <String> res = new BasicResponseHandler(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("x_coord", Double.toString(longitude))); nameValuePairs.add(new BasicNameValuePair("y_coord", Double.toString(latitude))); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.v("DataTransferUtil", "executing request " + httpPost.getRequestLine()); HttpResponse response = httpclient.execute(httpPost); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Copy a file from one location to another.
//package bander.fileman.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; /** Utility class containing File-related helper functions. */ public class FileUtils { public static Boolean copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } return true; } return false; } public static String readTextFile(File file) throws IOException { byte[] buffer = new byte[(int) file.length()]; BufferedInputStream stream = new BufferedInputStream( new FileInputStream(file)); stream.read(buffer); stream.close(); return new String(buffer); } }
LocationManager.GPS_PROVIDER
import android.content.Context; import android.location.LocationManager; class GpsUtil { public static boolean checkStatus(Context context){ LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } }
Location util
//package com.android.gnview.utils; import java.util.ArrayList; import java.util.List; import android.graphics.Point; import android.location.Location; import android.location.LocationManager; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; public class LocUtils { public static String distanceBeetwin(Location a, Location b) { double dist = a.distanceTo(b); String unit; if (dist > 1000) { unit = " km"; dist /= 1000; dist = ((int) (dist*100)) / 100.0; } else { unit = " m"; dist = ((int) (dist*100)) / 100; } return (dist + unit); } public static String getBestLocationProvider(LocationManager lManager) { List <String> providers = lManager.getProviders(true); String choixSource = null; if (providers.isEmpty()){ return null; }else if(providers.size()==1){ return providers.get(0); }else{ int i = Integer.MAX_VALUE; for(String provider : providers) { if (lManager.getProvider(provider).getAccuracy()<i && lManager.getProvider(provider).getAccuracy() > 0 ) { choixSource = provider; i = lManager.getProvider(provider).getAccuracy(); } } } return choixSource; } public static GeoPoint toGeoPoint(Location location) { return new GeoPoint( (int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6) ); } public static Location toLocation(GeoPoint myLocation) { Location loc = new Location(""); loc.setLatitude(myLocation.getLatitudeE6()/1E6); loc.setLongitude(myLocation.getLongitudeE6()/1E6); return loc; } public static ArrayList<Location> DouglasPeucker(Projection projection, ArrayList<Location> line, double d) { ArrayList<Point> listPoints = GeoUtils.DouglasPeucker(toPoints(projection,line),d); return toLineOfInterest(projection, listPoints); } private static ArrayList<Location> toLineOfInterest(Projection projection, ArrayList<Point> listPoints) { ArrayList<Location> retLine = new ArrayList<Location>(); for (Point p:listPoints) { retLine.add( toLocation(projection.fromPixels(p.x, p.y)) ); } return retLine; } private static List<Point> toPoints(Projection projection, ArrayList<Location> line) { ArrayList<Point> retPoints = new ArrayList<Point>(); Point prev = new Point(); for (Location l:line) { Point p = new Point(); projection.toPixels(toGeoPoint(l), p); if (!p.equals(prev.x, prev.y)) { retPoints.add(p); } prev = p; } return retPoints; } public static boolean isGPSEnabled(LocationManager lManager) { List<String> EnablesProviders = lManager.getProviders(true); for (String provider:EnablesProviders) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) return true; } return false; } }