Background location service start not working
I have some problems using Android background location service. I started using this code and modified it for my own needs: https://gist.github.com/blackcj/20efe2ac885c7297a676
Here are the modified parts for the LocationLoggerServiceManager:
I changed the part so I can start this service manually with my own broadcast.
public class LocationLoggerServiceManager extends BroadcastReceiver {
private SharedPreferences mPrefs;
public static final String TAG = "LocationLoggerServiceManager";
@Override
public void onReceive(Context context, Intent intent) {
// Make sure we are getting the right intent
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction()) || "ftm.vem_game.services.LocationLoggerServiceManager".equals((intent.getAction()))) {
boolean mUpdatesRequested = false;
// Open the shared preferences
mPrefs = context.getSharedPreferences("ftm.vem_game.shared_preferences",
Context.MODE_PRIVATE);
/*
* Get any previous setting for location updates
* Gets "false" if an error occurs
*/
if (mPrefs.contains("KEY_UPDATES_ON")) {
mUpdatesRequested = mPrefs.getBoolean("KEY_UPDATES_ON", false);
}
if(mUpdatesRequested){
//ComponentName comp = new ComponentName(context.getPackageName(), BackgroundLocationService.class.getName());
//ComponentName service = context.startService(new Intent().setComponent(comp));
Intent i = new Intent(context, BackgroundLocationService.class);
ComponentName service = context.startService(i);
if (null == service){
// something really wrong here
Log.e(TAG, "Could not start service BackgroundLocationService");
}
}
} else {
Log.e(TAG, "Received unexpected intent " + intent.toString());
}
}
}
And here is the part I am sending Broadcast to my MainActivity class:
public static final String BROADCAST = "ftm.vem_game.services.LocationLoggerServiceManager";
SharedPreferences sharedPref = getSharedPreferences("ftm.vem_game.shared_preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("KEY_UPDATES_ON", true);
editor.commit();
Intent intent = new Intent(BROADCAST);
Bundle extras = new Bundle();
extras.putString("send_data", "test");
intent.putExtras(extras);
sendBroadcast(intent);
I haven't changed anything in the service class. The problem is the service never starts, in the log it says "Failed to start BackgroundLocationService". And context.startService () returns null every time.
I don't know what I am doing wrong, or maybe I missed something to do before starting the service.
You may have forgotten to define the service in AndroidManifest.xml if you just add something like the following code to your manifest:
<service
android:name="com.examples.yourApp.BackgroundLocationService"
android:icon="@drawable/ic_launcher"
android:label="@string/service_name">
</service>
and if you want to run it in the background, see the following link: http://uncorkedstudios.com/blog/background-location-updates-on-android