其他分享
首页 > 其他分享> > Android应用程式-应用程式可运作,但运作缓慢

Android应用程式-应用程式可运作,但运作缓慢

作者:互联网

这是我的第一个正式且已完成的应用程序…或者所以我想…这是我的一些问题(我也会发布代码):

>加载应用程序时,ui出现大约需要3-6秒的时间…它所显示的只是标题
>我有一个进度条视图,在加载下一张图片时我可以看到它……永远都不会变得可见.
>当您单击下一个或上一个按钮时,该按钮将保持按下状态,直到加载为止

这些问题使我发疯…谁能指出正确的方向

Main.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/widget210"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp" 
        android:layout_weight="1">
        <ImageView
            android:id="@+id/ImageView01"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
        <ProgressBar
            android:indeterminate="true"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleLarge" />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:text="Medium Text "
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#88ffffff"
            android:background="#88000000" android:gravity="center"/>
    </RelativeLayout>
    <TableLayout
        android:id="@+id/widget214"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TableRow
            android:id="@+id/widget215"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button
                android:id="@+id/Previous"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:text="Previous" 
                android:onClick="GetPrevPic"/>
            <Button
                android:id="@+id/Next"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:text="Next" 
                android:onClick="GetNextPic"/>
        </TableRow>
    </TableLayout>
    <com.google.ads.AdView
        android:id="@+id/adView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="xxxxxxxxxxxxxxx"
        ads:loadAdOnCreate="true"/>
</LinearLayout>

爪哇

package com.ndai.funnys;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.google.ads.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.*;


