Android应用程序加载问题

发布于 2024-12-07 08:07:47 字数 8357 浏览 1 评论 0原文

我正在 Android 2.2 上开发一个应用程序。它的主要作用是从互联网上获取数据,然后将其显示在设备的屏幕上。我已经完成了一个 Activity,但是,它太慢了,获取网页内容需要太多时间。我想让它跑得更快。我想 Async Task 将是我应该使用的最合适的方法。我尝试更改代码以插入异步任务,但我不知道如何正确执行。 这是我的代码:

package com.nextlogic.golfnews;



import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Activity1 extends Activity {

     View vw;
     ImageView im;
     Bitmap bmp; 
     URL url = null; 


    //ImageView t;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        String s="";
        String pag="";
        String aux1="";


        ArrayList<String>  pg;
        ArrayList<String>  links;
        ArrayList<String> sbt;
        TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
        String q="";
        String tt="";
        pag=getPage();
        aux1=pag.substring(pag.indexOf("\">Annonse<"),pag.indexOf("<!-- START articleListBullets -->"));        
        pg=title(aux1);
        links=urls(aux1);
        sbt=subtitle(aux1);

        ///////////////////////////////////////////////////////////////////////////
        for(int i=0; i<pg.size(); i++) {

            s = "http://www.golfnews.no/" +links.get(i);

            q=pg.get(i);
            tt=sbt.get(i);




              // create a new TableRow
            TableRow row = new TableRow(this);
            row.setBackgroundColor(Color.WHITE);
            row.setTag(i);
            row.setClickable(true);
            row.setClickable(true);
            row.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {

                      Intent myIntent = new Intent(view.getContext(), News.class);

                        startActivityForResult(myIntent, 0);
                }
            });


            // create a new TextView

            TextView fin = new TextView(this);
            vw = new View(this);
            im = new ImageView(this);
            ////////////////////////////////////

            bmp=getbmp(s);
            im.setImageBitmap(bmp);  
            vw.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
            vw.setBackgroundColor(Color.LTGRAY);

            row.addView(im, new TableRow.LayoutParams(70,30));


          q=titleEdit(q);
          tt=subtitleEdit(tt);




          //////////////////////////////////////
            fin.setText(Html.fromHtml("<b>" + q + "</b>" +  "<br />" + 
                    "<small>" + tt + "</small>"));
           row.addView(fin);
            tableView.addView(vw);
            tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        }
        }

    public Bitmap getbmp(String s)
    {
        Bitmap bmp = null;
        try{ 
            url = new URL(s); 
            } 
            catch(MalformedURLException e) 
            { 
                    e.printStackTrace(); 
            } 
            try{ 
                    HttpURLConnection conn =  (HttpURLConnection)url.openConnection(); 
                    conn.setDoInput(true); 
                    conn.connect(); 
                    InputStream is = conn.getInputStream(); 
                    bmp = BitmapFactory.decodeStream(is); 

                    } catch (IOException e) 
                    { 
                            e.printStackTrace(); 
                    } 
            return bmp;
    }

    public String titleEdit(String q)
    {
        if(q.length()>33)
         {
             String q1 = q.substring(0,33);
             String q2 = q.substring(33);
             q =q1 + "<br />" +q2;
         }
        return q;
    }
    public String subtitleEdit(String tt)
    {
         if(tt.length()>40)
         {
             String tt1 = tt.substring(0,40);
             String tt2 = tt.substring(40);
             if(tt2.length()>42)
             {
                 String z1 = tt2.substring(0,40);
                 String z2 = tt2.substring(40);
                 if(z2.length()>42)
                 {
                     String z21 = z2.substring(0,40);
                     String z22 = z2.substring(40);
                     z2=z21+"<br />"+z22;
                 }
                 tt2=z1+"<br />"+z2;
             }
             tt = "<br />"+tt1 + "<br />" +tt2;
         }

        return tt;
    }
    private  ArrayList<String> title (String trax)
    {

        ArrayList<String> result= new ArrayList<String>(); 
        int ok=1;
        int s1,s2;
        while(ok==1)
        {
            //System.out.println("INDEX = "+trax.indexOf("alt="));
            ok=0;
            if((trax.indexOf("alt=")!=-1&&trax.indexOf("\"/>")!=-1)&&((trax.indexOf("alt=")<trax.indexOf("\"/>"))))
            {


            ok=1;
            s1 =trax.indexOf("alt=");
            s2 = trax.indexOf("\"/>");
        //System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
            result.add(trax.substring(s1+5,s2));
        //  i++;
            trax = trax.substring(s2 + 3);

            }

        }
         return result;
    }
    private  ArrayList<String> subtitle (String trax)
    {

        ArrayList<String> result= new ArrayList<String>(); 
        int ok=1;
        int s1,s2;
        while(ok==1)
        {

            ok=0;
            if(trax.indexOf("<p>")!=-1)
            {


            ok=1;
            s1 =trax.indexOf("<p>");
            s2 = trax.indexOf(")");
            //System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
            result.add(trax.substring(s1+3,s2+1));
            trax = trax.substring(s2+1 );

            }

        }
         return result;
    }
    private  ArrayList<String> urls (String trax)
    {

        ArrayList<String> result= new ArrayList<String>(); 
        int ok=1;
        int s1,s2;
        while(ok==1)
        {
            //System.out.println("INDEX = "+trax.indexOf("alt="));
            ok=0;
            if((trax.indexOf("<img src")!=-1&&trax.indexOf("alt=\"")!=-1)&&((trax.indexOf("<img src")<trax.indexOf("alt=\""))))
            {


            ok=1;
            s1 =trax.indexOf("<img src");
            s2 = trax.indexOf("alt=\"");
      //  System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
            result.add(trax.substring(s1+10,s2-2));
        //  i++;
            trax = trax.substring(s2 + 6);

            }

        }
         return result;
    }
        private String getPage() {
            String str = "***";

            try
            {
                HttpClient hc = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://golfnews.no/nyheter.php");
                HttpResponse rp = hc.execute(post);

                if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                {
                    str = EntityUtils.toString(rp.getEntity());
                }
            }catch(IOException e){
                e.printStackTrace();
            }  

            return str;
        }


}

