MainActivity.java
public class MainActivity extends AppCompatActivity {
WebView webView;
// webView.setWebViewClient
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// webView.getSettings().setBlockNetworkLoads(false);
webView = (WebView) findViewById(R.id.urlWebView);
webView.loadUrl("https://unsplash.com/images");
Intent serviceIntent = new Intent();
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
serviceIntent.putExtra("urlToDownload", url);
Log.d("Download img", url);
Log.d("User Agent", userAgent);
Log.d("Content", contentDisposition);
Log.d("mimetype", mimetype);
Log.d("Content Length", String.valueOf(contentLength));
}
});
}
}
downloaderSer.java
package com.example.lab3webview;
import android.app.IntentService;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.webkit.URLUtil;
import androidx.annotation.Nullable;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class downloaderSer extends IntentService {
@Override
public void onCreate() {
super.onCreate();
}
MainActivity mainActivity;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public downloaderSer(String name) {
super(name);
}
// Downloader Intent Service
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getExtras().getString("urlToDownload");
// test service intent here
try {
URL url = new URL(urlToDownload);
String filename = URLUtil.guessFileName(urlToDownload, null, null);
InputStream is = url.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "Download/" + filename));
while ((length = dis.read(buffer))>0) {
fos.write(buffer, 0, length); }
} catch (Exception e) {
Log.e("Image download", e.toString());
}
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Lab3WebView"
android:usesCleartextTraffic="true">
到目前为止,前面提到的java类是我正在编写的代码。
现在,我遇到了一个问题,在我的downloaderSer.java
类中,它无法从站点成功下载图像,然后将其保存到下载文件中。我花了好几个小时才能弄清楚。我以为,在onHandleIntent
方法中,我已成功将MainActivity类的urlToDownload传递到此处。有人可以解释为什么这在逻辑上是错误的吗?