我想停止我的服务去完成它的任务。但服务不会停止我覆盖 onDestroy() 但它不起作用。当服务停止时,它将开始一个新的活动。
下面是我的代码
数据服务.java
package com.remote.synchronizer.haris;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class DataService extends Service {
boolean wifi,edge;
private Timer timer= new Timer();
SQLiteDatabase db;
String un,shop,city,date,order;
private SQLiteAdapter mySQLiteAdapter;
@Override
public void onCreate(){
super.onCreate();
mySQLiteAdapter = new SQLiteAdapter(this);
// this.stopSelf();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler mHandler = new Handler();
new Thread(new Runnable(){
@Override
public void run() {
Log.e("Service Started", "Successful");
while(true){
try{
Thread.sleep(10000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Checking network connectivity
wifi=NetworkInfo.Wifi(DataService.this);
edge=NetworkInfo.EDGE(DataService.this);
if(wifi==true||edge==true)
{
int count=mySQLiteAdapter.getCCount();
int counter=0;
if(mySQLiteAdapter.getCCount()>0){
while(counter<count){
Log.e("Service Network", "Network is online");
int id=mySQLiteAdapter.getID();
List<NameValuePair> contacts=new ArrayList<NameValuePair>();
contacts=mySQLiteAdapter.getSingleRecord(id);
String url="http://10.0.2.2:3325/Product/Create?";
int response = 0;
try
{
response = CustomHttpClient.executeHttpPost(url, contacts);
if(response==200){
mySQLiteAdapter.delete_byID(id);
Log.e("Data Sent", "Response 200");
counter++;
}
else{
Log.e("Service Data", "Faield to upload data" );
}
}
catch (Exception e)
{
Log.e("Data Sending Error", e.toString());
e.printStackTrace();
}
}
}
//
Thread.currentThread().interrupt();
}
else
{
Log.e("Service Network", "Network is offline");
}
}
});
}
catch (InterruptedException e) {
Log.e("Data Sending Error", e.toString());
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
Log.v("SERVICE","Service killed");
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
//timer.cancel();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callIntent.setClass(this, com.remote.synchronizer.haris.Login.class);
startActivity(callIntent);
super.onDestroy();
}
}
我读过的某处不停止服务Android会自行停止。如果是这样,请编辑我的代码并告诉我如何在我的工作完成后开始新的活动。我需要停止计时器吗?然后 onStartCommand 将停止,它会调用 onDestroy?如果是,那么我该如何停止计时器,因为我已经尝试过但没有成功。