该 Activity 加载时间太长。(大约 10 秒)。那么,您能帮我弄清楚在哪里以及如何插入异步任务吗?或者也许您可以建议我其他一些东西来使应用程序运行得更快?例如像处理程序之类的东西?由于我是 Android 编程新手,所以我真的不太了解。任何建议将不胜感激。谢谢。

I am developing an application on Android 2.2 . Mainly what it does , is that it grab data from the internet and then it shows it on the device's screen. I have finished an Activity , but , it is too slow , it takes too much to get the web content . I would like to make it run faster . I guess that Async Task would be the most appropriate method that I should use . I've tried to change the code , to insert the Async Task but I cant figure out how to do it right .
This is my code :

package com.nextlogic.golfnews;



import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Activity1 extends Activity {

     View vw;
     ImageView im;
     Bitmap bmp; 
     URL url = null; 


    //ImageView t;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        String s="";
        String pag="";
        String aux1="";


        ArrayList<String>  pg;
        ArrayList<String>  links;
        ArrayList<String> sbt;
        TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
        String q="";
        String tt="";
        pag=getPage();
        aux1=pag.substring(pag.indexOf("\">Annonse<"),pag.indexOf("<!-- START articleListBullets -->"));        
        pg=title(aux1);
        links=urls(aux1);
        sbt=subtitle(aux1);

        ///////////////////////////////////////////////////////////////////////////
        for(int i=0; i<pg.size(); i++) {

            s = "http://www.golfnews.no/" +links.get(i);

            q=pg.get(i);
            tt=sbt.get(i);




              // create a new TableRow
            TableRow row = new TableRow(this);
            row.setBackgroundColor(Color.WHITE);
            row.setTag(i);
            row.setClickable(true);
            row.setClickable(true);
            row.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {

                      Intent myIntent = new Intent(view.getContext(), News.class);

                        startActivityForResult(myIntent, 0);
                }
            });


            // create a new TextView

            TextView fin = new TextView(this);
            vw = new View(this);
            im = new ImageView(this);
            ////////////////////////////////////

            bmp=getbmp(s);
            im.setImageBitmap(bmp);  
            vw.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
            vw.setBackgroundColor(Color.LTGRAY);

            row.addView(im, new TableRow.LayoutParams(70,30));


          q=titleEdit(q);
          tt=subtitleEdit(tt);




          //////////////////////////////////////
            fin.setText(Html.fromHtml("<b>" + q + "</b>" +  "<br />" + 
                    "<small>" + tt + "</small>"));
           row.addView(fin);
            tableView.addView(vw);
            tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        }
        }

    public Bitmap getbmp(String s)
    {
        Bitmap bmp = null;
        try{ 
            url = new URL(s); 
            } 
            catch(MalformedURLException e) 
            { 
                    e.printStackTrace(); 
            } 
            try{ 
                    HttpURLConnection conn =  (HttpURLConnection)url.openConnection(); 
                    conn.setDoInput(true); 
                    conn.connect(); 
                    InputStream is = conn.getInputStream(); 
                    bmp = BitmapFactory.decodeStream(is); 

                    } catch (IOException e) 
                    { 
                            e.printStackTrace(); 
                    } 
            return bmp;
    }

    public String titleEdit(String q)
    {
        if(q.length()>33)
         {
             String q1 = q.substring(0,33);
             String q2 = q.substring(33);
             q =q1 + "<br />" +q2;
         }
        return q;
    }
    public String subtitleEdit(String tt)
    {
         if(tt.length()>40)
         {
             String tt1 = tt.substring(0,40);
             String tt2 = tt.substring(40);
             if(tt2.length()>42)
             {
                 String z1 = tt2.substring(0,40);
                 String z2 = tt2.substring(40);
                 if(z2.length()>42)
                 {
                     String z21 = z2.substring(0,40);
                     String z22 = z2.substring(40);
                     z2=z21+"<br />"+z22;
                 }
                 tt2=z1+"<br />"+z2;
             }
             tt = "<br />"+tt1 + "<br />" +tt2;
         }

        return tt;
    }
    private  ArrayList<String> title (String trax)
    {

        ArrayList<String> result= new ArrayList<String>(); 
        int ok=1;
        int s1,s2;
        while(ok==1)
        {
            //System.out.println("INDEX = "+trax.indexOf("alt="));
            ok=0;
            if((trax.indexOf("alt=")!=-1&&trax.indexOf("\"/>")!=-1)&&((trax.indexOf("alt=")<trax.indexOf("\"/>"))))
            {


            ok=1;
            s1 =trax.indexOf("alt=");
            s2 = trax.indexOf("\"/>");
        //System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
            result.add(trax.substring(s1+5,s2));
        //  i++;
            trax = trax.substring(s2 + 3);

            }

        }
         return result;
    }
    private  ArrayList<String> subtitle (String trax)
    {

        ArrayList<String> result= new ArrayList<String>(); 
        int ok=1;
        int s1,s2;
        while(ok==1)
        {

            ok=0;
            if(trax.indexOf("<p>")!=-1)
            {


            ok=1;
            s1 =trax.indexOf("<p>");
            s2 = trax.indexOf(")");
            //System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
            result.add(trax.substring(s1+3,s2+1));
            trax = trax.substring(s2+1 );

            }

        }
         return result;
    }
    private  ArrayList<String> urls (String trax)
    {

        ArrayList<String> result= new ArrayList<String>(); 
        int ok=1;
        int s1,s2;
        while(ok==1)
        {
            //System.out.println("INDEX = "+trax.indexOf("alt="));
            ok=0;
            if((trax.indexOf("<img src")!=-1&&trax.indexOf("alt=\"")!=-1)&&((trax.indexOf("<img src")<trax.indexOf("alt=\""))))
            {


            ok=1;
            s1 =trax.indexOf("<img src");
            s2 = trax.indexOf("alt=\"");
      //  System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length());
            result.add(trax.substring(s1+10,s2-2));
        //  i++;
            trax = trax.substring(s2 + 6);

            }

        }
         return result;
    }
        private String getPage() {
            String str = "***";

            try
            {
                HttpClient hc = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://golfnews.no/nyheter.php");
                HttpResponse rp = hc.execute(post);

                if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                {
                    str = EntityUtils.toString(rp.getEntity());
                }
            }catch(IOException e){
                e.printStackTrace();
            }  

            return str;
        }


}

The Activity takes too much time to load .(About 10 seconds) . So please , can you help me figure out where and how to insert the Async Task ? Or maybe you can suggest me something else to make the application run faster ? Something like a handler for example ? I don't really know much since I am new to Android programming . Any advice would be much appreciated . Thanks.

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

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

发布评论

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

评论(1

栖迟 2024-12-14 08:07:47

1)你需要改进你的代码风格
2) 为此,您必须使用AsynchTask或Handler+Separate Thread
<一href="http://www.google.com/search?hl=en&client=opera&hs=0Ra&rls=en&channel=suggest&q=android%20Handler%20Thread%20%20tutorial&o q=android%20Handler%20Thread%20%20tutorial&aq=f&aqi=g1&aql=1&gs_sm=e&gs_upl=33519l46294l0l47086l19l17l0l2l0l6l395l2972l0.9.5.1l15l0" rel="nofollow">1,2

1) You need improve your code style
2) For such purposes you must use AsynchTask or Handler+Separate Thread
1,2

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