My application has a "start download" and a "pause" button. Once I start the download through "Start Download" button my download starts and stop upon clicking "pause" now when I press back or home button the onPause() function works as intended it pauses my download and when I open the app again and click start it resumes from that progress,
what I want is that upon switching back(not the first time load of app) to the application once I have pressed back or home I want the download to resume automatically by onResume without clicking start button again. Right now in below code my download automatically starts without doing anything which is due to my onResume(), is it possible that I can resume with onResume but not start the download automatically upon first time loading of the app thorugh it? I know the below code is not as efficient as it could have been. Apologies for that.
Again, I want my onResume to only resume my previously downloaded file not start the download unless download was once initiated through the button.
public class MainActivity extends Activity implements OnClickListener{
String url = "http://upload.wikimedia.org/wikipedia/commons/1/11/HUP_10MB_1946_obverse.jpg";
boolean mStopped=false;
private ProgressBar progressBar2;
private String filepath = "MyFileStorage";
private File directory;
private TextView finished;
#Override
protected void onPause() {
super.onPause();
mStopped=true;
}
#Override
protected void onResume() {
super.onResume();
mStopped=false;
grabURL(url);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
progressBar2.setVisibility(View.GONE);
finished = (TextView) findViewById(R.id.textView1);
finished.setVisibility(View.GONE);
Button stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(this);
Button download = (Button) findViewById(R.id.download);
download.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.stop:
mStopped=true;
break;
case R.id.download:
mStopped=false;
grabURL(url);
break;
}
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
progressBar2.setVisibility(View.VISIBLE);
progressBar2.setProgress(0);
finished.setVisibility(View.GONE);
}
protected String doInBackground(String... urls) {
String filename = "MySampleFile.png";
File myFile = new File(directory , filename);
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
if (myFile.exists())
{
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + myFile.length() + "-");
}
connection.connect();
int fileLength = connection.getContentLength();
fileLength += myFile.length();
InputStream is = new BufferedInputStream(connection.getInputStream());
RandomAccessFile os = new RandomAccessFile(myFile, "rw");
os.seek(myFile.length());
byte data[] = new byte[1024];
int count;
int __progress = 0;
while ((count = is.read(data)) != -1 && __progress != 100) {
if (mStopped) {
throw new IOException();
}
else{
__progress = (int) ((myFile.length() * 100) / fileLength);
publishProgress((int) (myFile.length() * 100 / fileLength));
os.write(data, 0, count);}
}
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
protected void onProgressUpdate(Integer... progress) {
finished.setVisibility(View.VISIBLE);
finished.setText(String.valueOf(progress[0]) + "%");
progressBar2.setProgress(progress[0]);
}
protected void onCancelled() {
Toast toast = Toast.makeText(getBaseContext(),
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
protected void onPostExecute(String filename) {
progressBar2.setProgress(100);
finished.setVisibility(View.VISIBLE);
finished.setText("Download in progress..");
File myFile = new File(directory , filename);
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
myImage.setImageBitmap(BitmapFactory.decodeFile(myFile.getAbsolutePath()));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You seem to already have most of the code in place for the functionality. In onResume you can call your ASyncTask and it should start download if the file exists (paused download in onPause(), file exists). I have written similar code, you can find it here: https://github.com/hiemanshu/ContentDownloader/blob/master/src/com/example/contentdownloader/MainActivity.java
In my code you can find that instead of using onPause and onResume, I just have a wakelock for that period of time.
Related
My app crashes when the link is empty. I am trying to download Instagram videos. The apps work fine with public links. But I put a private link the app crashes. This means with a private link the apps get no HTML from the website. And the download links remain empty. Which causes the app to crash. I want when enter a private link app wouldn't crash
I tried to use if-else statements in the onPostExecute method but it didn't work or maybe I am doing it the wrong way.
This AsyncTask class
private class InstaVideo extends AsyncTask<Void, Void, Void> {
String dlink, imglink;
#Override
protected void onPreExecute() {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.loading_indicator);
progressBar.setVisibility(View.VISIBLE);
DoubleBounce doubleBounce = new DoubleBounce();
progressBar.setIndeterminateDrawable(doubleBounce);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://www.10insta.net/#grid-gallery")
.data("url", temp)
.post();
Log.v("Hello", doc.title());
Element srctag = doc.select("img.card-img-top").first();
Element ptag = doc.select("p.card-text").first();
Element atag = ptag.select("a").first();
imglink = srctag.attr("src");
dlink = "https://www.10insta.net/";
dlink += atag.attr("href");
Log.i("DownloadActivity",dlink);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (dlink=="https://www.10insta.net/download.php?url=") {
Toast.makeText(DownloadActivity.this,"Link is private",Toast.LENGTH_SHORT).show();
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
TextView t = (TextView) findViewById(R.id.imgtxt);
if (Content.id == 2) {
t.setText("Video Preview");
} else {
t.setText("Image Preview");
}
t.setVisibility(View.VISIBLE);
Button b = (Button) findViewById(R.id.instadownload);
b.setVisibility(View.VISIBLE);
final ImageView img = (ImageView) findViewById(R.id.instaimg);
Picasso.get().load(imglink).placeholder(R.drawable.loading).into(img);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(dlink);
DownloadManager.Request req = new DownloadManager.Request(uri);
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (Content.id == 2) {
req.setDestinationInExternalPublicDir("/VideoDownloader", "insta.mp4");
} else {
req.setDestinationInExternalPublicDir("/VideoDownloader", "insta.jpg");
}
StyleableToast.makeText(getBaseContext(), "Download Started", Toast.LENGTH_SHORT, R.style.mytoast).show();
Long ref = dm.enqueue(req);
}
});
}
}
}
doInBackground fetch HTML from the website and filters the required video download link. This works fine with public links but crashes with private links.
Now I want when I enter a private link app wouldn't crash. help is much appreciated
Error Image
Since you have mentioned if-else not working to check image path then try to consume the exception using try - catch block.
try {
Picasso.get().load(imglink).placeholder(R.drawable.loading).into(img);
} catch(Exception ex) {
ex.printStackTrace();
t.setVisibility(View.GONE);
b.setVisibility(View.GONE);
}
Besides this, you use == operator to compare String which give you false always. Try using equals()/equalsIgnoreCase()
if (dlink.equalsIgnoreCase("https://www.10insta.net/download.php?url="))
I am creating an application in which i am setting a gallery of images with shuffling effect on wallpaper. shuffling effect is working if app is in background.
But the problem is when i change my wallpaper from my device to set on home screen(not from application but select form wallpapers of device), that wallpaper is setting on my home screen and the shuffling effect remains continue(because i think service is running). Can someone please tell me what is the issue and how to solve this. This is my service class:
public class WallpaperService extends Service {
ArrayList<String> arrayList = new ArrayList<>();
int counter = 0;
Bitmap bmImg = null;
int seconds;
public WallpaperService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flag, int startId) {
super.onStartCommand(intent, flag, startId);
arrayList = intent.getStringArrayListExtra("image_url");
seconds = intent.getIntExtra("seconds", 5000 * 60);
Toast.makeText(this, "Hello", Toast.LENGTH_SHORT).show();
SaveWallpaperAsync async = new SaveWallpaperAsync();
async.execute();
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
}
public class SaveWallpaperAsync extends AsyncTask<String, Integer, Void> {
URL ImageUrl;
Bitmap bmImg = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Toast.makeText(WallpaperService.this, "downloading", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
InputStream is = null;
for (int i = 0; i < arrayList.size(); i++) {
try {
ImageUrl = new URL(arrayList.get(i));
HttpURLConnection conn = (HttpURLConnection) ImageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
bmImg = BitmapFactory.decodeStream(is, null, options);
saveImageToInternalStorage(bmImg, i);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(WallpaperService.this, "Downloaded", Toast.LENGTH_SHORT).show();
createNotificationIcon();
}
}
protected String saveImageToInternalStorage(Bitmap bitmap, int index) {
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Dark Wallpapers/");
if (!dir.exists()){
dir.mkdirs();
}
File file = new File(dir, "UniqueFileName" + index + ".jpg");
try {
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
Uri savedImageURI = Uri.parse(file.getAbsolutePath());
return savedImageURI.toString();
}
private Bitmap loadImageFromStorage(int counter) {
Bitmap b = null;
try {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Dark Wallpapers/", "UniqueFileName" + counter + ".jpg");
b = BitmapFactory.decodeStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return b;
}
public void createNotificationIcon() {
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
counter += 1;
if (counter < arrayList.size()) {
try {
wallpaperManager.setBitmap(loadImageFromStorage(counter));
wallpaperManager.suggestDesiredDimensions(1080, 1920);
} catch (IOException e) {
e.printStackTrace();
}
} else if (counter == arrayList.size()) {
counter = 0;
try {
wallpaperManager.setBitmap(loadImageFromStorage(counter));
wallpaperManager.suggestDesiredDimensions(1080, 1920);
} catch (IOException e) {
e.printStackTrace();
}
}
}
},
0,
seconds);
}}
This is how i called it from activity:
Intent intent = new Intent(CategoryActivity.this, WallpaperService.class);
intent.putExtra("image_url", img_urls);
intent.putExtra("seconds", 60);
intent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(intent);
If I have understood well you would like to get an "event" (or just to know...) when the home wallpaper is changed. Is it right?
Maybe you would like to stop your Service if it detects that the User wants to set a fixed wallpaper from that moment.
There isn't any Event to do this, but there is a solution: remember which wallpaper you have automatically changed from the App (maybe memorize the path+filename in a file in your /xxxxx/files folder) and then check the Current Wallpaper just before trying to set the new one, using this:
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
In this way if the Current Wallpaper is the same of your last and memorized filename than there is a 99% of chance that the user doesn't set a fixed one by his/her own. (the remaining 1% could be the possibility that the user manually sets the SAME wallpaper you automatically set as the last one, but it's very-very rare)
I've been getting very strange behavior from my code.
Basically, my code is using an Input/Output stream to download a .pdf file from the internet, saving it to internal storage (using an AsyncTask) and then outputting it using an outside "showPdf" library.
The strangest thing is that it only works on two conditions:
I run the code twice (run or debug without any break points). The first run logs File is empty when showPdf() is called, but the second run through runs perfectly fine when showPdf() is called on its own.
I debug the code and step through the program
As a preface, I'm new to java and android studio, so my guess may not be right at all, but I'm guessing since the InputStream is being done "asynchronously", showPdf() may be called before the byte[] array is written into memory. If this is the case, what could I do to delay Async long enough to work?
public class pdfView extends AppCompatActivity {
PDFView pdfView; //pdfView object
String URL;
String fileName;
File directory; //path of created File
// Container for all parameters of DownloadAsync
private static class AsyncParameters {
String URL;
File directory;
AsyncParameters(String URL, File directory) {
this.URL = URL;
this.directory = directory;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_view);
//Grab the extras from the intent call
Intent intent = getIntent(); //whatever calls this activity, gather the intent
URL = intent.getStringExtra("File URL"); // in this case, get the file name of the "extra" passed through
fileName = intent.getStringExtra("File Name");
//Grab the internal storage directory and create a folder if it doesn't exist
File intDirectory = getFilesDir();
File folder = new File(intDirectory, "pdf");
boolean isDirectoryCreated = folder.exists();
//See if the file exists
if (!isDirectoryCreated) {
isDirectoryCreated= folder.mkdir();
}
if(isDirectoryCreated) {
directory = new File(folder, fileName);
try {
directory.createNewFile();
if (directory.canWrite())
Log.d("hngggggggggggggg", "onCreate: ");
} catch (IOException e1) {
e1.printStackTrace();
}
//See if file already exists
boolean empty = directory.length() == 0;
if (empty){
/**Call class to create parameter container**/
AsyncParameters param = new AsyncParameters(URL, directory);
DownloadAsync Downloader = new DownloadAsync();
Downloader.execute(param);
showPdf();
}
else
showPdf();
}
}
public void showPdf()
{
pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(directory).load();
}
/**Class for asynchronous tasks**/
public class DownloadAsync extends AsyncTask<AsyncParameters, Void, Void> {
// Container for all parameters of DownloadAsync
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(pdfView.this);
pDialog.setMessage("Downloading Database...");
String message= "Downloading Files";
SpannableString ss2 = new SpannableString(message);
ss2.setSpan(new RelativeSizeSpan(2f), 0, ss2.length(), 0);
ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0);
pDialog.setMessage(ss2);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(AsyncParameters... params) {
Log.d("WE ARE IN DOBACKGROUND", "doInBackground: ");
String fileURL = params[0].URL;
File directory = params[0].directory;
try {
FileOutputStream f = new FileOutputStream(directory);
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[8192];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
onPostExecute();
return null;
}
protected void onPostExecute() {
pDialog.dismiss();
}
}
}
You already have answered your own question. Since the download is asyncTask running on a different thread, there is no wait for the asyncTask to complete before showPdf() is called. You can call showPdf() from onPostExecute() which is called after the background task completes. Your code should look like:
#Override
protected void onCreate(Bundle savedInstanceState) {
........
........
AsyncParameters param = new AsyncParameters(URL, directory);
DownloadAsync Downloader = new DownloadAsync();
Downloader.execute(param);
.......
.......
}
public class DownloadAsync extends AsyncTask<AsyncParameters, Void, Void> {
.......
#Override
protected void onPostExecute() {
pDialog.dismiss();
showPdf();
}
}
im beginner in android.
i have 2 class in 2 .java file. first:Mainacivity and second:ImageDownloader.
imagedownloader downloads bitmap with it's function getBitmapFromURL(String url), i give string to this function and it works well, but i wanna download more than 1 bitmap one after another.
my main activity:
public class MainActivity extends Activity implements View.OnClickListener
{
private Button download, downloadBG, save;
private ImageView img;
private ProgressBar pb;
private EditText etUrl;
private TextView percent;
private ImageDownloader mDownloader;
private static Bitmap bmp;
private FileOutputStream fos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*--- initialize layout compinents ---*/
private void initViews() {
download = (Button) findViewById(R.id.btnDownload);
downloadBG = (Button) findViewById(R.id.btnDownloadBackground);
save = (Button) findViewById(R.id.btnSave);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
download.setOnClickListener(this);
downloadBG.setOnClickListener(this);
save.setOnClickListener(this);
save.setEnabled(false);
img = (ImageView) findViewById(R.id.image);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
etUrl = (EditText) findViewById(R.id.etUrl);
percent = (TextView) findViewById(R.id.tvPercent);
percent.setVisibility(View.INVISIBLE);
}
#Override
public void onClick(View v) {
/*--- determine which button was clicked ---*/
switch (v.getId())
{
case R.id.btnDownload:
{
/*--- we use trim() to remove whitespaces which could be entered ---*/
bmp = ImageDownloader.getBitmapFromURL(URLbuilder(0, 0, 0));
img.setImageBitmap(bmp);
save.setEnabled(true);
break;
}
case R.id.btnDownloadBackground:
for(int a = 0 ; a < 4 ; a++)
{
/*--- check whether there is some Text entered ---*/
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(URLbuilder(a, a, a), a,pb, save, img, percent, MainActivity.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
MainActivity.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
break;
}
}
public String URLbuilder(int x , int y , int z)
{
String myurl = "http://khm0.google.com/kh/v=132&hl=EN&x={0}&y={1}&z={2}&s=";
String.format(myurl, x,y,z);
return String.format(myurl, x,y,z);
}
}
if i click on DownloadBackground button it should download 4 bitmap from it's url.
i know that each download take some time but i cannot stop this function untill first bitmap download.
my imagedownloader:
public class ImageDownloader extends AsyncTask<Void, Integer, Void>
{
private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
FileOutputStream fos;
int Counter = 0;
/*--- constructor ---*/
public ImageDownloader(String url,int counter, ProgressBar pb, Button save,
ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
this.url = url;
this.pb = pb;
this.save = save;
this.c = c;
this.img = img;
this.percent = percent;
this.bmp = bmp;
this.listener = listener;
//this.Counter = Integer.toString(counter);
}
/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity.
* Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {
void onImageDownloaded(Bitmap bmp);
}
#Override
protected void onPreExecute() {
progress = 0;
pb.setVisibility(View.VISIBLE);
percent.setVisibility(View.VISIBLE);
Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
bmp = getBitmapFromURL(url);
while (progress < 100) {
progress += 1;
publishProgress(progress);
/*--- an image download usually happens very fast so you would not notice
* how the ProgressBar jumps from 0 to 100 percent. You can use the method below
* to visually "slow down" the download and see the progress bein updated ---*/
//SystemClock.sleep(200);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
/*--- show download progress on main UI thread---*/
pb.setProgress(values[0]);
percent.setText(values[0] + "%");
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onImageDownloaded(bmp);
}
img.setImageBitmap(bmp);
saveImageToSD();
save.setEnabled(true);
Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
public static Bitmap getBitmapFromURL(String link)
{
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("getBmpFromUrl error: ", e.getMessage().toString());
return null;
}
}
private void saveImageToSD()
{
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDownloadedImage" + Integer.toString(Counter) + ".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Counter++;
}
i need to stop for loop in onclick method in main activity until each image download. i did every things that i knew but every time it crashed.
later i have to put image downloader in a thread but i dont know how to stop thread for a while.
pls help me. ty
You can use Handler
new Handler().postDelayed(new Runnable(){
public void run() {
//some job to do delayed 3s
}}, 3000);
Hope it helps!
Dear stackOverflow members i have recently started a new project called "RootBox" and it is an app that needs "su" perms and i have successfully allowed the app "su" or "root" access and im trying to download and replace a system file in "/system/media and i have setup my downloader but the download progress dialog pops up and closes which im guessing is the result of the file not being able to written to the system directory and i have Re-mounted the system as r-w before starting the download an i have searched all over the internet and was unable to find help thats why i have come here.
This is the activity executing the download
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bootmation);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
RootTools.remount("/system/", "rw");
}
});
}
private void startDownload() {
String url = "http://www.filehosting.org/file/details/430746/bootanimation.zip";
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/system/media/bootanimation.zip");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
for this u have to allow in manifest for permission for writing as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
URL u = new URL(fUrls[i]);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();