Skip to content Skip to sidebar Skip to footer

Start A Service On Onclick

I want to start a service when the user clicks a button. Basically, when the user clicks the start button the service should start recording GPS coordinates and when he clicks stop

Solution 1:

I'm not quite sure why you want to start a service in order to start/stop recording gps coordinates. So I'll give you two answers. One will show you how to start and stop a service with buttons and the other will show you how to start/stop recording gps coordinates which does not need to be done with a service (though can be changed to do so).

Start/Stop A Service With Buttons

The main thing you have to do is add android:onClick="functionToCall" to the button xml tag. Replace functionToCall with the real function name. Then you have to make that function call either the startService() or stopService() function to start/stop the service. Here is my example program that starts/stops a service that called SayHello.

You can ignore most of the following xml just notice the android:onClick=""

main.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"
    ><Buttonandroid:text="Start"android:id="@+id/Button01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="startClicked"></Button><Buttonandroid:text="Stop"android:id="@+id/Button02"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="stopClicked"></Button></LinearLayout>

ServiceClick.java (the activity I made that holds the buttons):

package com.ServiceClick;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

publicclassServiceClickextendsActivity {

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    publicvoidstartClicked(View view) {
        startService(newIntent("SayHello"));
    }

    publicvoidstopClicked(View view) {
        stopService(newIntent("SayHello"));
    }

}

I'm sure you don't want to start/stop the SayHello Service, so make sure you change Intent to call for the service you do want.

Solution 2:

I decide to put the GPS location recording answer into a new post to make things cleaner.

Recording GPS Coordinates

The first thing we need to do is add a line into our AndroidManifest.xml saying we want to be allowed to record GPS coordinates:

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android".... >
    ....       
    <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /></manifest>

(I put in those .... to represent that I was omitting some content)

Next you have to add the android:onClick="functionToCall" to the each of the button tags (see my other answer for more detail). The button tags should look something like this:

<Buttonandroid:text="Start"android:id="@+id/Button01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="startButton"></Button><Buttonandroid:text="Stop"android:id="@+id/Button02"android:layout_width="wrap_content"android:layout_height="wrap_content"android:onClick="stopButton"></Button>

Now you have to ask the system for the LocationManager, which we can give a LocationListener to use when a location is recieved. We will give the LocationManager the LocationListener when the start button is hit and remove that listener when the stop button is hit. That LocationListener will call a function to store the location.

Here is the code to do that:

package com.TrackLocation;

import java.util.ArrayList;
//Ommitted rest of the importspublicclassTrackLocationextendsActivity {
    ArrayList<Location> recordedLocations = newArrayList<Location>();

    LocationManager locationManager;
    LocationListener locationListener; 

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        // Get the manager from the system
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        // Create the locationListener that we will be adding and removing
        locationListener = newLocationListener() {
            publicvoidonLocationChanged(Location location) {
                recordLocation(location);
            }

            publicvoidonStatusChanged(String provider, int status, Bundle extras) {}

            publicvoidonProviderEnabled(String provider) {}

            publicvoidonProviderDisabled(String provider) {}
          };

    }

    publicvoidrecordLocation(Location loc) {
        recordedLocations.add(loc);
    }

    publicvoidstartButton(View view) {
        //Add the listener asking for GPS
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    }

    publicvoidstopButton(View view) {
        locationManager.removeUpdates(locationListener);
    }
}

The above code doesn't do much with the values (in fact you can't even see the locations without using the debugger), but I wanted to keep this as small as possible. I have fuller version of the code that will display the locations in a ListView. Here is the link to that fuller version.

Post a Comment for "Start A Service On Onclick"