How to browse to destination folder when clicking on download notification - android

From my App, I am downloading some music files and saving them in a folder. In notification panel download progress is shown. When download completes, if notification is clicked, my android device should directly browse to destination folder, similar to "go to folder" on PCs after any download finishes.
I tried it from below code, but it is not working. It is just opening the app.
public class Temp extends Activity {
String[] link;
String[] items;
String song_link;
String song_name;
int song_index;
int link_index;
String url_link;
Exception error;
private ProgressBar mProgress;
long total = 0;
boolean downloadStatus = false;
ProgressDialog progressBar;
private Handler progressBarHandler = new Handler();
int progressBarStatus = 0;
Uri selectedUri;
Intent intent;
PendingIntent resultPendingIntent;
NotificationCompat.Builder mBuilder=
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Downloading");
NotificationManager mNotificationManager;
int id=1;
private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... urls) {
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mProgress = (ProgressBar) findViewById(R.id.progress_bar);
url_link = urls[0];
try {
/* runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"link: "+url_link,Toast.LENGTH_SHORT).show();
}
});*/
int count;
URL url = new URL(url_link);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a typical 0-100% progress bar
final int lenghtOfFile = conexion.getContentLength();
// Download the file
InputStream input = new BufferedInputStream(url.openStream());
// String name = "first.mp3";
File folder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC), "Vaishnav Songs");
if (!folder.mkdirs()) {
Log.e(DOWNLOAD_SERVICE, "Directory not created");
}
File filename = new File(folder,song_name);
OutputStream output = null;
output = new BufferedOutputStream(new FileOutputStream(filename));
byte data[] = new byte[1024];
mBuilder.setContentTitle(song_name);
int percentage;
id = song_index*10 + link_index;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// publishProgress((int)(total*100/lenghtOfFile) );
percentage = (int)(total*100/lenghtOfFile) ;
if(percentage%5 ==0){
new Thread(new Runnable() {
public void run() {
mBuilder.setProgress(100, (int)total*100/lenghtOfFile, false);
// Displays the progress bar for the first time.
mNotificationManager.notify(id, mBuilder.build());
}
}).start();
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mBuilder.setContentIntent(resultPendingIntent);
new Thread(new Runnable() {
public void run() {
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(100,100,false);
mNotificationManager.notify(id, mBuilder.build());
}
}).start();
}
catch (Exception e) {
error = e;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Error: "+error,Toast.LENGTH_SHORT).show();
}
});
}
// Escape early if cancel() is called
// if (isCancelled()) break;
return total;
}
protected void onProgressUpdate(Integer... progress) {
progressBarStatus = progress[0];
}
protected void onPostExecute(Long result) {
/* Toast.makeText(getApplicationContext(),"Downloaded "+result+" bytes",Toast.LENGTH_SHORT).show();*/
Intent intent = getIntent();
finish();
//startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedUri = Uri.parse(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC) + "/"+"Vaishnav Songs"+"/");
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
resultPendingIntent =
PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
song_name = (String) getIntent().getExtras().getString("songName");
song_link = (String) getIntent().getExtras().getString("songLink");
song_index = getIntent().getIntExtra("songIndex",0);
link_index = getIntent().getIntExtra("position",0);
Toast.makeText(getApplicationContext(),"Download started. Check progress in notification panel",Toast.LENGTH_SHORT).show();
//new DownloadFilesTask().execute(song_link);
DownloadFilesTask task = new DownloadFilesTask();
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,song_link);
finish();
}
}

Discover this https://developer.android.com/reference/android/app/Notification.Builder.html
You can try add setContentIntent(PendingIntent intent) to your notification with action for File manager opening.

Related

Manage Queue in android with service

