在 onClick 上启动服务

var*_*ker 2 service gps android button

我想在用户单击按钮时启动服务。

基本上,当用户单击开始按钮时,服务应开始记录 GPS 坐标,当他单击停止时,服务应终​​止。

我应该如何实施这个?

Ant*_*ton 5

我不太确定您为什么要启动服务以开始/停止记录 gps 坐标。所以我给你两个答案。一个将向您展示如何使用按钮启动和停止服务,另一个将向您展示如何开始/停止记录不需要使用服务完成的 GPS 坐标(尽管可以更改为这样做)。

使用按钮启动/停止服务

您需要做的主要事情是添加android:onClick="functionToCall" 到按钮 xml 标记。替换functionToCall为真正的函数名。然后,您必须使该函数调用startService()stopService()函数来启动/停止服务。这是我的示例程序,用于启动/停止名为 SayHello 的服务。

您可以忽略以下大部分 xml 只需注意 android:onClick=""

主文件:

<?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> 
Run Code Online (Sandbox Code Playgroud)

ServiceClick.java(我制作的用于保存按钮的活动):

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"));
    }

}
Run Code Online (Sandbox Code Playgroud)

我确定您不想启动/停止 SayHello 服务,因此请确保更改 Intent 以调用您想要的服务。