android os network on main thread exception

2020-02-07 04:32发布

问题:

i make this code in single application working, but if join with other application , show this dialog "android os network on main thread exception"

 package com.kelompok2.bissmilahpulsa;
    import java.util.ArrayList;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import android.net.Uri;
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioGroup;
    import android.widget.TextView;

    public class coba extends Activity {
      EditText nm,nmr;
      RadioGroup prov,nom,pem;
      TextView error;
      Button ok;

      @Override

  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.mulaitransaksi);

      nm=(EditText)findViewById(R.id.et_nama);
      nmr=(EditText)findViewById(R.id.et_nomor);
      prov=(RadioGroup)findViewById(R.id.provider);
      nom=(RadioGroup)findViewById(R.id.nominal);
      error=(TextView)findViewById(R.id.error);
      pem=(RadioGroup)findViewById(R.id.pembayaran);
      ok=(Button)findViewById(R.id.btn_ok);

      ok.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View v) {
              // TODO Auto-generated method stub
              String type=null;
               String type1=null;
               String type2=null;
               switch (prov.getCheckedRadioButtonId()) 
               {
               case R.id.rb_as:
               type="As";
               break;
               case R.id.rb_axis:
               type="Axis";
               break;
               case R.id.rb_im3:
               type="Im3";
               break;
               case R.id.rb_telkomsel:
               type="Telokmsel";
               break;
               case R.id.rb_xl:
               type="Xl";
               break;
               }
               switch (nom.getCheckedRadioButtonId()) 
               {
               case R.id.rb_5:
               type1="5";
               break;
               case R.id.rb_10:
               type1="10";
               break;
               case R.id.rb_20:
               type1="20";
               break;
               case R.id.rb_50:
               type1="50";
               break;
               }
               switch (pem.getCheckedRadioButtonId()) 
               {
               case R.id.rb_cash:
               type2="Cash";
               break;
               case R.id.rb_hutang:
               type2="Hutang";
               break;
               }

              ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
              postParameters.add(new BasicNameValuePair("nama", nm.getText().toString()));
              postParameters.add(new BasicNameValuePair("nomor", nmr.getText().toString()));
              postParameters.add(new BasicNameValuePair("provider", type));
              postParameters.add(new BasicNameValuePair("nominal", type1));
              postParameters.add(new BasicNameValuePair("jenis_pembayaran", type2));
              String response = null;

              try {

                 response = CustomHttpClient.executeHttpPost("http://appmob.pusku.com/save.php", postParameters);

                 String res = response.toString();

                 res = res.trim();

                 res = res.replaceAll("\\s+","");

                 error.setText(res);

                 if (res.equals("1")) error.setText("Data Tersimpan");

                 else error.setText("Data Tersimpan Ke server");

              }

              catch (Exception e) {

                 error.setText(e.toString());

              }

              String nama1 = nm.getText().toString();
              String nama2 = nmr.getText().toString();
              String nama3 = type;
              String nama4 = type1;
              String nama5 = type2;

             String sms = nama1+"#"+nama2+"#"+nama3+"#"+nama4+"#"+nama5;

                      Intent    i = new Intent (Intent.ACTION_SENDTO,Uri.parse("sms:5556"));
                          i.putExtra("sms_body", sms);
                          startActivity(i); 

                                  nm.setText(null);
                                  nmr.setText(null);  

           }




      });

      }   
}

in permission i active that <uses-permission android:name="android.permission.INTERNET"/> and still not working

回答1:

You need to run internet activities on a thread separate from main (UI) thread, you can do that by wrapping your code in the following block:

new Thread() {
    @Override
    public void run() {
       //your code here
    }
}.start();


回答2:

Execute your Network related operation in AsyncTask

You can also refer here Android AsyncTask

public class ExcuteNetworkOperation extends AsyncTask<Void, Void, String>{

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            /**
             * show dialog
             */
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            /**
             * Do network related stuff
             * return string response.
             */
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            /**
             * update ui thread and remove dialog
             */
            super.onPostExecute(result);
        }
    }


回答3:

first method 

you can create an AsynTask .. Your code should run in background in order to be responsive.. otherwise it will show Not Responding ..

Second Method

You can create a seperate thread for it .. using multitasking.

Third 

Right the code in the onCreate after setContentView

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);


回答4:

While all of the answers posted in this thread is correct, asynctasks are not really considering to be a good tool to user for network transactions anymore. The main reasons for this is that the asynctasks are very closely tied to activities so alot issues arise like..."what happens if the activity is destroyed before the network call returns?".

If you really want to implement android best practices (and not to mention impress your fellow Android devs) then why not perform a network task in a service?

I would suggest looking at the Path FOSS project android-prioriy-queue. They make it ridiculously easy to perform task in a service.