【发布时间】:2015-07-17 06:47:39
【问题描述】:
我正在尝试在 android 中创建一个简单的服务。
我检查了设置->应用程序选项卡,我可以看到服务正在运行。不幸的是 OnStartCommand 函数没有被执行。我什至看不到 toast 消息。
这是我的代码:
服务类
public class CertisServices extends Service {
GPSTracker gps;
private double latitude = 0;
private double longitude = 0 ;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public int OnStartCommand(Intent intent, int flags, int startId){
get_my_gps_location();
String lati = String.valueOf(latitude);
String longi = String.valueOf(longitude);
Toast.makeText(this, "Services started : ", Toast.LENGTH_LONG).show();
send_data(lati, longi);
return START_STICKY;
}
public void OnDestroy (){
super.onDestroy();
Toast.makeText(this, "Services stopped", Toast.LENGTH_LONG).show();
}
private void send_data(String lat, String lng){
HttpClient httpclient = new DefaultHttpClient();
// Your URL
HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/get-schedules/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// Your DATA
nameValuePairs.add(new BasicNameValuePair("latitude", lat));
nameValuePairs.add(new BasicNameValuePair("longitude", lng));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void get_my_gps_location(){
gps = new GPSTracker(CertisServices.this);
// check if GPS enabled
if(gps.canGetLocation()){
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
//gps.showSettingsAlert();
}
}
}
主要活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
startService(new Intent(getBaseContext(), CertisServices.class));
我没有收到任何错误消息。谁能帮我解决这个问题?谢谢。
【问题讨论】:
-
a
Service没有有这样的方法:OnStartCommand -
另外,不要使用
Toasts 进行调试:改用Log.d -
@pskink tnx。我也尝试使用 Log.d,它没有记录任何内容。
-
因为没有这样的方法:
OnStartCommand覆盖,使用@Override注释来确保你覆盖了一些基本方法,像这样@Override onStartCommand(...