尝试进行Http连接时应用程序关闭

时间:2012-10-26 10:12:29

标签: android forceclose

这是我的第一个Android应用程序。我发布了我用于HTTP连接的代码(不是我的,这是来自一个教程站点)。问题是当我按下按钮下载文本时,它会显示进度对话框并关闭应用程序强制。我发布了代码。

package com.example.httpconnectsample;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class Httpconnectionsample extends Activity {

private Button getImageButton;
private Button getTextButton;
private ProgressDialog progressDialog;  
private Bitmap bitmap = null;
private String text = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_httpconnectionsample);

    getImageButton = (Button)findViewById(R.id.Button01);
    getTextButton = (Button)findViewById(R.id.Button02);

    getImageButton.setOnClickListener( new OnClickListener() {

        @Override
        public void onClick(View v) {
            downloadImage("http://www.android.com/media/wallpaper    /gif/android_logo.gif");

        }
    });

    getTextButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            downloadText("http://xyz.com")
        }
    });
}


private void downloadImage(String urlStr) {
    progressDialog = ProgressDialog.show(this, "", "Fetching Image...");
    final String url = urlStr;

    new Thread() {
        public void run() {
            InputStream in = null;
            Message msg = Message.obtain();
            msg.what = 1;
            try {
                in = openHttpConnection(url);
                bitmap = BitmapFactory.decodeStream(in);
                Bundle b = new Bundle();
                b.putParcelable("bitmap", bitmap);
                msg.setData(b);
                in.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            messageHandler.sendMessage(msg);    

        }
    }.start();

}

private void downloadText(String urlStr) {
    progressDialog = ProgressDialog.show(this, "", "Fetching Text...");
    final String url = urlStr;

    new Thread () {
        public void run() {
            int BUFFER_SIZE = 2000;
            InputStream in = null;
            Message msg = Message.obtain();
            msg.what=2;
            try {
                in = openHttpConnection(url);

                InputStreamReader isr = new InputStreamReader(in);
                int charRead;
                  text = "";
                  char[] inputBuffer = new char[BUFFER_SIZE];

                      while ((charRead = isr.read(inputBuffer))>0)
                      {                    
                          //---convert the chars to a String---
                          String readString = 
                              String.copyValueOf(inputBuffer, 0, charRead);                    
                          text += readString;
                          inputBuffer = new char[BUFFER_SIZE];
                      }
                     Bundle b = new Bundle();
                        b.putString("text", text);
                        msg.setData(b);
                      in.close();

            }catch (IOException e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(msg);
        }
    }.start();

}

private InputStream openHttpConnection(String urlStr) {
    InputStream in = null;
    int resCode = -1;

    try {
        URL url = new URL(urlStr);
        URLConnection urlConn = url.openConnection();

        if (!(urlConn instanceof HttpURLConnection)) {
            throw new IOException ("URL is not an Http URL");
        }

        HttpURLConnection httpConn = (HttpURLConnection)urlConn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect(); 

        resCode = httpConn.getResponseCode();     


        if (resCode == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();                                 
        }    

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return in;
}

private Handler messageHandler = new Handler() {

    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
                /*case 1:
            ImageView img = (ImageView) findViewById(R.id.imageview01);
            img.setImageBitmap((Bitmap)(msg.getData().getParcelable("bitmap")));
            break; */
        case 2:
            TextView text = (TextView) findViewById(R.id.textview01);
            text.setText(msg.getData().getString("text"));
            break;
        }
        progressDialog.dismiss();
    }
};
}

以下是我的XML

   <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<Button
    android:id="@+id/Button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="24dp"
    android:text="Button" />

<Button
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginRight="56dp"
    android:text="Button" />

<TextView
    android:id="@+id/textview01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/Button02"
    android:layout_marginTop="39dp"

    tools:context=".Httpconnectionsample" />



</RelativeLayout>
</ScrollView>

以下是日志: -

   10-26 15:22:43.660: D/ddm-heap(23866): Got feature list request
   10-26 15:22:48.930: W/System.err(23866): java.net.SocketException: Permission denied     (maybe missing INTERNET permission)
   10-26 15:22:48.940: W/System.err(23866):     at    org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocketImpl(Native Method)
   10-26 15:22:48.945: W/System.err(23866):     at org.apache.harmony.luni.platform.OSNetworkSystem.createStreamSocket(OSNetworkSystem.java:187)
   10-26 15:22:48.945: W/System.err(23866):     at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:266)
   10-26 15:22:48.950: W/System.err(23866):     at  java.net.Socket.checkClosedAndCreate(Socket.java:889)
   10-26 15:22:48.950: W/System.err(23866):     at java.net.Socket.connect(Socket.java:1036)
   10-26 15:22:48.950: W/System.err(23866):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>  (HttpConnection.java:62)
  10-26 15:22:48.950: W/System.err(23866):  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager$ConnectionPool.getHttpConnection(HttpConnectionManager.java:145)
 10-26 15:22:48.950: W/System.err(23866):   at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionManager.getConnection(HttpConnectionManager.java:67)
 10-26 15:22:48.960: W/System.err(23866):   at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getHTTPConnection(HttpURLConnection.java:821)
 10-26 15:22:48.960: W/System.err(23866):   at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:807)
 10-26 15:22:48.965: W/System.err(23866):   at com.example.httpconnectsample.Httpconnectionsample.openHttpConnection(Httpconnectionsample.java:142)
 10-26 15:22:48.965: W/System.err(23866):   at com.example.httpconnectsample.Httpconnectionsample.access$3(Httpconnectionsample.java:126)
 10-26 15:22:48.965: W/System.err(23866):   at com.example.httpconnectsample.Httpconnectionsample$5.run(Httpconnectionsample.java:97)
 10-26 15:22:48.965: W/dalvikvm(23866): threadid=15: thread exiting with uncaught exception (group=0x4001b180)
10-26 15:22:48.995: E/AndroidRuntime(23866): Uncaught handler: thread Thread-8 exiting due to uncaught exception
10-26 15:22:49.090: E/AndroidRuntime(23866): java.lang.NullPointerException
10-26 15:22:49.090: E/AndroidRuntime(23866):    at java.io.Reader.<init>(Reader.java:65)
 10-26 15:22:49.090: E/AndroidRuntime(23866):   at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
10-26 15:22:49.090: E/AndroidRuntime(23866):    at com.example.httpconnectsample.Httpconnectionsample$5.run(Httpconnectionsample.java:99)
10-26 15:22:49.100: I/dalvikvm(23866): threadid=7: reacting to signal 3
10-26 15:22:49.115: I/dalvikvm(23866): Wrote stack trace to '/data/anr/traces.txt'

我试图寻找修复但却无法理解为什么会发生这种情况。我只需要下载文本,所以目前我忽略了此代码的下载图像部分。另外,我补充道 uses-permission android:name =“android.permission.INTERNET” 在清单上方,但仍然显示许可被拒绝。 我会感激任何帮助。

1 个答案:

答案 0 :(得分:5)

INTERNET权限添加到清单文件中。

你必须添加这一行:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

在AndroidManifest.xml中的应用程序标记之外,如下所示

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" /> 

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />   

<application>
    //your stuffs
</application>

</manifest>