Java Android:停止向服务器发送数据的线程

Java Android:停止向服务器发送数据的线程,java,android,multithreading,Java,Android,Multithreading,我目前正在做一个耗时的项目,我遇到了很多让我的生活非常困难的小困难。。。 我向您提交了我的最后一个问题:我创建了一个线程,将数据发送到服务器,以便将其放入数据库中。它工作,但只有第一次,因为我的线程没有停止 代码如下: threadHttp = new Thread(){ @Override public void run(){ try{ httpClient = new DefaultHtt

我目前正在做一个耗时的项目,我遇到了很多让我的生活非常困难的小困难。。。 我向您提交了我的最后一个问题:我创建了一个线程,将数据发送到服务器,以便将其放入数据库中。它工作,但只有第一次,因为我的线程没有停止

代码如下:

threadHttp = new Thread(){
        @Override
        public void run(){
                try{
                    httpClient = new DefaultHttpClient();
                    httpPost = new HttpPost("http://www.seismdetector.info/reception.php");
                    nameValuePairs = new ArrayList<NameValuePair>(); // C'est la liste qui contiendra les couples champ/valeur
                    nameValuePairs.add(new BasicNameValuePair("test", "android"));
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    httpClient.execute(httpPost);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }  
        }
    };
但它也不起作用


非常感谢。

您应该使用
AsyncTask
类来完成以下任务:

private class ExampleThread extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {}

    @Override
    protected void doInBackground(Void... params) {
        try{
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost("http://www.seismdetector.info/reception.php");
            nameValuePairs = new ArrayList<NameValuePair>(); // C'est la liste qui contiendra les couples champ/valeur
            nameValuePairs.add(new BasicNameValuePair("test", "android"));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }

    @Override
    protected void onPostExecute(Void... params) {}

}
要停止线程,请执行以下操作:

ExampleThread thread = new ExampleThread();
thread.execute();
thread.cancel();

在您发布的代码中,您正在创建一个新线程,但从未启动它。如果您觉得在尝试重新启动线程时遇到问题,那么请发布您认为可以执行此操作的代码,因为您提供的代码没有这样做。对于您似乎正在尝试做的事情,AsyncTask可能是一个很好的解决方案——基本上让AsyncTask的实现担心选择或创建一个合适的后台线程来完成任务…}你能告诉我一个学习如何使用AsyncTask的好地方吗?谢谢!考虑它的文档,或者在这里搜索它。线程.STATE()只能调用一次。interrupt()或join()没有帮助。创建另一个线程实例。
thread.cancel();