当我尝试下载页面时,我的 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>