public class GuysFunnysActivity extends Activity 
{
    String xml;
    Document doc;
    NodeList nodes;
    int iIndex = 0;
    int iTotal = 0;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GetXMLStuff();
        GetPic();
        CheckForUpdates();
        CheckForReferral();
    }
    public void GetXMLStuff()
    {
        xml = XMLfunctions.getXML();
        doc = XMLfunctions.XMLfromString(xml);
        nodes = doc.getElementsByTagName("item");
        iTotal = nodes.getLength();
    }
    public void CheckForReferral()
    {
        SharedPreferences settings = getSharedPreferences("GuysFunnys", 0);
        SharedPreferences.Editor editor = settings.edit();
        long loads = settings.getLong("Loads", 0);
        if (loads % 50 == 0)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Thank you for using Guy's Funnys. Our app is only know to those who use it (it isn't in the Play Store). Please send a link for it to your friends. Send link now?")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
                {
                    public void onClick(DialogInterface dialog, int id) 
                    {
                        Intent ii=new Intent(android.content.Intent.ACTION_SEND);
                        ii.setType("text/plain");
                        ii.putExtra(Intent.EXTRA_SUBJECT, "Share Guy's Funnys App");
                        ii.putExtra(Intent.EXTRA_TEXT, "I wanted to share this cool app with you - Guy's Funnys - https://sites.google.com/site/guysfunnysapp/Guys%20Funnys.apk");
                        startActivity(Intent.createChooser(ii, "Share Guy's Funnys App"));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() 
                {
                    public void onClick(DialogInterface dialog, int id) 
                    {
                        dialog.cancel();
                    }
                });
            AlertDialog alert = builder.create();
            alert.show();
        }
        editor.putLong("Loads",(loads + 1));
        editor.commit();
    }
    public void CheckForUpdates()
    {
        PackageInfo pInfo;
        try 
        {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            int s = pInfo.versionCode;
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("https://sites.google.com/site/guysfunnysapp/appversion.txt");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String line = EntityUtils.toString(httpEntity);
            if (Long.valueOf(line) > s)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("A new verison of Guy's Funnys is ready to download. The older verisons will not work. Download Now?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() 
                    {
                        public void onClick(DialogInterface dialog, int id) 
                        {
                            Update("https://sites.google.com/site/guysfunnysapp/Guys%20Funnys.apk");
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() 
                    {
                        public void onClick(DialogInterface dialog, int id) 
                        {
                            finish();
                        }
                    });
                AlertDialog alert = builder.create();
                alert.show();
            }
        } 
        catch (NameNotFoundException e) 
        {
            e.printStackTrace();
        } 
        catch (ClientProtocolException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    public void Update(String apkurl)
    {
        try 
        {
            URL url = new URL(apkurl);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            String PATH = Environment.getExternalStorageDirectory() + "/download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "app.apk");
            FileOutputStream fos = new FileOutputStream(outputFile);
            InputStream is = c.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) 
            {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
            startActivity(intent);  
        } 
        catch (IOException e) 
        {
            Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
        }
    }  
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(1, 1, 0, "View Page").setIcon(R.drawable.pageico);
        menu.add(1, 2, 1, "Share Pic").setIcon(R.drawable.shareico);
        menu.add(1, 3, 2, "Share App").setIcon(R.drawable.shareico);
        menu.add(1, 4, 2, "Exit").setIcon(R.drawable.exitico);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        Element e = (Element)nodes.item(iIndex);
        switch(item.getItemId())
        {
            case 1:
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(XMLfunctions.getValue(e, "link")));
                startActivity(browserIntent);
                return true;
            case 2:
                Intent i=new Intent(android.content.Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "Guy's Funnys");
                i.putExtra(Intent.EXTRA_TEXT, XMLfunctions.getValue(e, "guid"));
                startActivity(Intent.createChooser(i, "Guy's Funnys"));
                return true;
            case 3:
                Intent ii=new Intent(android.content.Intent.ACTION_SEND);
                ii.setType("text/plain");
                ii.putExtra(Intent.EXTRA_SUBJECT, "Share Guy's Funnys App");
                ii.putExtra(Intent.EXTRA_TEXT, "I wanted to share this cool app with you - Guy's Funnys - https://sites.google.com/site/guysfunnysapp/Guys%20Funnys.apk");
                startActivity(Intent.createChooser(ii, "Share Guy's Funnys App"));
                return true;
            case 4:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    public void GetNextPic(View view)
    {
        iIndex++;
        if (iIndex == iTotal)
        {
            iIndex--;
            Toast.makeText(this, "At last photo", Toast.LENGTH_LONG).show(); 
        }
        else
        {
            GetPic();
            AdView adView = (AdView)this.findViewById(R.id.adView);
            adView.loadAd(new AdRequest());
        }
    }
    public void GetPrevPic(View view)
    {
        iIndex--;
        if (iIndex == -1)
        {
            iIndex++;
            Toast.makeText(this, "At first photo", Toast.LENGTH_LONG).show(); 
        }
        else
        {
            GetPic();
            AdView adView = (AdView)this.findViewById(R.id.adView);
            adView.loadAd(new AdRequest());
        }
    }
    public void ShowDebug(View v)
    {
    }   
    public void GetPic()
    {
        ProgressBar progressBar = (ProgressBar) this.findViewById(R.id.progressBar1);
        progressBar.setVisibility(View.VISIBLE);
        ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
        TextView txtView =(TextView)findViewById(R.id.textView1);
        if (iTotal==0)
        {
            txtView.setText("Network Error");
            Toast.makeText(this, "Error connecting to server. Try again later", Toast.LENGTH_LONG).show();
        }
        else
        {
            Element e = (Element)nodes.item(iIndex);
            txtView.setText(XMLfunctions.getValue(e, "title"));
            Drawable drawable = LoadImageFromWebOperations(XMLfunctions.getValue(e, "guid"));
            imgView.setImageDrawable(drawable);
        }
        progressBar.setVisibility(View.INVISIBLE);
    }
    private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e) 
        {
            System.out.println("Exc="+e);
            return null;
        }
    }
}

解决方法:

看来您正在主UI线程上建立网络连接,例如:checkForUpdates().建立网络连接应该在后台线程的帮助下进行. AsyncTask将使您更轻松.就目前而言,您正在捆绑UI线程,这将导致UI出现“滞后”问题.

http://developer.android.com/reference/android/os/AsyncTask.html

标签:performance,progress-bar,android
来源: https://codeday.me/bug/20191201/2078103.html