无法以Intent {flg=0x4 (has extras)}启动服务


Unable to start service with Intent { flg=0x4 (has extras) }

我想从Service插入到PHP。但是我有这样的错误:

Unable to start service skripsi.ubm.studenttracking.altitudeSurvey@366d624d with Intent { flg=0x4 cmp=skripsi.ubm.studenttracking/.altitudeSurvey (has extras) }: android.os.NetworkOnMainThreadException

这是我的代码:

public void insert() {
        String time;
        SimpleDateFormat dayFormat = new SimpleDateFormat("HH:mm:ss", Locale.US);
        Calendar calendars = Calendar.getInstance();
        time = dayFormat.format(calendars.getTime());
        try {
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost("http://studentstracking.hol.es/altitudeSurvey.php");
            nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("baro", value));
            nameValuePairs.add(new BasicNameValuePair("jam", time));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpClient.execute(httpPost);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpClient.execute(httpPost, responseHandler);
            Toast.makeText(altitudeSurvey.this, "Response from Server : " + response, Toast.LENGTH_SHORT).show();
            if (response.equalsIgnoreCase("Success")) {
                Toast.makeText(getApplicationContext(), "Data has been Inserted", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Data Failed", Toast.LENGTH_SHORT).show();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这个方法在服务内部。你能帮我解决这个问题吗?

您正面临这个android.os.NetworkOnMainThreadException,这意味着您正在从您的oncreate调用insert()方法。您需要使用AsyncTask,这将使您免于此异常。

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         insert()
         return result;
     }
     protected void onProgressUpdate(Integer... progress) {
     }
     protected void onPostExecute(Long result) {
     }
 }

像这样启动asyncTask

new DownloadFilesTask().execute();

将此方法写入asynctask中。

错误:

无法启动服务skripsi.ubm.studenttracking。altitudeSurvey@366d624d with Int

从错误中可以看到你正在主线程上运行网络操作。不能在应用程序的主线程上运行网络操作。

要么你必须创建asynctask或线程在后台线程运行网络操作。