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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Start"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startClicked">
</Button>
<Button android: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;
public class ServiceClick extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startClicked(View view) {
startService(new Intent("SayHello"));
}
public void stopClicked(View view) {
stopService(new Intent("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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…