在我的应用程序中,我正在从一个网络服务器下载一个 kml
文件。我已经在我的机器人清单文件中设置了外部存储和互联网的权限。我是安卓系统的新手,非常感谢您的帮助。
MainActivity.java
package com.example.demo;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadFiles();
}
public void DownloadFiles(){
try {
URL u = new URL("http://www.qwikisoft.com/demo/ashade/20001.kml");
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "data/test.kml"));
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
}
}
Android 清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.demo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
日志记录错误:
致命例外: 总部 无法启动活动 Component entInfo { com.example.demo/com.example.demo. MainActivity } : android.os. NetworkOnMainThreadException ActivityThread.PerformLaunchActivity (ActivityThread.java: 1956) ActivityThread.handleLaunchActivity (ActivityThread.java: 1981) ActivityThread.access $600(ActivityThread.java: 123) ActivityThread $H.handleMessage (ActivityThread.java: 1147) 在 android.os 处理器。调度消息(Handler.java: 99) 在 android.os. Looper.loop (Looper.java: 137) ActivityThread.main (ActivityThread.java: 4424) 原生方法(本机方法) 在 java.lang.response. Method.emon (Method.java: 511) ZygoteInit $MethodAndArgsCaller.run (ZygoteInit.java: 784) JygoteInit.main (ZygoteInit.java: 551) 在 dalvik.system. NativeStart.main (本机方法) 由 android.os. NetworkOnMainThreadException 引起 StrictMode $AndroidBlockGuardPolicy. onNetwork (StrictMode.java: 1099) 在 java.net. InetAdresss.lookupHostByName (InetAdresss.java: 391) 在 java.net. InetAddresss.getAllByNameImpl (InetAddresss.java: 242) 在 java.net. InetAddresss.getAllByName (InetAddresss.java: 220) 在 libcore.net.http. HttpConnection (HttpConnection.java: 71) 在 libcore.net.http. HttpConnection (HttpConnection.java: 50) 在 libcore.net.http. HttpConnection $Address.connect (HttpConnection.java: 351) 在 libcore.net.http. HttpConnectionPool.get (HttpConnectionPool.java: 86) 在 libcore.net.http. HttpConnection.connect (HttpConnection.java: 128) 在 libcore.net.http. HttpEngine.openSocketConnection (HttpEngine.java: 308) 在 libcore.net.http. HttpEngine.connect (HttpEngine.java: 303) 请访问 libcore.net.http. HttpEngine.sendSocketRequest (HttpEngine.java: 282) 请访问 libcore.net.http. HttpEngine.sendRequest (HttpEngine.java: 232) 请访问 libcore.net.http. HttpURLConnectionImp.getResponse (HttpURLConnectionImp.java: 273) 在 libcore.net.http. HttpURLConnectionImp.getInputStream (HttpURLConnectionImp.java: 168) (网址 java.net.URL.openStream: 462) 可以访问 com.example.demo. MainActivity. DownloadFiles (MainActivity.java: 30) 在 com.example.demo. MainActivity.onCreate (MainActivity.java: 24) 创建(Activity.java: 4465) 在 android.app. Instrumentation.calActivityOnCreate (Instrumentation.java: 1049) ActivityThread.PerformLaunchActivity (ActivityThread.java: 1920)
剪辑
package com.example.demo;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class MainActivity extends Activity {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute("http://www.qwikisoft.com/demo/ashade/20001.kml");
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
**/
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
**/
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/data/downloadedfile.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
**/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
**/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
当我在模拟器中运行这段代码时,代码仍然无法工作-文件没有被下载。