AsyncTask 启动 Android 需要很长时间

发布于 2024-12-03 17:10:12 字数 6671 浏览 0 评论 0原文

AM 使用 AsyncTask 从服务中检索数据。但它花费了太多时间,即大约2分钟左右..

我发现,当我启动异步任务时,对话框显示正在显示,但后台进程需要时间来响应和获取数据。

检查我的asynctask代码:

 public class JamsTask extends AsyncTask<Void,Void,Bundle> 
     { 


            private Context ctx; 
            ProgressDialog dlg;
            Bitmap userImage;
            String message ;

            public JamsTask(Context context) { 
                ctx = context; 
            } 

            @Override 
            protected void onPreExecute() { 
                //super.onPreExecute(); 
           try{
                dlg = new ProgressDialog(Jams.this); 
                dlg.setMessage("Please wait...."); 
                dlg.show();
           }catch (Exception e) {
            // TODO: handle exception
        }


                //setContentView(R.layout.splash);
            } 


            @Override
            protected Bundle doInBackground(Void... params) {
                   Bundle b=new Bundle();



                try{

                 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);



                 request.addProperty("fkPersonId", Integer.valueOf(JujamaMain.userValues.get(0)));
                 request.addProperty("fkConferenceId", Integer.valueOf(JujamaMain.userValues.get(4)));
                 request.addProperty("startIndex",1);
                 request.addProperty("endIndex",20);



                   SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                   envelope.dotNet=true;
                   envelope.setOutputSoapObject(request);

                   HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                   androidHttpTransport.call(SOAP_ACTION, envelope);

                   Object result= envelope.getResponse(); 

                   SoapObject response=(SoapObject)envelope.bodyIn;



                  strRes = result.toString();





                  SoapObject returnObj = (SoapObject)response.getProperty("GetAllStatusUpdatesResult");

                  SoapObject object=(SoapObject) returnObj.getProperty(1);


                  SoapObject returnObj2 = (SoapObject)object.getProperty("NewDataSet");



                 // Integer id = Integer.valueOf(returnObj.getPropertySafelyAsString("id");


                  for(int i=0;i<returnObj2.getPropertyCount();i++) {
                      SoapObject persondetails = (SoapObject)returnObj2.getProperty(i);



                      String salution = (String)persondetails.getPropertySafelyAsString("Salutation","");
                      //String companyname = (String)persondetails.getPropertySafelyAsString("CompanyName");
                      String firstname = (String)persondetails.getPropertySafelyAsString("FirstName","");

                      String lastname = (String)persondetails.getPropertySafelyAsString("LastName","");



                     if(!persondetails.getPropertySafelyAsString("Message","").contains("anyType"))
                        message = (String)persondetails.getPropertySafelyAsString("Message","");
                     else
                         message=""
;                     
                      String nameID = (String)persondetails.getPropertySafelyAsString("PKStatusID","");




                      String fkconfid = (String)persondetails.getPropertySafelyAsString("FKConferenceID","");





                  try{   

                     SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                      java.util.Date date = null;
                      String sub=commented.substring(0, 19);

                       date = form.parse(sub);


                      SimpleDateFormat postFormater =new SimpleDateFormat("MMMMM dd, yyyy, HH:mm");
                      String newDateStr = postFormater.format(date);

                      mTimedifference.add(newDateStr);


                   /* DateTime myBirthDate = new DateTime(year,month, day, hour, minute, 0, 0);
                      DateTime now = new DateTime();
                      Period period = new Period(myBirthDate, now);

                      PeriodFormatter formatter = new PeriodFormatterBuilder()
                          .appendYears().appendSuffix(" years, ")
                          .appendMonths().appendSuffix(" months, ")
                          .appendWeeks().appendSuffix(" weeks, ")
                          .appendDays().appendSuffix(" days, ")
                          .appendHours().appendSuffix(" hours, ")
                          .appendMinutes().appendSuffix(" minutes, ")

                          .printZeroNever()
                          .toFormatter();

                      String elapsed = formatter.print(period);
                      System.out.println(elapsed + " ago");*/

                  }catch (Exception e) {
                    // TODO: handle exception
                      e.printStackTrace();

                }

                     // System.out.println(".."+"dat"+now+"..."+time);
                      mNameID.add(nameID);


                      String ImageUrl = (String)persondetails.getPropertySafelyAsString("PhotoGuid","");

                      String liked = (String)persondetails.getPropertySafelyAsString("Liked","No");
                      String nocomments = (String)persondetails.getPropertySafelyAsString("NoofComments","0");

                      mName.add(firstname.toString()+lastname.toString()+salution.toString());
                      mMessages.add(message.toString());
                      mLikesCount.add(likescount.toString());



                         mLikeText.add(liked);
                         mNoComments.add(nocomments);




                         userImage=getBitmapFromURL("http://test.jujama.com/uploadfiles/"+ImageUrl);

                      Bitmap bmp=BitmapFactory.decodeResource(getResources(),R.drawable.nophoto);

                      if(userImage==null)
                             mUserImage.add(bmp);
                         else
                          mUserImage.add(userImage);


                  }




                } catch (Exception e) {
                    e.printStackTrace();

                }

                return b;
            }    





              @Override 
                protected void onPostExecute(Bundle b) { 

                 dlg.dismiss(); 

                 lv.setAdapter(new Viewadapter(Jams.this));





              }

         } 

