sendTextMessage is not applicable - android

I'm trying to build an app that send gps location with sms,and i got stuck in this error:
The method sendTextMessage(String, String, String, PendingIntent, PendingIntent) in the type SmsManager is not applicable for the arguments (EditText, null, String, null, null)
package com.example.thermolocation;import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
EditText txtphoneNo;
String Text;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
Text = "My location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
txtphoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
sendSMSMessage();
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
try {
android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
smsManager.sendTextMessage(txtphoneNo, null, Text, null, null); /* <--here i got the error */
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"GPS Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"GPS Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
Can i get some help please
Thank you

Check your Error :
The method sendTextMessage(String, String, String, PendingIntent, PendingIntent) in the type SmsManager is not applicable for the arguments (EditText, null, String, null, null)
The first argument doesn't match, you are passing an EditText instead of a String.
I suggest you change as following:
smsManager.sendTextMessage(txtphoneNo.getText().toString(), null, Text, null, null);

The error is quite clear:
The method is:
sendTextMessage(String, String, String, PendingIntent, PendingIntent)
but you call it with the arguments (EditText, null, String, null, null)
Notice how the first argument is a EditText and not a String (which it wants)
You should use txtphoneNo.getText().toString()

EditText is not a string. Change your call to this:
smsManager.sendTextMessage(txtphoneNo.getText().toString(), null, Text, null, null);

Related

GetApplicationConext() error

So today I started reading on tutorials on how to get my current GPS location using Android studio. but I came up with an error " Error:(21, 24) error: cannot find symbol method getApplicationContext() " I have looked around stuckoverflow but none of the solutions worked for me. here is the code
package com.example.chara.usegps;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.Toast;
/**
* Created by charalambous on 11/9/2015.
*/
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
String Text = "My Current Location is: " + " Latitude = " + location.getLatitude() + "longitude = " + location.getLongitude();
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
}
This is because your class is not extended from ActivityClass. you must add a Context object to your Costructor method and use it as context.

Method onLocationChanged() is not getting a different location