I have a activity with recycler-view, and each list item has a download button.inside button click event i manage make call for download-service.so how can i manage queue when user click more than one download button with custom notification update.
I have googled and tried some solutions are:
1.How to Manage Queue of Runnable Tasks in Android
2.how to handle a queue in android?? java
3.Best way to update Activity from a Queue
but doesn't find the correct way to implement queue with notification update.
Here is my DownloadService Code:
public class DownloadApkService extends Service {
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
String downloadLocation;
String appId = null;
String appLink = null;
String appName = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Queue", "queue");
appId = intent.getStringExtra(Constants.COM_APP_ID);
appLink = intent.getStringExtra(Constants.COM_APP_LINK);
appName = intent.getStringExtra(Constants.COM_APP_NAME);
Thread thread=new Thread(new MyThread(startId));
thread.start();
return START_STICKY;
}
final class MyThread implements Runnable {
int service_id;
MyThread(int service_id) {
this.service_id = service_id;
}
#Override
public void run() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
.setSmallIcon(R.drawable.ic_list_app_icon)
.setContentTitle(appName).setProgress(0, 0, true)
.setContentText("Downloading APK")
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
downloadApk();
}
}
private void downloadApk() {
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
File sourceFile = new File(downloadLocation);
if (sourceFile.exists()) {
sourceFile.delete();
}
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
sendBroadcast(intentResponse);
new DownloadFileFromURL().execute(appLink);
}
public void installApk(Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
DownloadApkService.this.startActivity(install);
}
/**
* Background Async Task to download file
*/
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
Log.e("ULR", f_url[0]);
URL url = new URL(f_url[0].trim());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
Log.e("Length", lenghtOfFile + "");
// download the file
InputStream input = connection.getInputStream();
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
// Output stream
FileOutputStream output = new FileOutputStream(downloadLocation);
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.getStackTrace().toString());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
sendBroadcast(intentResponse);
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
notificationManager.cancel(0);
installApk(Uri.fromFile(new File(downloadLocation)));
}
}
}
any help would be appriciated...
Finally got answer for my own question.
I managed it with Queue class that is in java.util package.
The code i have been used is below:
public class DownloadApkService extends Service {
private NotificationManager notificationManager = null;
String downloadLocation;
String appId = null;
String appLink = null;
String appName = null;
String isApkFromServer = null;
public boolean isDownloading = false;
public static Queue<QueueData> downloadQueue = new LinkedList<>();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (isDownloading) {
QueueData queueData = new QueueData();
queueData.setAppId(intent.getStringExtra(Constants.COM_APP_ID));
queueData.setAppLink(intent.getStringExtra(Constants.COM_APP_LINK));
queueData.setIsApkFromServer(intent.getStringExtra(Constants.COM_APK_FROM_SERVER));
queueData.setAppName(intent.getStringExtra(Constants.COM_APP_NAME));
downloadQueue.add(queueData);
Intent intentQueueingApk = new Intent();
intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
sendBroadcast(intentQueueingApk);
return START_NOT_STICKY;
} else {
appId = intent.getStringExtra(Constants.COM_APP_ID);
appLink = intent.getStringExtra(Constants.COM_APP_LINK);
appName = intent.getStringExtra(Constants.COM_APP_NAME);
isApkFromServer = intent.getStringExtra(Constants.COM_APK_FROM_SERVER);
}
Thread thread = new Thread(new MyThread());
thread.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (notificationManager != null) {
notificationManager.cancel(0);
}
}
class MyThread implements Runnable {
MyThread() {
}
#Override
public void run() {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(DownloadApkService.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(appName).setProgress(0, 0, true)
.setContentText(getResources().getText(R.string.downloading_notification))
.setOngoing(true)
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
new DownloadFileFromURL().execute(appLink);
}
}
public void installApk(Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
DownloadApkService.this.startActivity(install);
}
/**
* Background Async Task to download file
*/
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
isDownloading = true;
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, "0");
sendBroadcast(intentResponse);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
HttpURLConnection connection=null;
try {
String link=f_url[0].replace(" ","%20");
URL url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
int lenghtOfFile = connection.getContentLength();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
downloadLocation = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = appName + ".apk";
downloadLocation += fileName;
File sourceFile = new File(downloadLocation);
if (sourceFile.exists()) {
sourceFile.delete();
}
// Output stream
FileOutputStream output = new FileOutputStream(downloadLocation);
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) {
return "fail";
}finally {
if(connection != null)
connection.disconnect();
}
return "success";
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
intentResponse.putExtra(Constants.COM_APK_DOWNLOAD_PERCENTAGE, progress[0]);
sendBroadcast(intentResponse);
Intent intentQueueingApk = new Intent();
intentQueueingApk.setAction(Constants.ACTION_QUEUEING_APK);
sendBroadcast(intentQueueingApk);
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
notificationManager.cancel(0);
if (file_url.equals("success")) {
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_COMPLETE);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
sendBroadcast(intentResponse);
isDownloading = false;
if (isApkFromServer!=null && isApkFromServer.equals("0")) {
Intent intent = new Intent(DownloadApkService.this, UploadApkService.class);
intent.putExtra(Constants.COM_APP_ID, mAppDetails.getId());
intent.putExtra(Constants.COM_APK_FILE_PATH, downloadLocation);
startService(intent);
}
installApk(Uri.fromFile(new File(downloadLocation)));
} else if (file_url.equals("fail")) {
isDownloading = false;
Intent intentResponse = new Intent();
intentResponse.setAction(Constants.ACTION_DOWNLOADING_APK_FAILED);
intentResponse.putExtra(Constants.COM_APP_ID, appId);
sendBroadcast(intentResponse);
}
if (/*isDownloading &&*/ !downloadQueue.isEmpty()) {
QueueData queueData = downloadQueue.poll();
appId = queueData.getAppId();
appLink = queueData.getAppLink();
appName = queueData.getAppName();
isApkFromServer = queueData.getIsApkFromServer();
Thread thread = new Thread(new MyThread());
thread.start();
}
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
if (notificationManager != null)
notificationManager.cancel(0);
}
}
I hope it's going to be helpful for someone.

