android_id/app/src/main/java/com/psmreborn/pkgj/PsmGameDownloader.java

106 lines
3.1 KiB
Java

package com.psmreborn.pkgj;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
public class PsmGameDownloader extends AsyncTask<Void, Void, Void> {
private boolean wasError = false;
private String errorMsg = "";
private Context ctx = null;
private File psmApplicationsFolder = null;
private ProgressDialog dialog = null;
private Game gameDownloading = null;
public PsmGameDownloader(Context context, Game downloadGame){
this.ctx = context;
this.gameDownloading = downloadGame;
// get psm data folder ...
this.psmApplicationsFolder = new File(new File(new File(new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data"), "com.playstation.psstore"), "files"), "psm");
this.psmApplicationsFolder.mkdirs();
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(ctx);
dialog.setTitle("Downloading: "+gameDownloading.getPkgFilename());
dialog.setMessage(gameDownloading.getTitle());
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(false);
dialog.show();
}
private void download() throws IOException {
URL url = new URL(gameDownloading.getDownloadUrl());
URLConnection connection = url.openConnection();
connection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(new File(this.psmApplicationsFolder, gameDownloading.getPkgFilename()));
int fileLength = connection.getContentLength();
byte[] data = new byte[8192];
int count = 0;
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
dialog.setProgress((int) ((total * 100) / fileLength));
output.write(data, 0, count);
}
// flushing output
output.flush();
output.close();
input.close();
}
@Override
protected Void doInBackground(Void... voids) {
try{
download();
// TODO: extract pkg, extract zrif
}
catch (Exception e){
this.wasError = true;
this.errorMsg = e.toString();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
((MainActivity)ctx).updateGames();
if(wasError) {
new AlertDialog.Builder((Activity)ctx)
.setTitle("Error Downloading: "+ gameDownloading.getTitleId())
.setMessage(this.errorMsg)
.setCancelable(false)
.setPositiveButton("OK",null).show();
}
}
}