package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
double latitude;
double longitude;
private LocationManager lm;
ArrayList<Point> pt;
Point p;
private Context context;
private Location loc;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(){
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
loc = location;
Toast.makeText(getApplicationContext(), "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude(), Toast.LENGTH_LONG).show();
updateList();
}
#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
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
this.loc = null;
pt = new ArrayList<Point>();
p = new Point();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
So, in this code, my intention is to save a list of Points in an ArrayList of Points that will be use later. But all the points (latitude and longitude) have the same value, once i have the first value, all the others values are the same, its seems like onLocationChanged is never called.
Can someone help me?
You have a global point p that you're overwriting every call to updateList. Since you aren't creating a new point ever, this overwrites the old values. That means every element in your list will always have the most recent values, rather than the value at that time.
Also, why are you using class variables everywhere rather than passing parameters to functions? I have a feeling you don't understand Java or references very well.
Edit:
Here's what your code should look like, with locals used correctly:
package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
private LocationManager lm;
ArrayList<Point> pt;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(Location loc){
Point p = new Point();
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Lat: " + location.getLatitude() + "Long: " + location.getLongitude(), Toast.LENGTH_LONG).show();
updateList(location);
}
#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
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
pt = new ArrayList<Point>();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

onLocationChanged() is not getting executed in my service

i'm trying to automatically update my location and have some other part of cloud related code working when location is changed. here is the code of my service:
package com.salesforce.samples.templateapp;
import java.util.HashMap;
import org.json.JSONArray;
import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MyServices extends Service {
RestClient client;
double plat;
double plong;
int Two_Min=2*60*1000;
// TextView infoText;
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Location Updation has started", Toast.LENGTH_LONG)
.show();
Log.v("X","Response:in onStartCommand()");
//Intent in = new Intent().setClass(MyServices.this, GPSUpdate.class);
//in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(in);
detectLocation();
return START_STICKY;
}
private void detectLocation() {
// TODO Auto-generated method stub
Toast.makeText(this, "Inside detectlocation()", Toast.LENGTH_SHORT)
.show();
LocationManager lm1 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll1 = new MyLocationListetner();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String best = lm1.getBestProvider(crit, false);
// lm1.requestLocationUpdates(best, 0, 1, ll1);
Log.v("X",
"Response:After creating lm and ll ");
// boolean b1=lm1.addGpsStatusListener((Listener) ll1);
//Log.v("X",
// "Response: "+b1);
lm1.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll1);
Log.v("X",
"Response:After lm1.requestLocationUpdates ");
/*Location loc = null;
loc.getLatitude();
loc.getLongitude();
Log.v("X","Response:"+loc);
ll1.onLocationChanged(loc);*/
}
class MyLocationListetner implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d("X","Response:inside onLocationChanged ");
Toast.makeText(getApplicationContext(), "inside onLocationChanged()", Toast.LENGTH_LONG).show();
//Log.v("X","Response:"+location);
if (location != null) {
plat = location.getLatitude();
plong = location.getLongitude();
Log.d("X",
"Response:Location " + Double.toString(plat)+Double.toString(plong));
String objectType = "akshayg__User__c";
String objectId = "a02900000089fK3";
HashMap<String, Object> fields = new HashMap<String, Object>();
fields.put("Name", "Ashish");
// fields.put("akshayg__Donor_Location__Latitude__s",
// Double.toString(plat));
// fields.put("akshayg__Donor_Location__Longitude__s",
// Double.toString(plong));
RestRequest request = null;
try {
request = RestRequest.getRequestForUpdate(
getString(R.string.api_version), objectType,
objectId, fields);
// Toast.makeText(this, "Location Updation has started",
// Toast.LENGTH_LONG).show();
} catch (Exception e) {
// printHeader("Could not build update request");
printException(e);
return;
}
client.sendAsync(request, new AsyncRequestCallback() {
#Override
public void onSuccess(RestRequest request,
RestResponse result) {
// Toast.makeText(this,
// ""+Double.toString(plat)+","+Double.toString(plong),
// Toast.LENGTH_LONG).show();
try {
//Toast.makeText(this, "Location Updated",Toast.LENGTH_LONG).show();
Log.v("X",
"Response:inside onSuccess() " + result.toString());
/*JSONArray records = result.asJSONObject()
.getJSONArray("records");
for (int i = 0; i < records.length(); i++) {
// listAdapter.add(records.getJSONObject(i).getString("Name"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Phone_Number__c"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Latitude__s"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Longitude__s"));
}
*/
}
catch (Exception e) {
onError(e);
}
}
#Override
public void onError(Exception exception) {
Log.v("X",
"Response: " + exception.toString());
// Toast.makeText(MainActivity.this,
// MainActivity.this.getString(ForceApp.APP.getSalesforceR().stringGenericError(),
// exception.toString()),
// Toast.LENGTH_LONG).show();
}
});
}
}
private void printException(Exception e) {
String err = "Error: " + e.getClass().getSimpleName();
Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG)
.show();
}
#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
}
}
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Location Updation has stoped", Toast.LENGTH_LONG)
.show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
the toasts till "inside detectLocation" are popped up and log entries made till
04-04 00:42:34.687: V/X(10217): Response:After lm1.requestLocationUpdates
but beyond that the code is just unreachable...
even the GPS sign is shown in action bar but the toast for displaying location is not popped... pls help....!!!
In requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, Two_Min, ll1) you're passing Two_Min (which you've set to 5*60*1000 = 300000) into the minDistance paramter which should be a number of metres. Try setting minDistance to 0 instead.

Can't compare database latitude and longitude with current location