AlertDialog and service

Hi i am developing one android app where i upload multipal images to the server using Service that means i upload the images to server even my app is closed from background..
Also i displayed Nootification and displayed progress of image uploading in the notification .
The main problem is that i displayed alert dialog when all uploading is completed.But when i close the app then also that dialog is appeared on the screen.
i.e.
if i pause the app or hide the app then that alert dialog will display at home screen
i want to display alert dialog
here is my service
static public class UploadService extends Service {
private String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i = 0;
long totalSize=0;
NotificationManager manager;
String response_str = null;
long totalprice = 0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;
NotificationCompat.Builder mBuilder;
String strsize, strtype, usermail, total, strmrp, strprice, strlab, strcity, abc, strdel_type, struname, imageName;
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), dataT);
Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
strsize = intent.getStringExtra("strsize");
strtype = intent.getStringExtra("strtype");
usermail = intent.getStringExtra("user_mail");
strmrp = intent.getStringExtra("strmrp");
strprice = intent.getStringExtra("strprice");
strlab = intent.getStringExtra("strlab");
strcity = intent.getStringExtra("strcity");
struname = intent.getStringExtra("strusername");
strdel_type = intent.getStringExtra("strdel_type");
abc = intent.getStringExtra("foldername");
manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Upload")
.setContentText("Upload in progress")
.setSmallIcon(R.drawable.ic_launcher);
Intent resultIntent = new Intent(this, SelectPhotos.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
resultIntent.setAction("android.intent.action.MAIN");
resultIntent.addCategory("android.intent.category.LAUNCHER");
new UploadFileToServer().execute();
return Service.START_NOT_STICKY;
}
public class MyBinder extends Binder {
UploadService getService() {
return UploadService.this;
}
}
private class UploadFileToServer extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
pb.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("Abhijit122", "" + String.valueOf(progress[0]) + "%");
pb.setProgress(progress[0]);
tp.setText(String.valueOf(progress[0]) + "%");
Log.e("ef", "df" + incr);
ti.setText((incr+1)+"/"+listOfPhotos.size());
}
#Override
protected String doInBackground(String... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
for (incr = 0; incr < listOfPhotos.size(); incr++) {
mBuilder.setProgress(listOfPhotos.size(), incr, false);
manager.notify(1, mBuilder.build());
try {
File f = new File(listOfPhotos.get(i).sdcardPath.toString());
int j = i + 1;
j++;
imageName = f.getName();
totalprice = totalprice + Long.parseLong(strprice);
total = String.valueOf(totalprice);
Log.e("Totalprice", " " + total);
String responseString = null;
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(URL); //TODO - to hit URL);
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strsize));
entity.addPart("type",
new StringBody(strtype));
entity.addPart("username",
new StringBody(usermail));
entity.addPart("total",
new StringBody(total));
Log.e("Totalprice", "adf " + total);
entity.addPart("mrp",
new StringBody(strmrp));
entity.addPart("price",
new StringBody(strprice));
entity.addPart("lab",
new StringBody(strlab));
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
entity.addPart("initflag",
new StringBody(""+initflag++));
entity.addPart("lab_username",
new StringBody(struname));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
response_str = EntityUtils.toString(r_entity);
Log.d("Dhruva", "" + response_str);
if (r_entity != null) {
Log.v("Abhijit", "" + response_str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return response_str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mBuilder.setContentText("Upload complete")
// Removes the progress bar
.setProgress(0, 0, false);
manager.notify(1, mBuilder.build());
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("Success")
.setMessage("Successfully uploaded images...")
.setCancelable(false)
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
}
}
i want to display alert dialog when all uploading is completed and when i click on ok button i want to start next activity.
This is my way to open next activity after successful uploading of images through service.also i implemented notification then which activity should i open when i click on notification
If there is another way please give me suggestion.

Cancel AsyncTask inside ListArrayAdapter and dismiss notification

The aim of the application is to offer a simple way to download and extract a bunch of archives (~200mo), to delete it, and to open it. The download display a notification which display the progress.
I'm using a ListView to display every archive that can be downloaded. Each array contain an image, some text, and two buttons (for reading/deleting, downloading, or cancel). The data are retrieved from a json.
I've got some issues while I try to cancel the AsyncTask which display the notification and download the file. When I call the async.cancel(true);, the notification and the download are still running.
Maybe am I calling the asyncTask from the wrong place, but I don't know how to fix this.
My adapter :
public class ListArrayAdapter extends ArrayAdapter<String> {
private final Context context;
public Drawable d;
private ArrayList<HashMap<String, String>> list;
public boolean finishDownload = false;
JSONArray jsonArray;
// Constructor
public ListArrayAdapter(Context context, List<String> values,
ArrayList<HashMap<String, String>> list) {
super(context, R.layout.activity_list_array_adapter, values);
this.context = context;
this.list = list;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_list_array_adapter,
parent, false);
// Déclaration
TextView date = (TextView) rowView.findViewById(R.id.date);
TextView title = (TextView) rowView.findViewById(R.id.title);
TextView description = (TextView) rowView.findViewById(R.id.description);
ImageView imageView = (ImageView) rowView.findViewById(R.id.cover);
ProgressBar pd = (ProgressBar) rowView.findViewById(R.id.progress);
final Button button1 = (Button) rowView.findViewById(R.id.button1);
final Button button2 = (Button) rowView.findViewById(R.id.button2);
// Fill the array with the json file
title.setText(list.get(position).get("Title"));
date.setText(list.get(position).get("Date"));
description.setText(list.get(position).get("Description"));
new ParseImage(position, imageView, pd).execute();
final File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/Magazine/" + list.get(position).get("Name") + ".zip");
//If the file exist, let the user open it
if (file.exists()) {
button1.setText("Lire");
button2.setVisibility(View.VISIBLE);
button2.setText("Supprimer");
}
// else, let the user download it
else {
button1.setText("Télécharger");
button2.setVisibility(View.GONE);
}
final DownloadTask async = new DownloadTask(context, position, list);
button1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (button1.getText() == "Télécharger") {
button1.setEnabled(false);
button2.setVisibility(View.VISIBLE);
button2.setText("Annuler");
finishDownload = false;
async.execute(0);
} else if (button1.getText() == "Lire") {
Intent i1 = new Intent(context, WebActivity.class);
context.startActivity(i1);
}
}
});
button2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
if (button2.getText() == "Annuler") {
async.cancel(true);
button1.setEnabled(true);
button2.setVisibility(View.GONE);
button1.setText("Télécharger");
} else if (button2.getText() == "Supprimer") {
button1.setEnabled(true);
button2.setVisibility(View.GONE);
button1.setText("Télécharger");
if (file.exists()) {
file.delete();
}
}
}
});
return rowView;
}
public class DownloadTask extends AsyncTask<Integer, Integer, Void> {
private NotificationHelper mNotificationHelper;
public int position;
public ArrayList<HashMap<String, String>> list;
public DownloadTask(Context context, int position,
ArrayList<HashMap<String, String>> list) {
mNotificationHelper = new NotificationHelper(context);
this.position = position;
this.list = list;
}
#Override
protected void onPreExecute() {
mNotificationHelper.createNotification();
}
#Override
protected Void doInBackground(Integer... integers) {
int count = 0;
try {
Thread.sleep(1);
URL url = new URL(list.get(position).get("Content"));
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().getPath()
+ "/Magazine/"
+ list.get(position).get("Name")
+ ".zip");
byte data[] = new byte[1024];
long total = 0;
int progress_temp = 0;
while ((count=input.read(data)) != -1)
{
total += count;
progress_temp = (int) total*100/lenghtOfFile;
output.write(data, 0, count);
}
publishProgress(progress_temp);
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
mNotificationHelper.progressUpdate(progress[0]);
}
#Override
protected void onCancelled() {
mNotificationHelper.completed();
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
mNotificationHelper.completed();
finishDownload = true;
}
}
}
The notificationHelper class which manage the notification :
public class NotificationHelper {
private Context mContext;
private int NOTIFICATION_ID = 1;
private Notification mNotification;
private NotificationManager mNotificationManager;
private PendingIntent mContentIntent;
private CharSequence mContentTitle;
public NotificationHelper(Context context) {
mContext = context;
}
#SuppressWarnings("deprecation")
public void createNotification() {
mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_sys_download;
CharSequence tickerText = mContext.getString(R.string.download_ticker);
long when = System.currentTimeMillis();
mNotification = new Notification(icon, tickerText, when);
mContentTitle = mContext.getString(R.string.content_title);
CharSequence contentText = "0% téléchargé";
Intent notificationIntent = new Intent(mContext, MainActivity.class);
mContentIntent = PendingIntent.getActivity(mContext, 0,
notificationIntent, 0);
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);
mNotification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
#SuppressWarnings("deprecation")
public void progressUpdate(int percentageComplete) {
CharSequence contentText = percentageComplete + "% téléchargé";
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}
public void completed() {
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
The cancel() method on AsyncTasks (confusingly) doesn't actually stop the Thread from running, but rather sets a flag on the Task. You can find some discussion about that here. It seems that currently, if you want your Thread to actually stop mid-execution, you'll need to manually check that flag in your looping code using the isCancelled() method. For example, in your while loop in doInBackground:
while ((count=input.read(data)) != -1)
{
total += count;
progress_temp = (int) total*100/lenghtOfFile;
output.write(data, 0, count);
if(isCancelled())
{
//Code here that may...
// break out of the loop,
// stop the thread,
// close the notification,
// perform any cleanup, etc...
}
}
You can find another example of this in the AsyncTask docs under the "Usage" header. Hope this helps!

How to run some code when user click on the notification?

I have a some thread that opens progress dialog and downloads a file. While thread downloads the file, it update progress bar. But if progress dialog was hidden, thread creates a notification and updating progress bar in the notification. I wanna make this: when user click on the notification, Android opens Activity and showing progress dialog.
How can I do this?
That is my method that downloading a file:
public void downloadAction(int id) {
if(id<0 || id>data.length) { IO.showNotify(MusicActivity.this, getResources().getStringArray(R.array.errors)[4]); return; }
final int itemId = id;
AsyncTask<Void, Integer, Boolean> downloadTask = new AsyncTask<Void, Integer, Boolean>() {
ProgressDialog progressDialog = new ProgressDialog(MusicActivity.this);
String error = null;
int nId = -1;
int progressPercent = 0;
boolean notificated = false;
int urlFileLength;
String FILE_NAME = fileName(data.getName(itemId));
#Override
protected void onPreExecute() {
progressDialog.setTitle(data.getName(itemId));
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
progressDialog.setButton(Dialog.BUTTON_POSITIVE, getResources().getString(R.string.hide), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
progressDialog.hide();
}
});
progressDialog.setButton(Dialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(progressDialog.isShowing()) { cancel(true); progressDialog.dismiss();}
}
});
progressDialog.show();
progressDialog.setProgressNumberFormat("");
}
#Override
protected Boolean doInBackground(Void... params) {
int localFileLength, len;
int fullProgress = 0;
byte[] bytes = new byte[1024];
File rootDir = new File(PATH);
if(!rootDir.isDirectory()) rootDir.mkdir();
try {
URLConnection urlConnection = new URL(data.getUrl(itemId)).openConnection();
urlConnection.setConnectTimeout(20000);
urlConnection.setReadTimeout(60000);
localFileLength = (int) new File(FILE_NAME).length();
urlFileLength = urlConnection.getContentLength();
if (urlFileLength == 169 || urlFileLength == 0 || urlFileLength == -1) {
error = getResources().getStringArray(R.array.errors)[5];
return false;
}
if (urlFileLength == localFileLength) {
error = getResources().getString(R.string.file_exist);
return false;
} else {
publishProgress(0, urlFileLength);
InputStream in = urlConnection.getInputStream();
OutputStream out = new FileOutputStream(FILE_NAME);
while((len=in.read(bytes))!=-1) {
if(!isCancelled()) {
out.write(bytes, 0, len);
fullProgress += len;
publishProgress(fullProgress);
} else {
new File(FILE_NAME).delete();
error = getResources().getString(R.string.stopped);
return false;
}
}
}
} catch (MalformedURLException e) {
new File(FILE_NAME).delete();
error = getResources().getStringArray(R.array.errors)[2];
} catch (IOException e) {
new File(FILE_NAME).delete();
error = getResources().getStringArray(R.array.errors)[3];
}
return true;
}
#Override
protected void onProgressUpdate(Integer ... progress) {
int tmp;
if (progress.length==2) {
progressDialog.setProgress(progress[0]);
progressDialog.setMax(progress[1]);
} else if(progress.length==1) {
if(!progressDialog.isShowing()) {
if(!notificated) {
nId = NotificationUtils.getInstace(MusicActivity.this).createDownloadNotification(data.getName(itemId));
notificated = true;
} else {
tmp = (int) (progress[0]/(urlFileLength*0.01));
if(progressPercent!=tmp) {
progressPercent = tmp;
NotificationUtils.getInstace(MusicActivity.this).updateProgress(nId, progressPercent);
}
}
} else {
progressDialog.setProgress(progress[0]);
}
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result==true && error == null) {
if(progressDialog.isShowing()) {
IO.showNotify(MusicActivity.this, getResources().getString(R.string.downloaded) + " " + PATH);
progressDialog.dismiss();
} else if (nId!=-1) {
NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(data.getName(itemId) + " " + getResources().getString(R.string.finished));
}
} else {
if(progressDialog.isShowing()) {
IO.showNotify(MusicActivity.this, error);
progressDialog.dismiss();
} else if (nId!=-1){
NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(getResources().getString(R.string.error) + "! " + error);
}
}
}
#Override
protected void onCancelled() {
IO.showNotify(MusicActivity.this, getResources().getString(R.string.stopped));
}
};
if(downloadTask.getStatus().equals(AsyncTask.Status.PENDING) || downloadTask.getStatus().equals(AsyncTask.Status.FINISHED))
downloadTask.execute();
}
And that is two methods thats creating notification:
public int createDownloadNotification(String fileName) {
String text = context.getString(R.string.notification_downloading).concat(" ").concat(fileName);
RemoteViews contentView = createProgressNotification(text, text);
contentView.setImageViewResource(R.id.notification_download_layout_image, android.R.drawable.stat_sys_download);
return lastId++;
}
private RemoteViews createProgressNotification(String text, String topMessage) {
Notification notification = new Notification(android.R.drawable.stat_sys_download, topMessage, System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_download_layout);
contentView.setProgressBar(R.id.notification_download_layout_progressbar, 100, 0, false);
contentView.setTextViewText(R.id.notification_download_layout_title, text);
notification.contentView = contentView;
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;
Intent notificationIntent = new Intent(context, NotificationUtils.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
manager.notify(lastId, notification);
notifications.put(lastId, notification);
return contentView;
}
Help me please...
I am not sure, but in my code of notification I have no notification.contentIntent = contentIntent; and you seem to be missing this before the manager.notify(lastId, notification); line:
notification.setLatestEventInfo(context, MyNotifyTitle, MyNotifiyText, contentIntent );
MyNotifyTitle is the Title of the Notification, MyNotifyText is the text. Add them before the contentIntent as
MyIntent.putExtra("extendedTitle", notificationIntent );
MyIntent.putExtra("extendedText" , notificationIntent );
Hope this helps.

Progress bar is not showing on phone after clicking on notification status bar

When i am downloading the file from the server its downloading well,in the notification status bar its showing the progress bar but when i selecting from the notification status bar it will open that application but at that time progress bar is not showing in the phone but its working fine on emulator.Please help me out......
Thanks..
public class FileDownloadTestActivity extends Activity {
private static String url = "http://www.xxxxx.in/build/android/android/xyz.apk";
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.download);
Boolean boolean1=true;
if(boolean1){
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new DownloadFileAsync().execute(url);
}
});
boolean1=false;
}
}
#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<String, String, String> {
NotificationManager notificationManager;
Notification notification2;
#Override
protected void onPreExecute() {
super.onPreExecute();
notification2 = new Notification(android.R.drawable.stat_sys_download, "downloading..." , System.currentTimeMillis());
Intent intent = new Intent(getApplicationContext(),FileDownloadTestActivity.class);
intent .setAction("android.intent.action.MAIN");
intent .addCategory("android.intent.category.LAUNCHER");
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notification2 = new Notification(android.R.drawable.stat_sys_download, "downloading..." , System.currentTimeMillis());
notification2.flags = notification2.flags | Notification.FLAG_ONGOING_EVENT;
notification2.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.custom_notification_layout);
notification2.contentIntent = pendingIntent;
notification2.contentView.setImageViewResource(R.id.status_icon,R.drawable.junow );
notification2.contentView.setProgressBar(R.id.status_progress, 100, 1, false);
getApplicationContext();
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
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();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+"/xyz.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
long var=(int) ((total * 100) / lenghtOfFile);
publishProgress("" +var);
output.write(data, 0, count);
notificationManager.notify(1, notification2);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
notification2.contentView.setProgressBar(R.id.status_progress, 100,Integer.parseInt(progress[0]), false);
notification2.contentView.setTextViewText(R.id.percent,"Downloading in progress "+progress[0]+" %");
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
notificationManager.cancel(1);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/xyz.apk")), "application/vnd.android.package-archive");
startActivity(intent);
}
}
}

Categories

Resources