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

时间:2015-08-03 06:31:42

标签: php android

我想从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();
        }
    }

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

3 个答案:

答案 0 :(得分:1)

您正面临此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();

答案 1 :(得分:1)

错误:

  

无法启动服务   使用Int的skripsi.ubm.studenttracking.altitudeSurvey@366d624d

从错误中我可以看到您正在主线程上运行网络操作。您无法在应用程序的主线程上运行网络操作。

您必须创建asynctask或线程才能在后台线程中运行网络操作。

答案 2 :(得分:1)

将此方法写入asynctask中。它会很完美。