脱机时如何停止服务中的线程?

时间:2018-07-22 12:09:05

标签: android android-intentservice

我正在开发一个Android应用程序,当它通过使用服务和广播接收器连接到互联网时调用webservice,这是我的代码:

public class YourService extends IntentService {
private static String TAG = YourService.class.getSimpleName();
private MyThread mythread;
public boolean isRunning = false;
JSONArray SaveOrderDart,SaveOrderDetails,UpdateDart,updateOrderDetails;
private static String urlDartorder= Config.url+"SaveDartDetails";
private static String urlupdateOrderDetails= Config.url+"UpdateOrderDetails";
private static String urlSaveOrderDetails= Config.url+"SaveOrderDetails";
private static String urlDartupdate= Config.url+"UpdateDartDetails";
DartDatabase ddb;
OrderDatabase ord;

/**
 * Creates an IntentService.  Invoked by your subclass's constructor.
 *
 * @param name Used to name the worker thread, important only for debugging.
 */
public YourService(String name) {
    super(name);
}

@Override
public void onCreate() {
    super.onCreate();
    mythread=new MyThread();
}

public YourService()
{
    super("call webservice");
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {

    Bundle extras = intent.getExtras();
    boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
    // your code
    if(isNetworkConnected){
        if(!isRunning){
            mythread.start();

            isRunning = true;
        }
        Log.e("TAG", "Yes");


    }
    else {

        if (mythread != null) {

            isRunning = false;
            mythread.interrupt();


        }
        //mythread.stop();
    }


}

@Override
public void onDestroy() {
    super.onDestroy();
    if(!isRunning){
        mythread.start();

        isRunning = true;
    }
}

我的广播接收器

public class ConnectivityChangeReceiver extends BroadcastReceiver {

boolean mLastState =false;
@Override
public void onReceive(Context context, Intent intent) {

    // Explicitly specify that which service class will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            YourService.class.getName());

            //mLastState = true;
            intent.putExtra("isNetworkConnected", isConnected(context));
            context.startService((intent.setComponent(comp)));


}

public  boolean isConnected(Context context) {
    ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
}

}

我的目的是当存在互联网时,我想调用不存在的webservice,然后停止线程和服务,但是通过此代码,我无法停止服务,我不,为什么不可以帮助我! 但是我无法停止线程,请帮助我!

0 个答案:

没有答案