代码之家  ›  专栏  ›  技术社区  ›  ibad ur rahman

Android AsyncTask类挂起了我的应用程序为什么?

  •  -1
  • ibad ur rahman  · 技术社区  · 6 年前

    我在应用程序的Mainactivity类的onCreate()中调用myTask().execute()。它很忙,或者把我的申请挂了很长时间。请帮帮我为什么?我希望我的工作在后台,这样它就不会干扰我的应用程序。为什么我的应用程序变得繁忙和无响应? 分类代码如下:

     private class MyTask extends AsyncTask<String, Integer, String> {
    
        // Runs in UI before background thread is called
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
    
            // Do something like display a progress bar
        }
    
        // This is run in a background thread
        @Override
        protected String doInBackground(String... params) {
    
    
            checkUser();
    
            return "";
        }
    
        // This is called from background thread but runs in UI
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
    
            // Do things like update the progress bar
        }
    
        // This runs in UI when background thread finishes
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Do things like hide the progress bar or change a TextView
        }
    }
    

    checkuser()方法代码如下

     private void checkUser(){
    
        // now here we convert this list array into json string
    
    
        final String server_url="http://www.xxxx.com/TruCaller/check_user.php"; // url of server check this 100 times it must be working
    
    
    
        // volley
    
        StringRequest stringRequest=new StringRequest(Request.Method.POST, server_url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response)
                    {
    
                        final String result=response.toString().trim();
                        if(result.equals("not found")){
                            //Toast.makeText(MainActivity.this,"Wait...",Toast.LENGTH_LONG).show();
                         //   Log.d("responsedd", "result not found fffffffff: "+result);
                            getContacts2();
                        }else{
    
                        }
                       // Log.d("responsedd", "result : "+result); //when response come i will log it
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        error.printStackTrace();
                        error.getMessage(); // when error come i will log it
                    }
                }
        )
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
    
                params.put("identifier", UIDD);
    
                Log.d("responsedd", "result not found ggggggggggg: "+ UIDD);
                return params;
            }
        };
        Vconnection.getnInstance(this).addRequestQue(stringRequest); // vConnection i claas which used to connect volley
    
    
    }
    

    getContacts2()方法代码如下:

      public void getContacts2() {
    
        if (!mayRequestContacts()) {
            return;
        }
    
       // contactList = new ArrayList<String>();
    
        String phoneNumber = null;
        String email = null;
    
        Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
        String _ID = ContactsContract.Contacts._ID;
        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
        String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
    
        Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
        String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
    
        Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
        String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
        String DATA = ContactsContract.CommonDataKinds.Email.DATA;
    
        StringBuffer output;
    
        ContentResolver contentResolver = getContentResolver();
    
        cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
    
        // Iterate every contact in the phone
        if (cursor.getCount() > 0) {
    
            counter = 0;
            while (cursor.moveToNext()) {
                output = new StringBuffer();
    
    
                String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
                String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
                String phoneC = "", adressC = "", emailC = "",country_code="";
                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
                Bitmap bitmap = null;
                String image = "";
                if (hasPhoneNumber > 0) {
    
    
    
    
                    ////////////////////Phone numbers with this name..... 2 Testing ....////////////////
                    String phoneNumber2 = "";
                    final String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE,};
                    final Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contact_id)}, null);
    
                    if (phone.moveToFirst()) {
                        final int contactNumberColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
                        phoneC = "";
                        while (!phone.isAfterLast()) {
                            ////////////////////////////////////////////
    
                            String x = phone.getString(contactNumberColumnIndex);
                            bitmap = retrieveContactPhoto(MainActivity.this, x);
                            String countryCode = countryCode(phone.getString(contactNumberColumnIndex));
                            country_code = countryCode;
                            // String swissNumberStr = "03348633664";
                            PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(getApplicationContext());
                            Phonenumber.PhoneNumber pNumberProto;
                            String phoneVerfid="";
                            try {
                                pNumberProto = phoneUtil.parse(phone.getString(contactNumberColumnIndex), countryCode);
                             //   System.err.println("NumberParseException was thrown:>>>>>>>>>>>> " + pNumberProto);
                                boolean isValid = phoneUtil.isValidNumber(pNumberProto);
                                if(isValid){
                                    System.out.println(phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
                                    phoneVerfid = phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
                                }
                            } catch (NumberParseException e) {
                               // System.err.println("NumberParseException was thrown: " + e.toString() +"   ???" +phone.getString(contactNumberColumnIndex) + countryCode);
                            }
                            ///////////////////////////////
                            phoneNumber2 = phoneVerfid + "_";
                            //   output.append("\n Phone number:" + phoneNumber2);
                            phoneC = phoneC  + phoneNumber2;
                            //  System.out.println("Country = "+countryCode(phoneNumber2) + "  p= " +phoneNumber2);
                            phone.moveToNext();
    
                        }
    
                    }
                    phone.close();
    
    
                    /////////////////////////////////////////////////////////////
    
                    // Read every email id associated with the contact
                    Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
                    emailC = "";
                    email = "";
                    while (emailCursor.moveToNext()) {
    
                        email = emailCursor.getString(emailCursor.getColumnIndex(DATA)) + "%";
                        if (!emailC.contains(email)) {
                            emailC = emailC  + email;
                            //  output.append("\n Email:" + email);
                        }
                    }
    
                    emailCursor.close();
    
    
                    //////////// Adresss//////
    
                    String postalData = "";
                    String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
                    String[] addrWhereParams = new String[]{String.valueOf(contact_id), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
    
                    Cursor addrCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
    
                    if (addrCur.moveToFirst()) {
                        postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
                        //output.append("\n Address:" + postalData);
                        adressC = adressC + " " + postalData;
                    }
                    addrCur.close();
    
    
                }
                if (phoneC != "") {
    
                    if (bitmap != null) {
                        Bitmap bitmap1 = getResizedBitmap(bitmap,210);
                        image = getStringImage(bitmap1);
                        if(bitmap1!=null) {
                            bitmap1.recycle();
                        }
                       // System.out.println("KKKKKKKKKKKKKKKKKKK >>>>>>>>> "+image);
                    }
    
                    Contact_Details dt = new Contact_Details(name, phoneC, UIDD, country_code, image, emailC, adressC);
                    dataArray.add(dt);
                    if(bitmap!=null){ bitmap.recycle();}
    
                    image = "";
                }
    
            }
    
    
    
                    submit1User2Contacs();
    
    
    
        }
    
    }
    

    创建方法的主活动性:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    
        new MyTask().execute();}
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Kunal Parte    6 年前

        2
  •  0
  •   ibad ur rahman    6 年前

     new Thread(new Runnable(){
    
                                @Override
                                public void run() {
                                    //my method
                                    checkUser();
                                }
                            }).start();