I am working on one project. In this project i download the PDF file it work perfectly but i want progress bar with percentage. Progressbar show but problem is it does't update the progress stuck in 0(zero).What should i do?
See My code
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
// Progress dialog
private ProgressDialog mProgressDialog ;
private int mProgressStatus = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Creating a progress dialog window */
mProgressDialog = new ProgressDialog(this);
/** Close the dialog window on pressing back button */
mProgressDialog.setCancelable(true);
/** Setting a horizontal style progress bar */
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
/** Setting a message for this progress dialog
* Use the method setTitle(), for setting a title
* for the dialog window
* */
mProgressDialog.setMessage("Downloading...");
}
public void downloadPDF(View v) {
/** Show the progress dialog window */
mProgressDialog.show();
new DownloadFile().execute("https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf", "five-point-someone-chetan-bhagat_ebook.pdf");
}
public void viewPDF(View v) {
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/PDF DOWNLOAD/" + "five-point-someone-chetan-bhagat_ebook.pdf"); // -> filename = maven.pdf
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
}
private class DownloadFile extends AsyncTask<String, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressStatus = 0;
}
#Override
protected Void doInBackground(String... strings) {
publishProgress(mProgressStatus);
String fileUrl = strings[0]; // -> https://letuscsolutions.files.wordpress.com/2015/07/five-point-someone-chetan-bhagat_ebook.pdf
String fileName = strings[1]; // ->five-point-someone-chetan-bhagat_ebook.pdf
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "PDF DOWNLOAD");
folder.mkdir();
File pdfFile = new File(folder, fileName);
try {
pdfFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileDownloader.downloadFile(fileUrl, pdfFile);
return null;
}
/** This callback method is invoked when publishProgress()
* method is called */
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressDialog.setProgress(mProgressStatus);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Download PDf successfully", Toast.LENGTH_SHORT).show();
Log.d("Download complete", "----------");
}
}
}
You are not calculating the progress of your download. mProgressStatus will always zero.
First calculate the download size in percentage and store it in mProgressStatus then call publishProgress(mProgressStatus).
You should call
publishProgress(int progress) in doInBackground() method.
like
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Related
I am new for android.make one video player code the video play from url and user can download the video from the apps. i make until download and push Notification and using service. the issue i is when download one video the user click download another video is overwrite the 1st download. any one can give me solution..
package crazysing.crazyweb.my.fragment;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import crazysing.crazyweb.my.MainActivity;
import crazysing.crazyweb.my.R;
import crazysing.crazyweb.my.adater.CustomListAdapter;
import crazysing.crazyweb.my.app.AppController;
import crazysing.crazyweb.my.model.Movie;
import crazysing.crazyweb.my.service.NLService;
/**
* Created by LENOVO on 14/02/2017.
*/
public class SongPlayerFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
String videopath = "http://crazysing.crazyweb.my/upload/vid/";
NotificationCompat.Builder mBuilder;
NotificationManager mNotifyManager;
int id = 1;
int counter = 0;
private NotificationReceiver nReceiver;
String sdCard = Environment.getExternalStorageDirectory().toString();
File myDir = new File(sdCard, "Video/CrazySing");
VideoView videov;
MediaController mediaC;
NetworkImageView videothumbNail;
// Movies json url
private static final String url = "http://crazysing.crazyweb.my/api/songlist.php";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String event = intent.getExtras().getString(NLService.NOT_EVENT_KEY);
Log.i("NotificationReceiver", "NotificationReceiver onReceive : " + event);
if (event.trim().contentEquals(NLService.NOT_REMOVED)) {
killTasks();
}
}
}
private void killTasks() {
mNotifyManager.cancelAll();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.song_player_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
videov = (VideoView) view.findViewById(R.id.videov);
mediaC = new MediaController(getActivity());
listView = (ListView) view.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
// Register the ListView for Context menu
registerForContextMenu(listView);
listView.setOnItemClickListener(new ItemList());
videothumbNail = (NetworkImageView) view.findViewById(R.id.placeholder);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setFileName(obj.getString("filename"));
movie.setVideoPath(obj.getString("video_path"));
movie.setSingerName(obj.getString("singer_name"));
movie.setSongId(obj.getInt("songId"));
movie.setDuration(obj.getString("duration"));
movie.setThumbnailUrl(obj.getString("image"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
videoView(" ", " "," ");
}
public void videoView(String videopath,String fileName, String imageName) {
// videopath = videopath + filename;
if (imageName == " ") {
videothumbNail.setDefaultImageResId(R.drawable.sing);
videothumbNail.setErrorImageResId(R.drawable.sing);
videothumbNail.setVisibility(View.VISIBLE);
videov.setVisibility(View.INVISIBLE);
Log.d(TAG, "empty vedeio");
} else {
videothumbNail.setImageUrl(imageName, imageLoader);
videothumbNail.setVisibility(View.VISIBLE);
videov.setVisibility(View.INVISIBLE);
File file = new File(myDir, fileName);
if (file.exists()){
Uri uri = Uri.parse(myDir+"/"+fileName);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
videov.setVisibility(View.VISIBLE);
videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videothumbNail.setVisibility(View.GONE);
}
});
}else {
try {
Uri uri = Uri.parse(videopath);
videov.setVideoURI(uri);
videov.setMediaController(mediaC);
mediaC.setAnchorView(videov);
videov.start();
videov.setVisibility(View.VISIBLE);
videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
videothumbNail.setVisibility(View.GONE);
}
});
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.song_list_menu, menu);
menu.setHeaderTitle("Options");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
View view = info.targetView;
String VideoPath = ((Movie) movieList.get(index)).getVideoPath();
String FileName = ((Movie) movieList.get(index)).getFileName();
String urlsToDownload[] = {VideoPath,FileName};
switch (item.getItemId()) {
case R.id.download:
NotificationManager(urlsToDownload);
Log.d(TAG, "value=" + VideoPath);
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
killTasks();
getActivity().unregisterReceiver(nReceiver);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
class ItemList implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
String videoUrl = ((Movie) movieList.get(position)).getVideoPath();
String fileName = ((Movie) movieList.get(position)).getFileName();
String bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Toast.makeText(SongPlayerFragment.this.getActivity(), videoUrl, Toast.LENGTH_SHORT).show();
videoView(videoUrl,fileName, bitmap);
}
}
private void downloadImagesToSdCard(String downloadUrl, String videoName) {
FileOutputStream fos;
InputStream inputStream = null;
try {
URL url = new URL(downloadUrl);
/* making a directory in sdcard */
/* if specified not exist create new */
if (!myDir.exists()) {
myDir.mkdir();
Log.v("", "inside mkdir");
}
/* checks the file and if it already exist delete */
String fname = videoName;
File file = new File(myDir, fname);
Log.d("file===========path", "" + file);
if (file.exists())
file.delete();
/* Open a connection */
URLConnection ucon = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) ucon;
httpConn.setRequestMethod("GET");
httpConn.connect();
inputStream = httpConn.getInputStream();
/*
* if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
* inputStream = httpConn.getInputStream(); }
*/
fos = new FileOutputStream(file);
// int totalSize = httpConn.getContentLength();
// int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fos.write(buffer, 0, bufferLength);
// downloadedSize += bufferLength;
// Log.i("Progress:", "downloadedSize:" + downloadedSize +
// "totalSize:" + totalSize);
}
inputStream.close();
fos.close();
Log.d("test", "Video Saved in sdcard..");
} catch (IOException io) {
inputStream = null;
fos = null;
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
private class ImageDownloader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... param) {
downloadImagesToSdCard(param[0], param[1]);
return null;
}
protected void onProgressUpdate(String... values) {
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
}
#Override
protected void onPostExecute(Void result) {
Log.i("Async-Example", "onPostExecute Called");
mBuilder.setContentTitle("Done.");
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
}
private void NotificationManager(String... param){
mNotifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getActivity());
mBuilder.setContentTitle("Downloading Video...").setContentText("Download in progress").setSmallIcon(R.mipmap.ic_launcher);
//add sound
Uri nUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(nUri);
//vibrate
long[] v = {500,1000};
mBuilder.setVibrate(v);
// Start a lengthy operation in a background thread
mBuilder.setProgress(0, 0, true);
mNotifyManager.notify(id, mBuilder.build());
mBuilder.setAutoCancel(true);
ImageDownloader imageDownloader = new ImageDownloader();
imageDownloader.execute(param);
ContentResolver contentResolver = getActivity().getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
String packageName = getActivity().getPackageName();
// check to see if the enabledNotificationListeners String contains our
// package name
if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
// in this situation we know that the user has not granted the app
// the Notification access permission
// Check if notification is enabled for this application
Log.i("ACC", "Dont Have Notification access");
Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
} else {
Log.i("ACC", "Have Notification access");
}
nReceiver = new NotificationReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(NLService.NOT_TAG);
getActivity().registerReceiver(nReceiver, filter);
}
}
Instead of using only
File myDir = new File(sdCard, "Video/CrazySing");
use
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Video" + n + ".mp4";
File file = new File(myDir, fname);
This will generate a unique file name for each time.
Instead .mp4 you can use your video extension
Hi in the below downloading images for showing progessbar to 100 but completeld 100% images are not showing still downloading and not showing .i want after 100% i want to move to activity.
But it's taking time to move next activity.
java
public class DownloadTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
final DialogProgressBarRunnable progressDialog =
new DialogProgressBarRunnable(getActivity(), false, 2);
progressDialog.show();
// the dialog box shouldn't get cancelled when clicking outside it or pressing back button.
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
// pd.setMessage("Downloading catalogue images.");
// pd.show();
}
protected String doInBackground(Void... Params) {
parsingObject = new ParsingForFinalImages(catid, responseJson);
/* ConnectionDetector cd = new ConnectionDetector(getActivity().getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent==true)
{
}
*/
// put your code here
// JSON parsing begins here via the parsing class
// Put this code in async task
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// pd.hide();
// pd.dismiss();
Intent intent = new Intent(getActivity(), ImageGallery.class);
startActivity(intent);
}
}
private class DialogProgressBarRunnable extends ProgressDialog implements
Runnable {
private boolean showSecondary;
private int incrementAfter;
public DialogProgressBarRunnable(Context context,
boolean showSecondary, int incrementAfter) {
super(context);
setCancelable(true);
setMessage(getString(R.string.download_message));
setSecondaryProgress(0);
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
setMax(100);
setProgress(0);
this.showSecondary = showSecondary;
this.incrementAfter = incrementAfter;
}
#Override
public void show() {
super.show();
new Thread(this).start();
}
#Override
public void run() {
while (progress < 100) {
progress++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// increment the first/second progress bar after every %
progressBar();
}
}
private void progressBar() {
if (progress % incrementAfter == 0) {
progressFirstBar();
}
if (showSecondary) {
progressSecondaryBar();
}
}
private void progressSecondaryBar() {
while (secondaryProgress < 100) {
secondaryProgress++;
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
setSecondaryProgress(secondaryProgress);
}
});
}
}
private void progressFirstBar() {
secondaryProgress = 0;
handler.post(new Runnable() {
#Override
public void run() {
setProgress(progress);
if (progress == 100) {
dismiss();
}
}
});
}
}
class DownloadFileFromURL extends AsyncTask {
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
// Declear Variables
int count;
try {
URL url1 = new URL(url);
URLConnection conection = url1.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(url1.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString() + "/Report.xls");
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);
Log.d("Downloding"+data,"Count"+count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String reString) {
// dismiss the dialog after the file was downloaded
super.onPostExecute(null);;
dismissDialog(progress_bar_type);
Log.d("Download","Completed");
Intent intent1=new Intent(DownloadExcle.this,MainActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
}
i am working on wallpaper app in which i am downloading image, but now i want to show download process while downloading a image.
what i want is: see this screenshot: http://www.techfeb.com/wp-content/uploads/2012/03/download-facebook-photos-on-android-smartphone-2.jpg
this is my code:
Utils.java
package info.androidhive.awesomewallpapers.util;
import info.androidhive.awesomewallpapers.R;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
#SuppressLint("NewApi")
public class Utils {
private String TAG = Utils.class.getSimpleName();
private Context _context;
private PrefManager pref;
// constructor
public Utils(Context context) {
this._context = context;
pref = new PrefManager(_context);
}
/*
* getting screen width
*/
#SuppressWarnings("deprecation")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) _context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) {
// Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
public void saveImageToSDCard(Bitmap bitmap) {
String dirname = "/Amazing Wallpapers/";
File myDir = new File(Environment
.getExternalStorageDirectory().getPath() + dirname);
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Wallpaper-" +n+".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(
_context,
_context.getString(R.string.toast_saved).replace("#",
"\"" + pref.getGalleryName() + "\""),
Toast.LENGTH_LONG).show();
Log.d(TAG, "Wallpaper saved to:" + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();
}
}
public void setAsWallpaper(Bitmap bitmap) {
try {
WallpaperManager wm = WallpaperManager.getInstance(_context);
wm.setBitmap(bitmap);
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(_context,
_context.getString(R.string.toast_wallpaper_set_failed),
Toast.LENGTH_SHORT).show();
}
}
}
FullScreenActivity.java
package info.androidhive.awesomewallpapers;
import info.androidhive.awesomewallpapers.app.AppController;
import info.androidhive.awesomewallpapers.picasa.model.Wallpaper;
import info.androidhive.awesomewallpapers.util.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.JsonObjectRequest;
public class FullScreenViewActivity extends Activity implements OnClickListener {
private static final String TAG = FullScreenViewActivity.class
.getSimpleName();
public static final String TAG_SEL_IMAGE = "selectedImage";
private Wallpaper selectedPhoto;
private ImageView fullImageView;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
// Picasa JSON response node keys
private static final String TAG_ENTRY = "entry",
TAG_MEDIA_GROUP = "media$group",
TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url",
TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image);
fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
// hide the action bar in fullscreen mode
getActionBar().hide();
utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
Intent i = getIntent();
selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE);
// check for selected photo null
if (selectedPhoto != null) {
// fetch photo full resolution image by making another json request
fetchFullResolutionImage();
} else {
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT)
.show();
}
}
/**
* Fetching image fullresolution json
* */
private void fetchFullResolutionImage() {
String url = selectedPhoto.getPhotoJson();
// show loader before making request
pbLoader.setVisibility(View.VISIBLE);
llSetWallpaper.setVisibility(View.GONE);
llDownloadWallpaper.setVisibility(View.GONE);
// volley's json obj request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,
"Image full resolution json: "
+ response.toString());
try {
// Parsing the json response
JSONObject entry = response
.getJSONObject(TAG_ENTRY);
JSONArray mediacontentArry = entry.getJSONObject(
TAG_MEDIA_GROUP).getJSONArray(
TAG_MEDIA_CONTENT);
JSONObject mediaObj = (JSONObject) mediacontentArry
.get(0);
String fullResolutionUrl = mediaObj
.getString(TAG_IMG_URL);
// image full resolution widht and height
final int width = mediaObj.getInt(TAG_IMG_WIDTH);
final int height = mediaObj.getInt(TAG_IMG_HEIGHT);
Log.d(TAG, "Full resolution image. url: "
+ fullResolutionUrl + ", w: " + width
+ ", h: " + height);
ImageLoader imageLoader = AppController
.getInstance().getImageLoader();
// We download image into ImageView instead of
// NetworkImageView to have callback methods
// Currently NetworkImageView doesn't have callback
// methods
imageLoader.get(fullResolutionUrl,
new ImageListener() {
#Override
public void onErrorResponse(
VolleyError arg0) {
Toast.makeText(
getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(
ImageContainer response,
boolean arg1) {
if (response.getBitmap() != null) {
// load bitmap into imageview
fullImageView
.setImageBitmap(response
.getBitmap());
adjustImageAspect(width, height);
// hide loader and show set &
// download buttons
pbLoader.setVisibility(View.GONE);
llSetWallpaper
.setVisibility(View.VISIBLE);
llDownloadWallpaper
.setVisibility(View.VISIBLE);
}
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
getString(R.string.msg_unknown_error),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
// unable to fetch wallpapers
// either google username is wrong or
// devices doesn't have internet connection
Toast.makeText(getApplicationContext(),
getString(R.string.msg_wall_fetch_error),
Toast.LENGTH_LONG).show();
}
});
// Remove the url from cache
AppController.getInstance().getRequestQueue().getCache().remove(url);
// Disable the cache for this url, so that it always fetches updated
// json
jsonObjReq.setShouldCache(false);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
/**
* Adjusting the image aspect ration to scroll horizontally, Image height
* will be screen height, width will be calculated respected to height
* */
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private void adjustImageAspect(int bWidth, int bHeight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
if (bWidth == 0 || bHeight == 0)
return;
int sHeight = 0;
if (android.os.Build.VERSION.SDK_INT >= 13) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
sHeight = size.y;
} else {
Display display = getWindowManager().getDefaultDisplay();
sHeight = display.getHeight();
}
int new_width = (int) Math.floor((double) bWidth * (double) sHeight
/ (double) bHeight);
params.width = new_width;
params.height = sHeight;
Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width
+ ", h = " + sHeight);
fullImageView.setLayoutParams(params);
}
/**
* View click listener
* */
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
switch (v.getId()) {
// button Download Wallpaper tapped
case R.id.llDownloadWallpaper:
utils.saveImageToSDCard(bitmap);
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
utils.setAsWallpaper(bitmap);
break;
default:
break;
}
}
}
A very good toturial to do so here..
http://www.androidbegin.com/tutorial/android-download-image-from-url/\
A snippet of the code from the site is below:
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Download Image Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// Set the bitmap into ImageView
image.setImageBitmap(result);
// Close progressdialog
mProgressDialog.dismiss();
}
}
You can use ProgressDialog within the onCreate method.
mProgressDialog = new ProgressDialog(YourActivity.this);
You can then add other attributes like a message and so on like this:
mProgressDialog.setMessage("A message");
You can also add listeners like this:
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// Do stuff on Cancel
}
});
Check this link:
Download a file with Android, and showing the progress in a ProgressDialog
i am new in android and i am making a application to download the file from local server and i almost done.But now i want to add progress bar in this code and i am trying to do it. can anyone help me out. just help me if you can dont leave other comments like grammer mistake and other
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends ActionBarActivity
{
Button b1;
String FileDownloadPath="http://192.168.1.25/dinesh/di.mp3";
//String FileSavePath="/dinesh2/lecture3.pdf";
//String DownloadUrl = "http://myexample.com/android/";
String fileName = "di.mp3";
//myFile = new File(path,"/mysdfile.xml");
ProgressDialog dialog=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
dialog=ProgressDialog.show(MainActivity.this,"", "downloading",true);
new Thread(new Runnable()
{
public void run()
{
downlaodfile(FileDownloadPath,fileName);
}
}).start();
}
});
}
public void downlaodfile(String FileDownloadPath, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/sdcard/myclock/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://192.168.1.25/dinesh/di.mp3");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
/* uconn.setReadTimeout(TIMEOUT_CONNECTION);
uconn.setConnectTimeout(TIMEOUT_SOCKET);*/
InputStream is = uconn.getInputStream();
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
int dotindex = fileName.lastIndexOf('.');
if(dotindex>=0){
fileName = fileName.substring(0,dotindex);
}
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
}
catch(Exception e )
{
e.printStackTrace();
}
}
private void hideProgressIndicator() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable(){
public void run()
{
dialog.dismiss();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You should use AsyncTask<...> for your downloading process and use ProgressDialog.
private class ClassName extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(context, "Downloading", "Please Wait...");
}
#Override
protected String doInBackground(String... params)
{
//Your downloading code here
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
//dismiss the progress dialog in onPost and do remaining stuff after downloading....
}
}
hope this will help you...
I'm developing DES decryption in Android platform.
this is my main
package com.example.crack;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Main extends Activity {
public final static String EXTRA_MESSAGE = "com.example.crack.MESSAGE";
public final static String EXTRA_PLAINTEXT = "com.example.crack.PLAINTEXT";
public final static int ENCRYPTION_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendMessage(View view) {
Intent intent = new Intent(this, encryption.class);
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == ENCRYPTION_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
String result = data.getStringExtra(encryption.EXTRA_ENCRYPTION_RETURN);
Intent intent = new Intent(this, DisplayMessage.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
}
}
}
and this is the partial of my encrpytion
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.encryption);
Intent intent = getIntent();
message = intent.getStringExtra(Main.EXTRA_MESSAGE);
//Dictionary
is = getResources().openRawResource(R.raw.english);
in = new BufferedReader(new InputStreamReader(is));
readDic();
String result = "";
try {
result = decryptBruteForce();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent returnIntent = new Intent();
returnIntent.putExtra(EXTRA_ENCRYPTION_RETURN,result);
setResult(RESULT_OK,returnIntent);
finish();
}
when i click on the button, it calls the sendMessage function, while it is running the decryption the screen just black out until it finish running.
I had try using progress bar follow this guide, but not working, I need a button that can stop the process while running.
And is it possible to set a log on view, which show what the function is doing right now? like what is shown in the IDE log? Example, showing what key is the decryption trying right now.
Or maybe just a progress bar or please wait will do too.
I tried to change the sendMessage to this, yet it still black out and crash
public void sendMessage(View view) {
final Intent intent = new Intent(this, encryption.class);
view.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
EditText editText = (EditText) findViewById(R.id.input_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(intent, ENCRYPTION_REQUEST);
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
b.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
if I put sleep to 50000, it did not crash, but still it black out.
You can do it with a Thread and a Handler. While you try each combination, you update the progress bar.
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle savedInstanceState)
{
.... // Other initializations
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mProgress.setMax(dictionaryLength);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
for (int i=0 ; i<dictionaryLength ; i++)
{
mProgressStatus = decryptBruteForce(i);
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
However i recommend you to use AsyncTask to do background operations while you need to update the UI to show the progress or info about whats going on.
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html
Its a good habit to add a cancel control in your loop, so you can finish it from outside of the AsyncTask (for example another button in you UI).
private class DecryptTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... words)
{
long wordsDecrypted = 0;
for (int i = 0; i < words.length ; i++) {
wordsDecrypted += decryptBruteForce(i);
publishProgress(i);
// Escape early if cancel() is called
if (isCancelled())
break;
}
return wordsDecrypted;
}
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Decrypted " + result + " words");
}
}
And you can cancel the AsyncTask from outside with the cancel method:
http://developer.android.com/intl/es/reference/android/os/AsyncTask.html#cancel(boolean)
PD: Codes are not tested, just examples to show how it works