service包含Android上的HttpURLConnection

时间:2015-09-25 13:06:13

标签: android httpurlconnection

我在android上做了一个应用程序,包含一个服务来请求服务器的interval_time。当我的应用程序打开时,该服务运行清晰。当我关闭/停止我的应用程序时,我在connection.connect();我希望myService可以在我的应用程序打开或关闭时清晰运行。

我的代码:

public class RequestService extends Service {

   String interval_config;

   private Handler mHandlerConfig = new Handler();

   private Timer mTimerConfig = null;
   public static long CONFIG_INTERVAL=10;

   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }

 @Override
 public void onCreate() {
        if(mTimerConfig != null){
            mTimerConfig.cancel();
        } else {
            mTimerConfig = new Timer();
        }
        mTimerConfig.scheduleAtFixedRate(new ConfigTimerTask(), 0, CONFIG_INTERVAL);
   }

 class ConfigTimerTask extends TimerTask {
    @Override
    public void run() {
        // run on another thread
        mHandlerConfig.post(new Runnable() {

            @Override
            public void run() {
                URL url = new URL(/*URL address*/);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(15000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();  //error here
            }

        });
    }

  }

}

我如何运行我的服务:

startService(new Intent(this, RequestService.class));

错误:

2517-2517/com.sia.siav2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
        at      android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
        at java.net.InetAddress.getAllByName(InetAddress.java:214)
        at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
        at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
        at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
        at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
        at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
        at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
        at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
        at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
        at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
        at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
        at com.sia.siav2.service.RequestService.jsonFunction(RequestService.java:277)
        at com.sia.siav2.service.RequestService.memintaIntervalNotif(RequestService.java:141)
        at com.sia.siav2.service.RequestService$ConfigTimerTask$1.run(RequestService.java:106)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

首先,您几乎不应该在Android中使用Timer。你遇到的麻烦说明了原因。当AsyncTask为您完成所有操作时,它会强制您自己管理线程和线程安全。间隔做事的最佳方式通常是Handler#postDelayed(...)

您的错误可能是NetworkOnMainThreadException,对吧?它崩溃是因为你在主线程中调用了connect()。一旦你越过它,你可能会遇到其他问题,因为你的TimerTask试图每10毫秒运行一次。

答案 1 :(得分:1)

我相信你这里有两个问题。网络连接在主线程上运行,并且在应用程序退出后计时器不会停止。

服务将在主线程上创建,这意味着Handler mHandlerConfig也在主线程上,并且通过扩展名定时器中的帖子,这意味着网络连接也在主线程上运行。如果只是将连接代码移动到Timer的run()方法中,错误就会消失。

要确保在退出应用程序后停止计时器,您应该添加代码以停止服务的onDestroy方法中的计时器。