3

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

  1. 加载应用程序时,用户界面需要大约 3 - 6 秒才能出现......它只显示标题

  2. 我有一个进度条视图,我在加载下一张图片时使其可见......永远不会变得可见。

  3. 当您单击下一个或上一个按钮时,该按钮将保持按下状态,直到它加载

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

主要的.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;
        }
    }
}
4

1 回答 1

3

看起来您正在主 UI 线程上进行网络连接,例如:checkForUpdates()。建立网络连接应该在后台线程的帮助下完成。AsyncTask 将使您更轻松。现在,事实上,您正在捆绑您的 UI 线程,这会在您的 UI 中产生“滞后”问题。

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

于 2012-07-11T03:37:17.103 回答