I am trying to create an app that gives me the GPS coordinates when a photo is taken. Because the GPS needs to be accurate I am running it as a service to get the best lock. However when the main activity is opened the startservice()
in onCreate()
does not access the onStartCommand in GPSClass.
It runs the onStart()
and then is for some reason triggered to access that class after finishing both starting procedures.
Why is this happening? It seems so illogical. By the way, I have been trying to walk through using debugging.
Main activity start up code
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent GPSstart = new Intent(this, GPSClass.class);
this.startService(GPSstart);
}
private void GPSrunner() {
Intent GPSstart = new Intent(this, GPSClass.class);
this.startService(GPSstart);
// check GPS is onstart
if (!GPSClass.isGPSon()) {
buildAlertMessageNoGps();
}
}
@Override
protected void onStart() {
super.onStart();
GPSrunner();
}
Service Code
public class GPSClass extends Service implements LocationListener {
private static final int TWO_MINUTES = 1000 * 60 * 2;
private static LocationManager locationManager;
private static boolean GPSOn;
private static Location location;
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
GPSOn = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@ Override
public void onDestroy() {
locationManager.removeUpdates(this);
public static boolean isGPSon() {
return GPSOn;
}
Manifest
<service android:name=".GPSClass"
android:exported="false"
/>
<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>