android 4.0 中的 android.os.NetworkOnMainThreadException

标签 android eclipse

<分区>

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Signin extends Activity {

    EditText edt_mail, edt_password;
    Button btn_login, btn_pass, btn_reg, btn_forget;
    ImageView iv1, iv2;
    String strmail, strpassword, strres;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signin);

        btn_forget = (Button) findViewById(R.id.btnforget);

        edt_mail = (EditText) findViewById(R.id.edt_Username);
        edt_password = (EditText) findViewById(R.id.edt_Password);

        btn_login = (Button) findViewById(R.id.btnlogin);
        btn_pass = (Button) findViewById(R.id.btncancel);
        btn_reg = (Button) findViewById(R.id.btnReg);
        iv1 = (ImageView) findViewById(R.id.imgfacebook);
        iv2 = (ImageView) findViewById(R.id.imgtwitter);
        btn_forget.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, ForgetPassword.class);
                startActivity(intent);

            }
        });
        iv2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, Twitter.class);
                startActivity(intent);

            }
        });
        iv1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, Facebook.class);
                startActivity(intent);

            }
        });

        btn_reg.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Signin.this, Signup.class);
                startActivity(intent);
            }
        });
        btn_pass.setOnClickListener(new OnClickListener() {

            public void onClick(View v) { // TODO Auto-generated method stub

                cleartext();
            }

            public void cleartext() { // TODO Auto-generated method stub

                edt_mail.setText("");
                edt_password.setText("");
            }
        });

        btn_login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!edt_mail.getText().toString().equals("")) {

                    if (!edt_password.getText().toString().equals("")) {

                        try {
                            if (CheckConnection()) {
                                // new GetAccess().execute("");
                                getLogin();
                            } else {
                                Toast.makeText(
                                        Signin.this,
                                        "Please check your internet connection",
                                        Toast.LENGTH_LONG).show();
                            }

                        } catch (Exception e) {
                            Toast.makeText(Signin.this,
                                    "Error caught = " + e.toString(),
                                    Toast.LENGTH_LONG).show();
                        }

                    } else {

                        Toast.makeText(Signin.this, "please enter Password",
                                Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(Signin.this, "please enter Username",
                            Toast.LENGTH_LONG).show();

                }

            }

            private boolean CheckConnection() {
                final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
                if (activeNetwork != null
                        && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
                    // notify user you are online
                    // System.out.println("Internet connected = 1");
                    return true;

                } else {
                    // notify user you are not online
                    // System.out.println("Internet not connected = 0");
                    Toast.makeText(getApplicationContext(),
                            "Please check your internet connection ",
                            Toast.LENGTH_SHORT).show();
                    return false;

                }
            }
        });

    }

    public boolean CheckConnection() {
        final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
        if (activeNetwork != null
                && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
            // notify user you are online
            // System.out.println("Internet connected = 1");
            return true;
        } else {
            // notify user you are not online
            System.out.println("Internet not connected = 0");
            Toast.makeText(getApplicationContext(),
                    "Please check your internet connection ",
                    Toast.LENGTH_SHORT).show();
            return false;

        }

    }

    private void loadList() {

        /*
         * ArrayAdapter<String> adapter = new ArrayAdapter<String>(
         * MainActivity.this, android.R.layout.simple_list_item_1, eventlist);
         * view.setAdapter(adapter);
         */

        Intent intent = new Intent(Signin.this, MainList.class);
        startActivity(intent);

    }

    public void getLogin() {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "my link");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            // nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("email", edt_mail
                    .getText().toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("password", edt_password
                    .getText().toString().trim()));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpResponse = httpclient.execute(httppost);
            HttpEntity entity = httpResponse.getEntity();

            InputStream inputStream = entity.getContent();

            // EntityUtils.toString(httpResponse.getEntity());
            String strres = convertStreamToString(inputStream);

            if (!strres.toString().trim().equals("0")) {
                Toast.makeText(Signin.this, "Successfully logged in ",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Signin.this, NewMainList.class);

                startActivity(intent);
            }

            else if (strres.toString().trim().equals("0")) {
                Toast.makeText(Signin.this, "Invalid login and password",
                        Toast.LENGTH_SHORT).show();
            }
            System.out.println("Response = " + strres);

            // username.setText("");
            // password.setText("");// clear text box
        } catch (ClientProtocolException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public String convertStreamToString(InputStream inputStream)
            throws IOException {
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                inputStream.close();
            }
            return sb.toString();
        } else {
            return "";
        }

    }

    public class GetAccess extends AsyncTask<String, String, String> {
        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(Signin.this);
            dialog.setTitle("Please wait");
            dialog.setMessage("Getting login access");
            dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            getLogin();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dialog.dismiss();
            setSession();
            loadList();

            // System.out.println(result);

        }

        private void setSession() {
            SharedPreferences preferences = getSharedPreferences("CurrentUser",
                    MODE_WORLD_READABLE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("Save", edt_mail.getText().toString());
            editor.putString("Save1", edt_password.getText().toString());
            editor.putString("Save2", strres.toString().trim());
            System.out.println("Response = " + strres);

            editor.commit();
            edt_mail.setText("");
            edt_password.setText("");

        }
    }

}

注意:此代码在 android 2.3 模拟器和设备中完美运行。但是当我在 android 4.0 或更高版本中运行此代码时。它给我强制关闭错误。请帮忙解决这个问题。在 logcat 中,它显示 android.os.NetworkOnMainThreadException 错误。我该如何解决这个问题。???

最佳答案

您的错误会自行解释...

在旧版本的 AndroidOS 中,您可以在 UI 线程上运行网络,如果超时,将导致您的应用停止响应。为了解决这个问题,较新版本的 Android 不再支持在 UI 线程上运行网络请求,您现在需要在 Threads 或 AsyncTasks 中执行。

这一行: HttpResponse httpResponse = httpclient.execute(httppost); 需要处于未运行 UI 的线程中。

new Thread(){
    public void run(){
        //TODO Run network requests here.
        getLogin();
    }
}.start();

为什么会这样……Android 运行的东西可以称为 WatchDog,通俗地说,它是将您的代码链接到 Android 的代码的一部分。这个计时器会经常与您的应用程序和操作系统通信,以确保一切正常运行并且没有任何崩溃。如果您在 UI 线程(与运行 WatchDog 计时器的线程相同)上运行网络请求,并且您的响应超时,它将锁定您的整个应用,导致它停止与 Android 通信。

关于android 4.0 中的 android.os.NetworkOnMainThreadException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579906/

相关文章:

java - Spring Boot Gradle 插件无法与 Eclipse 一起使用

java - 导出的 Eclipse 代码格式首选项;在另一台计算机上导入但格式仍然不同

java - Tomcat 无法找到请求的资源,尽管它存在

android - 如何在 COCOS2d Android 中使用 CClistview?

android - Gradle 可以使用已编译的 Android APK 作为依赖项吗?

android - monodroid expandablelistview.itemclick 不会被 customview c# 调用

android - MediaStore.Playlists.Members.moveItem 的替代品

javascript - 单击事件未触发并溢出 : scroll

java - JUnit Eclipse 插件?

java - 让Eclipse识别普通源文件和测试源文件的区别