I want to send the longitude and latitude from my onLocationChanged method inside the class GPSTracker to GPSPrincipal (Which is my main activity) and activate a toast that shows the longitude and latitude.
I'm having problems with the broadcastreciver to send the data from GPSTracker to GPSPrincipal, also, the aplication crashes and it shows the following error:
FATAL EXCEPTION: main java.lang.NullPointerException at
android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:344)
at
co.edu.javeriana.introcm.gpsexample.GPSTracker.onLocationChanged(GPSTracker.java:192)
The line 192 is:
sendBroadcast(broadcastIntent);
Last line on onLocationChanged inside GPSTracker
GPSPrincipal (Main activity):
public class GPSPrincipal extends Activity {
GPSTracker gps;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpsprincipal);
}
public void loca(View arg0) {
gps = new GPSTracker(GPSPrincipal.this);
if(gps.canGetLocation()){
TextView latitud = (TextView) findViewById(R.id.showLatitud);
TextView longitud = (TextView) findViewById(R.id.showLongitud);
latitud.setText(String.valueOf(gps.getLatitude()));
longitud.setText(String.valueOf(gps.getLongitude()));}
else {
gps.showSettingsAlert();}
}
public void cambio () {
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Located: - \nLat: " + intent.getExtras().get("latitude") + "\nLong: " + intent.getExtras().get("longitude"), Toast.LENGTH_LONG).show();}};
registerReceiver(receiver, new IntentFilter("com.example.broadcast.gps.location_change"));
} }
GPSTracker:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private Location location;
private double latitude; // latitud
private double longitude; // longitud
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context; //Obtener el contexto
getLocation();
}
public void onLocationChanged(Location location) {
Intent broadcastIntent = new Intent("com.example.broadcast.gps.location_change");
broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
broadcastIntent.putExtra("latitude", latitude);
broadcastIntent.putExtra("longitude", longitude);
sendBroadcast(broadcastIntent);
}
Manifest:
package="co.edu.javeriana.introcm.gpsexample"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".GPSPrincipal"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Potentially seems to be that your context when calling sendBroadcast() is null within the ContextWrapper class. Perhaps you should try using mContext.sendBroadcast and see if that makes a difference.
Related
I am building app that tracks distance traveled. At the moment, I am having trouble displaying the coordinates. The code runs, but the Distance, which I've set to display the coordinates when Start is clicked, displays 0.00 when clicked.
public class MainActivity extends Activity {
private Button historyButton, startButton, stopButton;
private TextView Distance;
double currentDistance;
private SensorManager sensorManager;
private Chronometer TimeRan;
private LocationManager mLocManager;
private LocationListener location;
double longitude, latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing all buttons and textviews
historyButton = (Button) findViewById(R.id.History);
startButton = (Button) findViewById(R.id.Start);
stopButton = (Button) findViewById(R.id.Stop);
Distance = (TextView) findViewById(R.id.Distance);
TimeRan = (Chronometer) findViewById(R.id.Time_Spent);
mLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
location = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
currentDistance += .01;
Distance.append("/n " + location.getLongitude() + " " + location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
};
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 100:
configureButton();
break;
default:
break;
}
}
public void configureButton(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,100);
}
return;
}
//Request update every minute or 16 meters
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ignore permission
mLocManager.requestLocationUpdates("gps", 60000, 16, location);
}
});
};
public void GoToHistory(View v) {
Intent history = new Intent(this, History.class);
startActivity(history);
}
protected void EndWorkout(View v){
TimeRan.stop();
//ignore permission
mLocManager.removeUpdates(location);
}
}
Here is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stuyk.runningapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.sensor.stepcounter"/>
<uses-feature android:name="android.hardware.sensor.stepdetector"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".History" />
</application>
</manifest>
locationManager.requestLocationUpdates(
provider,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
You should set MINIMUM_TIME_BETWEEN_UPDATES to time that you want it to be updated frequently and set MINIMUM_DISTANCE_CHANGE_FOR_UPDATES distance the update will change according to your location status.
I'm making this simple app where when a button is placed users gps location should be displayed and it works fine with emulator but when i try that in a real phone both longitude and latitude are zero.
this is my code:
Main Activiy:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView longS = (TextView) findViewById(R.id.longi);
final TextView latiS = (TextView) findViewById(R.id.lati);
Button btn_show_location = (Button) findViewById(R.id.button1);
btn_show_location.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
LocationManager mlocManager=null;
LocationListener mlocListener;
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
if(MyLocationListener.latitude>0)
{
longS.setText("Latitude:- " + MyLocationListener.latitude);
latiS.setText("Longitude:- " + MyLocationListener.longitude + '\n');
}
else
{
longS.setText("Please wait");
}
} else {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
}
});
}
MyLocationListener:
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
// loc.getLatitude();
//loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
#Override
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.databasecollect"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have a trouble. I can't get location on my HTC incredible.
It's my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationfinder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
It's my activity
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#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.NETWORK_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "WIFI Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "WIFI Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText( getApplicationContext(), "snth", Toast.LENGTH_SHORT).show();
}
}/* End of Class MyLocationListener */
}
If I choose LocationManager.GPS_PROVIDER instead LocationManager.NETWORK_PROVIDER and GPS is off it currently makes toast with "GPS disabled". But if I use LocationManager.NETWORK_PROVIDER nothing happens no matter what the WiFi state is.
I am trying to learn the basics of location services and putting "pins" to mark locations.
I'm not sure whether this is the best approach, or what the alternatives are. What would be a better, or just a simpler way of doing this? Or what is the standard way?
Additionally, when I run this app on ICS 4.0.3, the phone just freezes after a few minutes. It works fine at first, and shows me the location, but eventually the entire device becomes unresponsive. I've checked both logcat and last_kmsg, and I can't find any hints about what is causing this. Gingerbread 2.3.6 runs the code without problems (at least it didn't crash for over 15min, while ICS crashes within 1~5min).
It doesn't seem like an exception, so maybe this is some memory leak or a kernel panic? I'm not sure how to start debugging this :\
Any help would be appreciated!
I am using the following code:
Mapper.java:
public class Mapper extends MapActivity{
MapView mapView;
LocationManager lm;
LocationListener ll;
GeoPoint p;
MapController mc;
MapOverlay overlay;
List<Overlay> lol;
public void onCreate(Bundle x){
super.onCreate(x);
setContentView(R.layout.mapper);
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
lol = mapView.getOverlays();
overlay = new MapOverlay();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new MyLocationListener();
mapView.invalidate();
}
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location loc){
if(loc!=null){
int lat = (int)(loc.getLatitude() * 1E6);
int lon = (int)(loc.getLongitude() * 1E6);
p = new GeoPoint(lat,lon);
mc.animateTo(p);
mc.setZoom(18);
lol.clear();
lol.add(overlay);
}
}
#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 onResume(){
super.onResume();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
}
public void onPause(){
super.onPause();
lm.removeUpdates(ll);
}
protected boolean isRouteDisplayed(){
return false;
}
private class MapOverlay extends com.google.android.maps.Overlay{
public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when){
super.draw(canvas, mv, shadow);
Point sp = new Point();
mv.getProjection().toPixels(p, sp);
Bitmap pic = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
canvas.drawBitmap(pic, sp.x, sp.y, null);
canvas.drawBitmap(pic, sp.x+60, sp.y, null);
canvas.drawBitmap(pic, sp.x-60, sp.y, null);
canvas.drawBitmap(pic, sp.x, sp.y+60, null);
canvas.drawBitmap(pic, sp.x, sp.y-60, null);
return true;
}
}
}
mapper.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="mykeyworks"
android:clickable="true" />
</LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jinworld"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>"
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="Second Activity" >
<intent-filter>
<action android:name="com.jinworld.SecondActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Notify"
android:label="DEVELOPERS" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Mapper"
android:label="Locatio" >
<intent-filter>
<action android:name="com.jinworld.Mapper" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
You don't need so much code to display your location, google already has an Overlay for this.
Try this, it may helps:
public class Mapper extends MapActivity{
com.google.android.maps.MyLocationOverlay myLocationOverlay;
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
}
#Override
public void onCreate(Bundle x){
...
setupMyLocation();
...
}
protected void setupMyLocation(){
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getOverlays().add(myLocationOverlay);
}
});
}
}
I tried to implement the addProximityAlert method, but it does not fire. Here is my code:
SampleProximityAlert
public class SampleProximityAlert extends Activity {
/** Called when the activity is first created. */
protected LocationManager locationManager;
protected Location location;
public static Location pLocation;
protected Intent intent;
protected PendingIntent pIntent;
protected GeoPoint point;
public float distance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1,
new ProximityListener());
} catch (RuntimeException e) {
e.printStackTrace();
}
// point = new GeoPoint(49868004, 8626971);
try {
pLocation = new Location(location.getProvider());
} catch (RuntimeException e) {
e.printStackTrace();
}
Log.i("PROVIDER", location.getProvider());
pLocation.setLatitude(49.868004);
pLocation.setLongitude(8.626971);
distance = methodeDistance(pLocation);
Log.i("DISTANCE", String.valueOf(distance));
Log.i("POSITION",
String.valueOf(location.getLatitude()) + ","
+ String.valueOf(location.getLongitude()));
intent = new Intent(this, ProximityAlert.class);
intent.setAction("ProximityAlert");
pIntent = PendingIntent.getService(this, 0, intent, 0);
locationManager.addProximityAlert(49.868004, 8.626971, 429, 50000,
pIntent);
}
public float methodeDistance(Location mLocation) {
float mDistance = location.distanceTo(pLocation);
return mDistance;
}
}
ProximityAlert
public class ProximityAlert extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i("Alert", "fired");
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i("ONCREATE", "create ProximityAlert as Service");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ONSTARTCOMMAND", "OnStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
ProximityListener
public class ProximityListener implements LocationListener {
String DEBUG_TAG = "ProximityListener";
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(DEBUG_TAG, location.toString());
// tvD.setText(String.valueOf(location.distanceTo(pLocation)));
}
#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
}
}
XML Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsystems.proximityAlert"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleProximityAlert"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ProximityAlert">
<intent-filter>
<action android:name="ProximityAlert"/>
<category android:name="com.proaktiveOrtung"/>
</intent-filter>
</service>
<service android:name=".ProximityAlert"></service>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsystems.proximityAlert"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SampleProximityAlert"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ProximityAlert">
<intent-filter>
<action android:name="ProximityAlert"/>
<category android:name="com.proaktiveOrtung"/>
</intent-filter>
</service>
<service android:name=".ProximityAlert"></service>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
Sorry I selected not the complete code.
when you add a ProximityAlert you have to pass a PendingIntent to the LocationManager, these PendingIntent will be fired on a broadcastIntent and i dont see in your code when, where you register a receiver for that PendingIntent.
Now a question... why do you write a service if you add the ProximityAlert on an Activity?