
我想在用户点击按钮时启动服务.
基本上,当用户点击开始按钮时,服务应该开始记录GPS坐标,当他点击停止时,服务应该终止.
我应该怎么做呢?
解决方法:
我不太清楚为什么要启动服务以启动/停止录制gps坐标.所以我会给你两个答案.一个将向您展示如何使用按钮启动和停止服务,另一个将向您展示如何开始/停止记录gps坐标,这不需要使用服务(尽管可以更改为这样做).
使用按钮启动/停止服务
你要做的主要是将android:onClick =“functionToCall”添加到按钮xml标签.将functionToCall替换为实际的函数名称.然后你必须使该函数调用startService()或stopService()函数来启动/停止服务.这是我的示例程序,它启动/停止一个名为SayHello的服务.
您可以忽略以下大多数xml,只需注意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(我用来保存按钮的活动):
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")); }}我确定您不想启动/停止SayHello服务,因此请确保更改Intent以调用您想要的服务.
总结以上是内存溢出为你收集整理的android – 在onClick上启动服务全部内容,希望文章能够帮你解决android – 在onClick上启动服务所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)