0

Today i made my first background service that keeps running if i exit from my application.

It is logging lattitude and londitude.

I would like to add some more functions to my code, and i would like to ask your help about which way should i contine coding, and is it good that i made already?

I work with an Activity, with a handler that gets messages from background service:

public class MyActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_act);



    BackgroundLocationService.context=this;

    Intent i = new Intent(this, BackgroundLocationService.class);
    i.putExtra("handler", new Messenger(this.handler));
    startService(i);
            /*.......more code here......*/
}

    Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // get data from msg
        String result = msg.getData().getString("result");
        Log.i("Activiti map: Locationing Service handler: ", 
                          "get data: " + result);
        super.handleMessage(msg);
    }
};

And this is my background service:

public class BackgroundLocationService extends IntentService {

private static final String TAG = "Activiti map: Locationing Service";

private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
public static Context context;

private boolean gps_enabled = false;
private boolean network_enabled = false;

private boolean DEBUG=false;

private String latitude="0";
private String londitude="0";

Messenger messenger;
Timer t=new Timer();

public BackgroundLocationService()
{
    super("myintentservice");

    locManager = (LocationManager) context.getSystemService
                                   (Context.LOCATION_SERVICE);
    try {
        gps_enabled = 
                    locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
        if(DEBUG)
        Log.e(TAG, ex.toString());
    }
    try {
        network_enabled = 
                locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
        if(DEBUG)
        Log.e(TAG, ex.toString());
    }

    if (gps_enabled) {
        if(DEBUG)
        Log.i(TAG, "Gps is Enabled!");
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                     0, 0, locListener);
    } else {
        if(DEBUG)
        Log.i(TAG, "Gps is Disabled!");
    }
    if (network_enabled) {
        if(DEBUG)
        Log.i(TAG, "Network provider is enabled!");

                   locManager.requestLocationUpdates
                        (LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
    } else {
        if(DEBUG)
        Log.i(TAG, "Network provider is Disabled!");
    }
}



@Override
protected void onHandleIntent(Intent intent) {
    messenger=(Messenger) intent.getExtras().get("handler");

    t.schedule(new TimerTask() {

        @Override
        public void run() {
            // just call the handler every 3 Seconds

            Message msg=Message.obtain();
            Bundle data=new Bundle();
            data.putString("result", "latitude: " + latitude+
                           " londitude: "+londitude);
            msg.setData(data);

            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, 100,3000);

}


class MyLocationListener implements LocationListener {

    private static final String TAG = "Activiti map: LocationListener";

    public void onLocationChanged(Location location) {

        if (location != null) {
            locManager.removeUpdates(locListener);

            londitude = Double.toString(location.getLongitude());
            latitude = Double.toString(location.getLatitude());

            if(DEBUG)
            Log.i(TAG, "Londitude: " + londitude + " Latitude: " + latitude);

        }
    }

    public void onProviderDisabled(String arg) {
        if(DEBUG)
        Log.i(TAG, "Provider just Disabled: " + arg);
    }

    public void onProviderEnabled(String arg) {
        if(DEBUG)
        Log.i(TAG, "Provider just Enabled: " + arg);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {


    }
}

}

Some problems that i would like to solve:

Is it possible to control the handler the service or anything in my code to keep SURE, that the service is stopped, started, etc? So i would like to add controls for example from a widget button for turning on and off the service. How is it possible ?

And another thing: If i quickly starts and exit my application many times i got each time a handler initalized and i got multiple log messages. How can i make a singleton of this or something like that?

Thanks for helping

1 Answer 1

1

Use Application for those purposes.

You can implement singleton logic into Application class and manage your service.

If you close your activity, the Service asks Application if Activity alive.

On Launch Activity, Application knows about and Service can bind with above mentioned Activity by using some Interfaces that Application stores.

** The main Activity must initiate Handler to make to Service to talk with Activity

Here is some code:

public class MyApplication extends Application{

 private static MyApplication mSingleton;


    private static final String PACKAGE = "com.code";
    private static final String PROCESS_NAME = PACKAGE + ".ui";
    private static final String SERVICE_NAME = PROCESS_NAME + "/" + PACKAGE + ".srvce.MyService";

      @Override
   public void onCreate() {
     super.onCreate();
     mSingleton = this;
   }

       public MyApplication getApp(){
         return mSingleton;
       }

      ....

      public boolean isServiceRun() {

    ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
    List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

    boolean isRunnig = false;

    for (int i = 0; i < services.size(); i++) {             
        RunningServiceInfo inf = services.get(i);
        if(PROCESS_NAME.equals(inf.process)){                   
            ComponentName cn = inf.service;                 
            String str = cn.toString();                 
            if(str.contains(SERVICE_NAME)){
                isRunnig = true;
                return isRunnig;
            }
        }               
    }  

    return isRunnig;        
}

 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.