So I am trying to get current latitude and longitude and comparing it with the data I stored in my database using cursor...but when I am trying to run this app on my cell then its getting force close after some time..don't know why what the reason is....
Here's the code for getting current location and comparing it with database
package com.example.alert;
import java.util.ArrayList;
import java.util.List;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service{
LocationManager lm;
DatabaseHelper db=new DatabaseHelper(this);
List<String> arlist=new ArrayList<String>();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll=new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
// Intent myIntent=new Intent(service.this,CurrentLocation.class);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
SQLiteDatabase y = db.getWritableDatabase();
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
// String t=loc.getLatitude().toString();
Cursor cr=null;
cr=y.rawQuery("SELECT LATITUDE FROM"+ "data",null);
cr.moveToFirst();
while(cr.moveToNext()) {
arlist.add(cr.getString(cr.getColumnIndex("Latitude")));
}
for(int i=0;i<arlist.size();i++){
if(arlist.get(i)==Double.toString(loc.getLatitude())){
Intent myIntent=new Intent(service.this,SilVib.class);
startActivity(myIntent);
}
}
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled - #From :Alert Me",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled - #From :Alert Me",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
/* public double calcDistance(double latA, double longA, double latB, double longB) {
double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}
*/
}

setTestProviderLocation does not trigger onLocationChanged in the service test case

I have small service implementing LocationListener. I tested it manually with my application and it works properly.
I wrote also a test case for the service.
I used setTestProviderLocation expecting that service will receive location update.
However, it does not happen.
Does anybody know what's a problem? I'd like to emphasize that the same service works in real application.
Test case is added below
package com.gkatz.android.mtg.test;
import java.util.List;
import com.gkatz.android.mtg.LocationService;
import com.gkatz.android.mtg.LocationService.LocationBinder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
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.os.IBinder;
import android.os.SystemClock;
import android.test.ServiceTestCase;
public class LocationServiceTest extends ServiceTestCase<LocationService> implements LocationListener{
public LocationServiceTest() {
super(LocationService.class);
// TODO Auto-generated constructor stub
}
#Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
}
public void testBinding(){
IBinder locationBinder;
locationBinder = getServiceBinder();
assertNotNull(locationBinder);
}
public void testStart(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
startService(locationIntent);
}
public void testNoStart(){
LocationService locationService = getService();
assertNull(locationService);
}
public void testLocationUpdate() throws InterruptedException{
LocationBinder locationBinder;
LocationService locationService;
Context context = getContext();
LocationManager lm = getLocationManager();
context.registerReceiver(locationReceiver,
new IntentFilter("android.mtg.custom.intent.action.GPS_LOCATION"));
locationBinder = (LocationBinder)getServiceBinder();
assertNotNull(locationBinder);
locationService = getService();
assertNotNull(locationService);
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLongitude(4.890935);
loc.setLatitude(52.373801);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
SystemClock.sleep(3000);
loc.setLongitude(35.2276757);
loc.setLatitude(31.7765488);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
synchronized (this) {
this.wait(2000);
}
Location lastLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Last known longitude: " + Double.toString(lastLoc.getLongitude()) +
"Last known latitude: " + Double.toString(lastLoc.getLatitude()));
assertEquals(35.2276757, locationService.getLongitude());
assertEquals(31.7765488, locationService.getLatitude());
context.unregisterReceiver(locationReceiver);
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
}
private BroadcastReceiver locationReceiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
assertTrue(intent.getAction().equals("android.mtg.custom.intent.action.GPS_LOCATION"));
System.out.println("Action received: " + intent.getAction());
this.notify();
}
};
private IBinder getServiceBinder(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
return bindService(locationIntent);
}
private LocationManager getLocationManager(){
LocationManager lm = (LocationManager)
getContext().getSystemService(Context.LOCATION_SERVICE);
lm.addTestProvider(LocationManager.GPS_PROVIDER,
true, true, true, true, true, true, true,
Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE, null, System.currentTimeMillis());
lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
return lm;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
System.out.println("LocationServiceTest, onLocationChanged, lon:" +
Double.toString(location.getLongitude()) + ", lat:" +
Double.toString(location.getLatitude()));
}
#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
}
}
Try with
// Register the listener with the Location Manager to receive location updates
lm.requestLocationUpdates("YOUR PROVIDER", 0, 0, YOUR_LOCATION_LISTENER);
Found at Location guide of Android Developers

Categories

Resources