0

当我尝试下载页面时,我的 android 应用程序崩溃,我授予应用程序访问互联网和读取/写入外部存储的权限,我正在尝试制作一个简单的应用程序,其中包含两个选项:下载 url 和保存页面的位置,但是当我点击下载按钮时,应用程序崩溃了。

是什么导致应用程序崩溃?下载网址的正确方法是什么?

package com.downloadfile;

import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class MainActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void saveButton(View v) throws MalformedURLException, IOException
    {
        EditText pageurl = (EditText) findViewById(R.id.page_url);
        String PageUrl = pageurl.getText().toString();
        EditText filePath = (EditText) findViewById(R.id.save_path);
        String FilePath = filePath.getText().toString();

        if (FilePath.startsWith("/"))
        {

            URL url = new URL(PageUrl);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

            String data = new java.util.Scanner(in).useDelimiter("\\A").next();
            PrintWriter writer = new PrintWriter(FilePath, "UTF-8"); 
            writer.println(data); 
            writer.close();
            urlConnection.disconnect();


            Context context = getApplicationContext(); 
            CharSequence text = FilePath;
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration); 
            toast.show();
        }
        else
        {
            Context context = getApplicationContext(); 
            CharSequence text = "Please enter file path";
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration); 
            toast.show();
        } 
    }
}

这是我的布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:minWidth="300dp"
    android:padding="5dp">

    <EditText
        android:id="@+id/page_url"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="url"
        android:inputType="textUri"/>

    <EditText
        android:id="@+id/save_path"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="save path"
        android:inputType="textUri"/>

    <LinearLayout
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:id="@+id/linearLayout1"
        android:layout_marginTop="4dp"/>

    <Button
        android:id="@+id/download"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Download"
        android:onClick="saveButton"/>

</LinearLayout>
4

1 回答 1

1

您正在 ui 线程上运行与网络相关的操作。使用ThreadAsynctask

你可能会得到NetWorkOnMainThreadException. http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

将视图的初始化移至 onCreate。在按钮上单击从 Edittext 获取文本。无需每次单击按钮时都进行初始化。

EditText pageurl;
EditText filePath;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    pageurl = (EditText) findViewById(R.id.page_url);
    filePath = (EditText) findViewById(R.id.save_path);
}

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

在按钮上单击

   public void saveButton(View v) 
   {
      String PageUrl = pageurl.getText().toString();
      String FilePath = filePath.getText().toString();
      new DownloadTask().execute(PageURl,FilePath);
   }

异步任务

    class DownloadTask extends AsyncTask<String,Void,Void>
    {

@Override
protected void onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
    // TODO Auto-generated method stub
       if (params[1].startsWith("/"))
       {
        try
        {

        URL url = new URL(params[0]);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        String data = new java.util.Scanner(in).useDelimiter("\\A").next();
        PrintWriter writer = new PrintWriter(FilePath, "UTF-8"); 
        writer.println(data); 
        writer.close();
        urlConnection.disconnect();
        }catch(Exception e)
        {
            e.printstackTrace()
        } 
       return null;
}

 }
于 2013-10-01T18:07:28.310 回答