有什么办法可以减少时间。因为时间太多了。

还有一个:

在开始之前:以下类型的线路即将到来。

 GC_FOR_MALLOC freed 31921 objects / 2006888 bytes in 100ms

谢谢

AM using AsyncTask to retrieve data from services. but it taking too much time i.e., about 2 mins or so ..

I found out that, when i start the asynctask the dialog show is showing but background process taking time to respond and getting data.

Check my code of asynctask:

 public class JamsTask extends AsyncTask<Void,Void,Bundle> 
     { 


            private Context ctx; 
            ProgressDialog dlg;
            Bitmap userImage;
            String message ;

            public JamsTask(Context context) { 
                ctx = context; 
            } 

            @Override 
            protected void onPreExecute() { 
                //super.onPreExecute(); 
           try{
                dlg = new ProgressDialog(Jams.this); 
                dlg.setMessage("Please wait...."); 
                dlg.show();
           }catch (Exception e) {
            // TODO: handle exception
        }


                //setContentView(R.layout.splash);
            } 


            @Override
            protected Bundle doInBackground(Void... params) {
                   Bundle b=new Bundle();



                try{

                 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);



                 request.addProperty("fkPersonId", Integer.valueOf(JujamaMain.userValues.get(0)));
                 request.addProperty("fkConferenceId", Integer.valueOf(JujamaMain.userValues.get(4)));
                 request.addProperty("startIndex",1);
                 request.addProperty("endIndex",20);



                   SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                   envelope.dotNet=true;
                   envelope.setOutputSoapObject(request);

                   HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                   androidHttpTransport.call(SOAP_ACTION, envelope);

                   Object result= envelope.getResponse(); 

                   SoapObject response=(SoapObject)envelope.bodyIn;



                  strRes = result.toString();





                  SoapObject returnObj = (SoapObject)response.getProperty("GetAllStatusUpdatesResult");

                  SoapObject object=(SoapObject) returnObj.getProperty(1);


                  SoapObject returnObj2 = (SoapObject)object.getProperty("NewDataSet");



                 // Integer id = Integer.valueOf(returnObj.getPropertySafelyAsString("id");


                  for(int i=0;i<returnObj2.getPropertyCount();i++) {
                      SoapObject persondetails = (SoapObject)returnObj2.getProperty(i);



                      String salution = (String)persondetails.getPropertySafelyAsString("Salutation","");
                      //String companyname = (String)persondetails.getPropertySafelyAsString("CompanyName");
                      String firstname = (String)persondetails.getPropertySafelyAsString("FirstName","");

                      String lastname = (String)persondetails.getPropertySafelyAsString("LastName","");



                     if(!persondetails.getPropertySafelyAsString("Message","").contains("anyType"))
                        message = (String)persondetails.getPropertySafelyAsString("Message","");
                     else
                         message=""
;                     
                      String nameID = (String)persondetails.getPropertySafelyAsString("PKStatusID","");




                      String fkconfid = (String)persondetails.getPropertySafelyAsString("FKConferenceID","");





                  try{   

                     SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                      java.util.Date date = null;
                      String sub=commented.substring(0, 19);

                       date = form.parse(sub);


                      SimpleDateFormat postFormater =new SimpleDateFormat("MMMMM dd, yyyy, HH:mm");
                      String newDateStr = postFormater.format(date);

                      mTimedifference.add(newDateStr);


                   /* DateTime myBirthDate = new DateTime(year,month, day, hour, minute, 0, 0);
                      DateTime now = new DateTime();
                      Period period = new Period(myBirthDate, now);

                      PeriodFormatter formatter = new PeriodFormatterBuilder()
                          .appendYears().appendSuffix(" years, ")
                          .appendMonths().appendSuffix(" months, ")
                          .appendWeeks().appendSuffix(" weeks, ")
                          .appendDays().appendSuffix(" days, ")
                          .appendHours().appendSuffix(" hours, ")
                          .appendMinutes().appendSuffix(" minutes, ")

                          .printZeroNever()
                          .toFormatter();

                      String elapsed = formatter.print(period);
                      System.out.println(elapsed + " ago");*/

                  }catch (Exception e) {
                    // TODO: handle exception
                      e.printStackTrace();

                }

                     // System.out.println(".."+"dat"+now+"..."+time);
                      mNameID.add(nameID);


                      String ImageUrl = (String)persondetails.getPropertySafelyAsString("PhotoGuid","");

                      String liked = (String)persondetails.getPropertySafelyAsString("Liked","No");
                      String nocomments = (String)persondetails.getPropertySafelyAsString("NoofComments","0");

                      mName.add(firstname.toString()+lastname.toString()+salution.toString());
                      mMessages.add(message.toString());
                      mLikesCount.add(likescount.toString());



                         mLikeText.add(liked);
                         mNoComments.add(nocomments);




                         userImage=getBitmapFromURL("http://test.jujama.com/uploadfiles/"+ImageUrl);

                      Bitmap bmp=BitmapFactory.decodeResource(getResources(),R.drawable.nophoto);

                      if(userImage==null)
                             mUserImage.add(bmp);
                         else
                          mUserImage.add(userImage);


                  }




                } catch (Exception e) {
                    e.printStackTrace();

                }

                return b;
            }    





              @Override 
                protected void onPostExecute(Bundle b) { 

                 dlg.dismiss(); 

                 lv.setAdapter(new Viewadapter(Jams.this));





              }

         } 

Is there any way to reduce the time . because its too much time.

and one more:

bfore it starts:this below types of lines are coming .

 GC_FOR_MALLOC freed 31921 objects / 2006888 bytes in 100ms

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纸短情长 2024-12-10 17:10:12

从你的代码中很难看出为什么它这么慢。我相信,最好的猜测是您正在执行两个网络请求(其中一次是获取图像)。可能是您的服务速度非常慢。

您上面发布的日志行意味着您正在分配内存。如果你正在做一些内存密集型的事情,你可能会看到很多这样的东西。

也可能有很多其他线程正在运行,并且 AsyncTask 线程的优先级低于其他线程,然后基本上被它们阻塞。尝试提高其优先级(不知道该怎么做)或仔细查看代码中的其他线程。

It is hard to tell why from looking at your code why it is so slow. The best guess would be that you are, I believe, doing two web requests (once of which is fetching an image). It could be that your services are just very slow.

The log lines you posted above mean you are allocating memory. If you are doing something memory intensive you can expect to see a lot of them.

It is also possible that you have a lot of other threads going and the AsyncTask thread has lower priority than the other threads and is then essentially blocked by them. Try raising its priority (no idea how to do) or carefully look at the other threads in your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文