How can i make this app run in the background? I can't implement Service class because i already using MapActivity. What should i do?
public class GoogleMaps extends MapActivity implements LocationListener {
LocationManager locationManager;
MapView map;
long start;
long stop;
MyLocationOverlay myLocation;
MapController controller;
List<Overlay> overlayList;
int x, y;
GeoPoint touchedPoint;
Drawable d;
String towers;
int lat;
int longi;
double midllat;
double midlongi;
NotificationManager nm;
static final int uniqueID = 1394885;
// Location location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.googlemaps);
map = (MapView) findViewById(R.id.mvGoogleMaps);
ourLocation();
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
d = getResources().getDrawable(R.drawable.round_pointer);
controller.setZoom(18);
Criteria crit = new Criteria();
towers = locationManager.getBestProvider(crit, false);
Location location = locationManager.getLastKnownLocation(towers);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(uniqueID);
}
public void ourLocation()
{
// Pin der blinker på lokation
myLocation = new MyLocationOverlay(this, map);
map.getOverlays().add(myLocation);
myLocation.enableMyLocation();
// Fin nuværende lokation
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
20000, 0, this);
controller = map.getController();
}
There is more code here, but nothing relevant to this case. Just a feature that lets me pin a point.
#Override
protected void onPause() {
// TODO Auto-generated method stub
myLocation.disableCompass();
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
myLocation.enableCompass();
super.onResume();
locationManager.requestLocationUpdates(towers, 500, 1, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location1) {
// TODO Auto-generated method stub
// Updating location and zoom
controller.setCenter(new GeoPoint(
(int) (location1.getLatitude() * 1000000), (int) (location1
.getLongitude() * 1000000)));
controller.setZoom(18);
// Trying to get MyPostion.
Location myLocation = new Location("point A");
myLocation.setLongitude(location1.getLongitude());
myLocation.setLatitude(location1.getLatitude());
Location locationB = new Location("point B");
locationB.setLatitude(midllat);
locationB.setLongitude(midlongi);
float distance = myLocation.distanceTo(locationB);
if (distance < 100) {
String hej = formatDist(distance);
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Intent intent = new Intent(this, GoogleMaps.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
String body = "You are now in the silentzone";
String title = "IRemember";
Notification n = new Notification(R.drawable.round_pointer, body,
System.currentTimeMillis());
n.setLatestEventInfo(this, title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(uniqueID, n);
}
}
public String formatDist(float meters) {
if (meters < 1000) {
return ((int) meters) + "m";
} else
return formatDec(meters / 1000f, 1) + "km";
}
public String formatDec(float val, int dec) {
int factor = (int) Math.pow(10, dec);
int front = (int) (val);
int back = (int) Math.abs(val * (factor)) % factor;
return front + "." + back;
}
}
Related
I have a StringBuilder variable from which I want to get the final value and pass it to the another activity. And I want to display the final string value in edit text view.
I have tried to get the value using toString() method but I am unable to see the value in text view its blank.
String value=str.toString();
intent.putExtra("value",value);
startActivity(intent);
By this I have got the value and sending to 2nd activity.
Intent intent = this.getIntent();
String data = intent.getStringExtra("keyName");
edtxt_from.setText(data);
Using this I am getting the value in 2nd activity.
Whats going wrong??
Please help...
I am not getting the updated address in edit text view..
ChooseFromMapActivity
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
String value=str.toString();
intent.putExtra("value",value);
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSend
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
Location l=new Location();
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
//Bundle bundle = getIntent().getParcelableExtra("bundle");
// double fromPosition = bundle.getParcelable("from_position");
// edtxt_from.setText(fromPosition);
/* Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("Longitude");
edtxt_from.setText(String.valueOf(latitude));*/
Intent intent = this.getIntent();
String data = intent.getStringExtra("value");
edtxt_from.setText(data);
// Bundle bundle = intent.getExtras();
// Serializable value =bundle.getSerializable("value");
// edtxt_from.setText(String.valueOf(longitude));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Change
String data = intent.getStringExtra("keyName");
to
String data = intent.getStringExtra("value");
You were using the wrong key.
simply do :
Replace keyName by value
I have a problem with Location variable in my Android app. On this screen GPSLocation works fine, but when I change screen to gpsLocation.getLastKnownLocation() this method always returns null.
First Screen:
public class MainActivity extends ActionBarActivity {
private TextView text;
private GPSLocation gpsLocation;
private Location targetLocation;
private EditText editLatitude;
private EditText editLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.textView);
gpsLocation = new GPSLocation(this);
editLatitude = (EditText)findViewById(R.id.editDlugosc);
editLongitude = (EditText)findViewById(R.id.editSzerokosc);
targetLocation = new Location("Bosch");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void click_rozpocznij(View view) {
targetLocation=gpsLocation.getLastKnownLocation();
text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_end(View view)
{
gpsLocation.stopUsingGPS();
text.setText("Your location:");
}
public void click_pointer(View view) {
if(targetLocation !=null) {
Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
nextScreen.putExtra("location", targetLocation);
startActivity(nextScreen);
}
else
{
targetLocation.setLongitude(0);
targetLocation.setLatitude(0);
Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
nextScreen.putExtra("location", targetLocation);
startActivity(nextScreen);
}
}
public void click_show(View view) {
gpsLocation.getLastKnownLocation();
text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_SaveTarget(View view) {
if(targetLocation !=null)
{
try{
targetLocation.setLatitude(Double.parseDouble(editLatitude.getText().toString()));
targetLocation.setLongitude(Double.parseDouble(editLongitude.getText().toString()));
}
catch(Exception e)
{
targetLocation.setLatitude(0);
targetLocation.setLongitude(0);
editLatitude.setText("0");
editLongitude.setText("0");
}
}
}
Second Screen:
public class Pointer extends ActionBarActivity implements SensorEventListener{
private Location cel;
private TextView textLocation;
private TextView textDistance;
private TextView textAngle;
private TextView textAccuracy;
private ImageView obrazek;
private SensorManager sensorManager;
private float[] lastCompass= new float[3];
private float[] lastAccelero = new float[3];
private float[] orientation = new float[3];
private boolean lastCompassSet = false;
private boolean lastAcceleroSet = false;
private float[] rotation = new float[9];
private float degree = 0f;
private Sensor compass;
private Sensor accelerometer;
private GPSLocation gpsLocation;
private Location locationFirst;
private Location locationNow;
private GeomagneticField magneticField;
private float azimuthDegress;
private float azimuthCel;
private Long timeStart;
private Long timeEnd;
private void sprawdzPolozenie()
{
if (gpsLocation.location.distanceTo(locationFirst) > 10000)
{
magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
locationFirst = gpsLocation.getLastKnownLocation();
}
SensorManager.getRotationMatrix(rotation,null,lastAccelero,lastCompass);
SensorManager.getOrientation(rotation,orientation);
float azimuthRadians = orientation[0];
azimuthDegress = (float)(Math.toDegrees(azimuthRadians));
azimuthDegress += magneticField.getDeclination();
azimuthCel= locationNow.bearingTo(cel);
azimuthDegress=azimuthDegress-azimuthCel;
RotateAnimation ra = new RotateAnimation(degree,-azimuthDegress, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
ra.setDuration(400);
ra.setFillAfter(true);
obrazek.startAnimation(ra);
degree=-azimuthDegress;
}
#Override
public void onSensorChanged(SensorEvent event) {
locationNow=gpsLocation.getLastKnownLocation();
if(locationNow!=null) {
if (event.sensor == compass) {
/*event.values[0]=lastCompass[0];
event.values[1]=lastCompass[1];
event.values[2]=lastCompass[2];*/
System.arraycopy(event.values, 0, lastCompass, 0, event.values.length);
lastCompassSet = true;
} else if (event.sensor == accelerometer) {
/*event.values[0]=lastAccelero[0];
event.values[1]=lastAccelero[1];
event.values[2]=lastAccelero[2];*/
System.arraycopy(event.values, 0, lastAccelero, 0, event.values.length);
lastAcceleroSet = true;
}
if (lastCompassSet) {
timeStart = System.currentTimeMillis();
if (timeStart > timeEnd + 500) {
sprawdzPolozenie();
timeEnd = timeStart;
}
}
textDistance.setText("Distanse: " + locationNow.distanceTo(cel));
textAccuracy.setText("Accuracy: " + locationNow.getAccuracy());
textAngle.setText("Angle: " + azimuthDegress);
}
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(this, compass, SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause(){
super.onPause();
sensorManager.unregisterListener(this,accelerometer);
sensorManager.unregisterListener(this,compass);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gpsLocation = new GPSLocation(this);
locationFirst = new Location("Bosch");
locationNow = new Location("Bosch");
cel = new Location("Bosch");
locationNow=gpsLocation.getLastKnownLocation();
locationFirst= gpsLocation.getLastKnownLocation();
setContentView(R.layout.activity_wskaznik);
timeEnd =System.currentTimeMillis();
sensorManager = (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
compass = sensorManager.getDefaultSensor(TYPE_MAGNETIC_FIELD);
accelerometer = sensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
obrazek =(ImageView)findViewById(R.id.wskaznik_imageView);
textLocation = (TextView)findViewById(R.id.wskaznikTekstCel);
textDistance = (TextView)findViewById(R.id.wskaznikTekstOdleglosc);
textAngle = (TextView)findViewById(R.id.wskaznikTekstKat);
textAccuracy =(TextView)findViewById(R.id.wskaznikTekstDokladnosc);
Bundle extras = getIntent().getExtras();
magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
if(extras!=null)
{
cel = (Location)extras.get("location");
}
textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void click_wroc(View view) {
finish();
}
GPSLocation itself:
public class GPSLocation extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
//czas i dystans pomiedzy pomiarami
private static final long MIN_DISTANCE = 10;
private static final long MIN_TIME = 1000 * 60 * 1;
double latitude;
double longitude;
double altitude;
public Location location;
protected LocationManager locationManager;
public GPSLocation(Context context)
{
this.mContext = context;
getLocation();
}
public void requestLocation() {
//network
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
altitude = location.getAltitude();
}
}
//gps
if(isGPSEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude = location.getAltitude();
}
}
}
public Location getLastKnownLocation()
{
try
{
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
this.canGetLocation=false;
this.showSettingsAlert();
}
else
{
requestLocation();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
public Location getLocation()
{
try
{
locationManager=(LocationManager)mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
this.canGetLocation=false;
this.showSettingsAlert();
}
else
{
this.canGetLocation=true;
requestLocation();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
public double getLatitude()
{
if(location!=null)
{
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
latitude = location.getLatitude();
}
return longitude;
}
public double getAltitude(){
if(location!=null)
{
latitude=location.getAltitude();
}
return altitude;
}
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Przejdź do ustawień");
alertDialog.setMessage("Lokalizacja wyłączona");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS()
{
if(locationManager!=null)
{
locationManager.removeUpdates(GPSLocation.this);
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
I ran your Pointer Activity code in isolation, and it worked fine for me.
It looks like your main issue is how you're passing the Location through the Intent to the Pointer Activity from MainActivity.
Location implements Parcelable, so you can pass it though the Intent as you are already doing, and retrieve it like this:
if(extras!=null)
{
//cel = (Location)extras.get("location"); //this is not correct
cel = (Location) extras.getParcelable("location");
}
if (cel != null){
textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}
Documentation: http://developer.android.com/reference/android/os/Bundle.html#getParcelable(java.lang.String)
http://developer.android.com/reference/android/location/Location.html
Sory for everyone who wanted help me for problem. I solved this by myself.
Problem was in GPSLocation class. I had to add new constructor at start and change way of getting location from locationManager
public GPSLocation(Context context)
{
this.mContext = context;
location = new Location("Bosch");
getLocation();
}
When I use this code location stay nullpointer.
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
But creating copy of location from locationManager solved problem.
location = new Location(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
Maybe locationManager is creating data of location only not Location itself and that was causing creating nullpointer.
Map showing starting point.
why call marker from database not show.
I'm don't understand.
Or write code the show from database error?
this code Map.java
public class Map extends FragmentActivity implements LocationListener {
SQLiteDatabase SQL;
GoogleMap map;
myDBClass DB;
Cursor cursor;
ArrayList<LatLng> MarkerPoint = new ArrayList<LatLng>();
double latitude = 0;
double longtitude = 0;
GMapV2Direction md = new GMapV2Direction();
Document document;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show_map);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
//map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Destination Marker from Database SQLite
if (MarkerPoint.size() > 1) {
String Name = getIntent().getStringExtra("Name");
DB = new myDBClass(this);
SQL = DB.getWritableDatabase();
cursor = SQL.rawQuery("SELECT *" + " FROM "
+ myDBClass.TABLE_NAME + " WHERE " + myDBClass.NAME
+ " ='" + Name + "'", null);
cursor.moveToFirst();
/**String name = cursor.getString(cursor.getColumnIndex(myDBClass.NAME));
double lat_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
double lng_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
map.addMarker(new MarkerOptions()
.position(new LatLng(lat_db, lng_db)) .title(name));**/
latitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
longtitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
cursor.moveToNext();
//MarkerPoint.clear();
//map.clear();
LatLng strpoint = new LatLng(latitude, longtitude);
drawMarker(strpoint);
}
}
DrawRouteTask drawroute = new DrawRouteTask();
drawroute.execute();
}
private class DrawRouteTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response = "";
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(Map.this);
Dialog.setMessage("Loading");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
// Get All Route values
if (MarkerPoint.size() >= 2) {
LatLng Start = MarkerPoint.get(0);
LatLng End = MarkerPoint.get(1);
document = md.getDocument(Start, End,GMapV2Direction.MODE_DRIVING);
response = "Success";
}
return response;
}
#Override
protected void onPostExecute(String result) {
try {
if (response.equalsIgnoreCase("Success")) {
ArrayList<LatLng> directionPoint = md.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
}
} catch (Exception e) {
// TODO:ERROR TRACE ROUTE
}
Dialog.dismiss();
}
}
private void drawMarker(LatLng point) {
MarkerPoint.add(point);
MarkerOptions options = new MarkerOptions();
options.position(point);
if (MarkerPoint.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoint.size() == 2) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
map.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (MarkerPoint.size() < 2) {
latitude = location.getLatitude();
longtitude = location.getLongitude();
LatLng point = new LatLng(latitude, longtitude);
map.moveCamera(CameraUpdateFactory.newLatLng(point));
map.animateCamera(CameraUpdateFactory.zoomTo(6));
drawMarker(point);
}
}
#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
}
http://i.stack.imgur.com/SXq5P.jpg
Map showing starting point.
why call marker from database not show.
I'm don't understand.
Or write code the show from database error?
I am developing an android application that contains 3 activities and one of them is map. I am using google maps
what I want:
When the user opens the activity (map) it shows the user her location not the coordinate.
The user should also be able to posit(pining) any place by using a pin and my app must store the coordinates for this pin in a variable so i can use it later.
public class LActivity extends MapActivity
{
/** Called when the activity is first created. */
MapView mapView;
GeoPoint geo;
MapController mapController;
LocationManager locationManager;
CustomPinpoint itemizedoverlay;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
// create a map view
//LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);
mapView.setBuiltInZoomControls(true);
// Either satellite or 2d
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
this is CustomPinpoint class
public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {
static int maxNum = 3;
OverlayItem overlays[] = new OverlayItem[maxNum];
int index = 0;
boolean full = false;
CustomPinpoint itemizedoverlay;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return overlays[i];
}
#Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}
}
public void addOverlay(OverlayItem overlay) {
if (index < maxNum) {
overlays[index] = overlay;
} else {
index = 0;
full = true;
overlays[index] = overlay;
}
index++;
populate();
}
}
I have implemented the same thing you want. I am providing you the sample code. In this I have also implemented the ProgressDialog when fetching the location.
This is the starting point for getting the location. I named this AndroidLocationActivity. This is the 1st activity which starts when your app starts.
String provider;
public double latitude, longitude = 0;
CurrentPositionTask getCurrentLocation;
Location currentLocation;
LocationListener locationListener;
LocationManager locationManager;
private long time=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setCriteria();
currentLocation = AndroidLocationActivity.this.locationManager.getLastKnownLocation(provider);
if (currentLocation == null) {
currentLocation = new Location(provider);
}
time = currentLocation.getTime();
if (latitude == 0 && longitude == 0) {
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
Toast.makeText(AndroidLocationActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();
Here set the time if time is not more than 1minute than i am not updating the location.
if (time >= 100000) {
latitude = 0;
longitude = 0;
}
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null");
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
runAsyncTask();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
locationManager.removeUpdates(locationListener);
}
public void setCriteria() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
provider = locationManager.getBestProvider(criteria, true);
Toast.makeText(getApplicationContext(), "Provider - " + provider, Toast.LENGTH_SHORT).show();
if (provider == null) {
provider = LocationManager.GPS_PROVIDER;
}
}
public void runAsyncTask() {
// TODO Auto-generated method stub
if (getCurrentLocation == null) {
getCurrentLocation = new CurrentPositionTask();
}
if (getCurrentLocation != null) {
getCurrentLocation.execute("Searching for Location");
}
}
public boolean checkConnection()
{
//ARE WE CONNECTED TO THE NET
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (AndroidLocationActivity.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
private class CurrentPositionTask extends AsyncTask<String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(AndroidLocationActivity.this);
private boolean flag = true;
public CurrentPositionTask() {
locationListener = new MyLocationListener();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
try {
if (checkConnection()) {
Dialog.setTitle("Loading");
Dialog.setMessage("Searching for Location");
Dialog.show();
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}
else {
Toast.makeText(getApplicationContext(), "Internet is Not Available", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
while (flag) {
if (latitude !=0 && longitude != 0) {
flag=false;
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidLocationActivity.this, "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
if (Dialog != null && Dialog.isShowing()) {
Dialog.dismiss();
time=0;
Intent homeIntent = new Intent(AndroidLocationActivity.this.getApplicationContext(), HomeMenuActivity.class);
set the lat & lng here and start new activity
homeIntent.putExtra("lat", latitude);
homeIntent.putExtra("lng", longitude);
startActivity(homeIntent);
}
locationManager.removeUpdates(locationListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
This is the function in which i am displaying the Map. This is the HomeMenuActivity
public static Context context;
onCreate(..) {
context = getApplicationContext(); // it will be used in Itemized Overlay
latitude = getIntent().getDoubleExtra("lat", 0);//get the lat & lng
longitude = getIntent().getDoubleExtra("lng", 0);
}
public void showMap() {
// TODO Auto-generated method stub
try {
geoPoint = new GeoPoint((int)(latitude * 1E6),(int)(longitude * 1E6));
mapview = (MapView)findViewById(R.id.mapview);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapview.setTraffic(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(your pic....);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ItemizedOverlay Class
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
Toast.makeText(HomeMenuActivity.context, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
Hope this will help.....
Remove your method onCreate and add this code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
initMap(); // This is the method which initialize the map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
#Override
public void onResume()
{
super.onResume();
try
{
initMyLocation();
}catch(Exception e){}
}
/**
* Inits the map.
*/
protected void initMap()
{
mapView = (MyMapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapView.setStreetView(false);
mapController = mapView.getController();
mapOverlay = new MapOverlay();
List<Overlay> overlays = mapView.getOverlays();
overlays.add(mapOverlay);
mapController.setZoom(14);
mapView.invalidate();
}
/**
* Initialises the MyLocationOverlay and adds it to the overlays of the map.
*/
public void initMyLocation() {
try
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location l = LocationService.getLastKnownLocation(lm);
int lat = (int)(l.getLatitude()*1E6);
int lng = (int)(l.getLongitude()*1E6);
mapController.setCenter(new GeoPoint(lat , lng));
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(myLocOverlay);
mapController.setCenter(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
findMe();
}
/**
* This method will animate to my current position
*/
public void findMe()
{
try
{
mapController.animateTo(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
}
Then to store the Overlays for future use you can either use SharedPreferences or SQLite. There are loads of tutorials for each of them.
I try to send a Toast Message from a Thread to the UIThread when clicking a button.
However, every time I click the button the Toast does not appear.
I am using a Handler to do this.
This is the full code, in case I made a major mistake somewhere:
package google.map.activity;
//imports
public class GoogleMapActivity extends MapActivity {
int lat = 0;
int lng = 0;
Location location;
MapController mc;
GeoPoint p;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.googlemapactivity);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(false);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(19);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5,
0, new GeoUpdateHandler());
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5, 0, new GeoUpdateHandler());
// //////---Switch to
// Start/////////////////////////////////////////////////////////////////////////////
Button switchToMain = (Button) findViewById(R.id.switchtomain);
switchToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// ////--Call a
// Cab/////////////////////////////////////////////////////////////////////////////////////
Button getCab = (Button) findViewById(R.id.GetCab); // create the Button
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
getCab.setOnClickListener(new View.OnClickListener() {
String bestProvider = locationManager.getBestProvider(criteria,
true);
Location locationTest = locationManager
.getLastKnownLocation(bestProvider); // get
// last
// known
// location fix from
// locationManager
public void getAddress() {
String msg = null;
Looper.prepare();
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager
.getLastKnownLocation(bestProvider);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale
.getDefault());// create
// new
// GeoCoder
String result = null; // initialize result
try { // try to get Address list from location of bestProvider
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", "
+ address.getLocality();// set result
// to
// Streetname+Nr.
// and City
}
} catch (IOException e) {
msg = String.format("IOException!!");
} finally {
if (result != null) {
msg = String.format(result);
// Looper.loop();
} else
msg = String.format("Keine Position");
}
Message myMessage = new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", msg);
myMessage.obj = resBundle;
handler.sendMessage(myMessage);
}
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Looper.myLooper();
// Looper.prepare();
getAddress(); // get the Address
Location locationTest = locationManager
.getLastKnownLocation(bestProvider);
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location2 = locationManager
.getLastKnownLocation(bestProvider);
int lat = (int) (location2.getLatitude() * 1E6); // get
// position
// for GeoPoint
int lng = (int) (location2.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng); // create
// GeoPoint
// for
// mapController
mapController.animateTo(point);
}
}).start();
// toast.show();
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), msg.toString(),
Toast.LENGTH_LONG);
}
};
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Thank you in advance!
Edit: Solved it by using this:
Handler toastHandler = new Handler();
Runnable toastRunnable = new Runnable() {public void run() {Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();}};
In the UIThread and this:
toastHandler.post(toastRunnable);
in the background thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
// Here you can make a Toast
}
});
Your toast needs to be done in the UI thread. Here's how to do that:
Note: ClassName.this is needed because this by itself will refer to your anonymous Runnable class.
runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(ClassName.this, R.string.something, Toast.LENGTH_LONG).show();
}
});