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

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.

Related

How to get context in service outside of onStartCommand() method?

When I use Intent outside of onStartCommand() of service, to show notification on a specific event, it shows getApplicationContext on the null object reference.
Service only allow to use getApplcationContext/this/context inside the onStartCommand() method.
How can I use it outside of onStartCommand() method?
Below is my Service. Can someone help me out with this?
public class ForegroundService extends Service {
#Nullable
private static TransferUtility transferUtility;
private static ArrayList<HashMap<String, Object>> transferRecordMaps;
private static ArrayList<HashMap<String, Object>> transferRecordMaps1;
private Utils utils = new Utils();
private static final int INDEX_NOT_CHECKED = -1;
public static int totalcount, totalAssetCount;
private int checkedIndex;
private static List<TransferObserver> observers;
private static int REQUEST_CAMERA = 0, navigate = 0,counter=0,failedcounter=0;
private static final String LOG_TAG = "ForegroundService";
UploadMediaToAssetFragment uploadMediaToAssetFragment;
private int progress;
Context context;
private long currentbyte, totalbyte;
private Notification notification;
#Override
public void onCreate() {
super.onCreate();
transferUtility = Util.getTransferUtility(getApplicationContext());
checkedIndex = INDEX_NOT_CHECKED;
transferRecordMaps = new ArrayList<HashMap<String, Object>>();
transferRecordMaps1 = new ArrayList<HashMap<String, Object>>();
uploadMediaToAssetFragment = new UploadMediaToAssetFragment();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Intent notificationIntent = new Intent(this, UploadMediaToAssetFragment.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
Log.d(LOG_TAG,"bytes"+UploadMediaToAssetFragment.totalAssetCount+ " total"+UploadMediaToAssetFragment.totalcount);
uploadAsset();
initData();
updateList();
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Test dialog");
// builder.setIcon(R.drawable.icon);
// builder.setMessage("Content");
//
// AlertDialog alert = builder.create();
// alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alert.show();
// startActivity(notificationIntent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ForegroundService.class);
previousIntent.setAction(Constants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(Constants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, ForegroundService.class);
nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
PendingIntent pnextIntent = PendingIntent.getService(this, 0,
nextIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Visibly")
.setTicker("asset uplaoding")
.setContentText("uploading")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.setProgress(100,progress,false)
.addAction(android.R.drawable.ic_menu_close_clear_cancel,
"cancel", ppreviousIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
// if(UploadMediaToAssetFragment.totalAssetCount>=UploadMediaToAssetFragment.totalcount)
// {
// onDestroy();
// stopForeground(true);
// stopSelf();
// }
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
Log.i(LOG_TAG, "Clicked Previous");
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
Log.i(LOG_TAG, "Clicked Play");
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
Log.i(LOG_TAG, "Clicked Next");
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
public IBinder onBind(Intent intent) {
return null;
}
public class ForegroundServiceBInder extends Binder {
ForegroundService getService() {
// Return this instance of LocalService so clients can call public methods
return ForegroundService.this;
}
}
public void uploadAsset()
{
Log.d("upload asset service","method called");
for(int i=0;i<AddMediaAssetActivity.galleryDTOArrayList1.size();i++)
{
Handler handler1 = new Handler();
try {
if(AddMediaAssetActivity.galleryDTOArrayList1.get(i)!=null)
{
String path;
Uri uri = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getMediaName()));
path = Utility.getPath(uri, getApplicationContext());
Uri uriThumb = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getThumbnail()));
String pathThum = null;
if (uriThumb != null)
pathThum = Utility.getPath(uriThumb, getApplicationContext());
path = Utility.getPath(uri, getApplicationContext());
if(GlobalVariables.isNetworkAvailable(getApplicationContext())) {
beginUpload1(pathThum, pathThum);
beginUpload(path, AddMediaAssetActivity.galleryDTOArrayList1.get(i).getDescription(), pathThum,AddMediaAssetActivity.galleryDTOArrayList1.get(i).getCreateTagPostDTOList());
}else
{
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getApplicationContext(),android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getApplicationContext());
}
builder.setMessage(getResources().getString(R.string.network_connectivity))
.setTitle("");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
//getApplicationContext().finish();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.clear_blue));
}
}
}catch (Exception e)
{
}
}
}
/*
* Begins to upload the file specified by the file path.
*/
private void beginUpload(String filePath, String title, String pathThum, List<TagDTO> createTagPostDTOList)
{
Log.d("beginUpload","method called "+filePath+" title "+title+" pathnum "+pathThum+" list tagdto"+createTagPostDTOList);
if (filePath == null) {
Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
file, CannedAccessControlList.PublicRead);
File file1 = new File(pathThum);
AssetMediaDTO assetMediaDTO=new AssetMediaDTO();
if(GlobalVariables.isCampaignAsset)
{
if (GlobalVariables.campaignFeedDTO.getCampaign_category() != null && GlobalVariables.campaignFeedDTO.getCampaign_category().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_category().equalsIgnoreCase("null"))) {
assetMediaDTO.setCategory_id(GlobalVariables.campaignFeedDTO.getCampaign_category());
} else {
assetMediaDTO.setCategory_id("rpPDp");
}
if (GlobalVariables.campaignFeedDTO.getCampaign_folder() != null && GlobalVariables.campaignFeedDTO.getCampaign_folder().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("null"))) {
if(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("General"))
{
assetMediaDTO.setFolder_id("");
}else
{
assetMediaDTO.setFolder_id(GlobalVariables.campaignFeedDTO.getCampaign_folder());
}
} else
{
assetMediaDTO.setFolder_id("");
}
}else
{
if (AssetFolderActivity.folderDTO.getCategoryID() != null && AssetFolderActivity.folderDTO.getCategoryID().length() > 0 && !(AssetFolderActivity.folderDTO.getCategoryID().equalsIgnoreCase("null"))) {
assetMediaDTO.setCategory_id(AssetFolderActivity.folderDTO.getCategoryID());
} else {
assetMediaDTO.setCategory_id("rpPDp");
}
if (AssetFolderActivity.folderDTO.getFolderIdentity() != null && AssetFolderActivity.folderDTO.getFolderIdentity().length() > 0 && !(AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("null"))) {
if(AssetFolderActivity.folderDTO.getFoldername()!=null&&AssetFolderActivity.folderDTO.getFoldername().equalsIgnoreCase("general"))
{
assetMediaDTO.setFolder_id("");
}else {
assetMediaDTO.setFolder_id(AssetFolderActivity.folderDTO.getFolderIdentity());
}
} else {
assetMediaDTO.setFolder_id("");
}
}
assetMediaDTO.setMedia_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file.getName());
assetMediaDTO.setThumbnail_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file1.getName());
try {
assetMediaDTO.setMediaSize(""+file.length());
}catch (Exception e)
{
}
assetMediaDTO.setDetail(title);
String result = file.getName().substring(0, file.getName().lastIndexOf("."));
assetMediaDTO.setTitle(result);
assetMediaDTO.setTagDTOList(createTagPostDTOList);
GlobalVariables.assetMediaDTOList.add(assetMediaDTO);
}
/*
* Begins to upload the file specified by the file path.
*/
private void beginUpload1(String filePath, String pathThum) {
Log.d("beginUpload1","method called");
if (filePath == null) {
Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
file,CannedAccessControlList.PublicRead);
// temp1=file.getName();
}
//To delete assets from list
public void deleteMediaUpload(final int position)
{
final int position1=position+1;
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(GlobalVariables.mActivity, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(GlobalVariables.mActivity);
}
builder.setMessage("Do you want to delete this media?")
.setTitle("");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
if (position >= 0 && position1 < observers.size())
{
try {
transferUtility.deleteTransferRecord(observers.get(position).getId());
transferUtility.deleteTransferRecord(observers.get(position1).getId());
observers.remove(position1);
transferRecordMaps.remove(position1);
observers.remove(position);
transferRecordMaps.remove(position);
AddMediaAssetActivity.galleryDTOArrayList1.remove(position);
}catch (Exception e)
{
}
updateList();
try {
GlobalVariables.assetMediaDTOList.remove(position);
}catch (Exception e)
{
}
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
}
// /**
// * Gets all relevant transfers from the Transfer Service for populating the
// * UI
// */
// private void initData() {
// counter=0;
// failedcounter=0;
// navigate=0;
// transferRecordMaps.clear();
// transferRecordMaps1.clear();
// // Use TransferUtility to get all upload transfers.
// observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
// TransferListener listener = new UploadMediaToAssetFragment.UploadListener();
// for (TransferObserver observer : observers) {
//
// // For each transfer we will will create an entry in
// // transferRecordMaps which will display
// // as a single row in the UI
// HashMap<String, Object> map = new HashMap<String, Object>();
// Util.fillMap(map, observer, false);
//
// transferRecordMaps.add(map);
//
// // Sets listeners to in progress transfers
// if (TransferState.WAITING.equals(observer.getState())
// || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
// || TransferState.IN_PROGRESS.equals(observer.getState())) {
// observer.setTransferListener(listener);
// }
// }
// transferRecordMaps1.clear();
// for(int i=0;i<transferRecordMaps.size();i++)
// {
// File file = new File((String) transferRecordMaps.get(i).get("fileName"));
// if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
// {
// }
// else
// {
// transferRecordMaps1.add(transferRecordMaps.get(i));
//
// }
//
// }
// assetListAdapter.notifyDataSetChanged();
// }
/*
* A TransferListener class that can listen to a upload task and be notified
* when the status changes.
*/
public class UploadListener implements TransferListener {
// Simply updates the UI list when notified.
#Override
public void onError(int id, Exception e)
{
failedcounter++;
updateList();
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
updateList();
currentbyte =bytesCurrent;
totalbyte =bytesTotal;
Log.d("onprogresschnaged","method bytes"+bytesCurrent+" bytestotoal"+bytesTotal);
}
#Override
public void onStateChanged(int id, TransferState newState)
{
if (newState.equals(TransferState.COMPLETED))
{
counter++;
updateList();
} else if (newState.equals(TransferState.FAILED))
{
failedcounter++;
updateList();
}
}
}
/*
* Updates the ListView according to the observers.
*/
/*
* Updates the ListView according to the observers.
*/
public void updateList()
{
if(transferRecordMaps!=null&&transferRecordMaps.size()>0)
{
TransferObserver observer = null;
HashMap<String, Object> map = null;
for (int i = 0; i < observers.size(); i++) {
observer = observers.get(i);
map = transferRecordMaps.get(i);
progress = (int) ((double) observer.getBytesTransferred() * 100 / observer
.getBytesTotal());
Log.d("progressuploadingData"," map"+progress);
Util.fillMap(map, observer, i == checkedIndex);
Log.d("uploadingData"," map"+map+" observer"+observer);
}
transferRecordMaps1.clear();
for (int i = 0; i < transferRecordMaps.size(); i++)
{
File file = new File((String) transferRecordMaps.get(i).get("fileName"));
if (file.getName().substring(0, 2).equalsIgnoreCase("0!")) {
} else
{
transferRecordMaps1.add(transferRecordMaps.get(i));
}
totalcount=transferRecordMaps.size();
totalAssetCount=counter+failedcounter;
Log.d("totalcount","count"+totalcount+"toatlassetcount"+totalAssetCount);
if(counter>1&&totalAssetCount>=totalcount&&GlobalVariables.assetMediaDTOList.size()>0)
{
Log.d("myservice asset","complete");
navigate=1;
Intent intent = new Intent(this, DialogeActivity.class);
context.getApplicationContext().startActivity(intent);
// Toast.makeText(this,"Your asset uploaded successfully",Toast.LENGTH_LONG).show();
// Intent notificationIntent = new Intent(this, DialogeActivity.class);
// notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
// notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(notificationIntent);
// Notification notification = new NotificationCompat.Builder(this)
// .setContentTitle("Visibly")
// .setTicker("asset uploaded")
// .setContentText("asset uploaded successfully")
// .setSmallIcon(R.drawable.ic_launcher)
// .build();
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Test dialog");
// builder.setIcon(R.drawable.icon);
// builder.setMessage("Content");
// builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// //Do something
// dialog.dismiss();
// });
//
// AlertDialog alert = builder.create();
// alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alert.show();
// AlertDialog alertDialog = new AlertDialog.Builder(this)
// .setTitle("Title")
// .setMessage("Are you sure?")
// .create();
//
// alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alertDialog.show();
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Done");
// button_Done.setEnabled(true);
// button_Done.setClickable(true);
}else if(failedcounter>=totalcount)
{
navigate=0;
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Back");
// button_Done.setEnabled(true);
// button_Done.setClickable(true);
}else
{
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Please wait.");
// button_Done.setEnabled(false);
// button_Done.setClickable(false);
}
}
// assetListAdapter.notifyDataSetChanged();
}else
{
// Intent intent=null;
// if( AssetFolderActivity.folderDTO!=null&&AssetFolderActivity.folderDTO.getFolderIdentity()!=null&& AssetFolderActivity.folderDTO.getFolderIdentity().length()>0&&!AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("")) {
// intent = new Intent(activity, AssetFolderActivity.class);
// }else
// {
// intent = new Intent(activity, DashboardActivity.class);
// }
// intent.putExtra("folderDTO", AssetFolderActivity.folderDTO);
// activity.startActivity(intent);
// activity.finish();
}
}
private void initData() {
counter=0;
failedcounter=0;
navigate=0;
transferRecordMaps.clear();
transferRecordMaps1.clear();
// Use TransferUtility to get all upload transfers.
observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
TransferListener listener = new ForegroundService().new UploadListener();
for (TransferObserver observer : observers) {
// For each transfer we will will create an entry in
// transferRecordMaps which will display
// as a single row in the UI
HashMap<String, Object> map = new HashMap<String, Object>();
Util.fillMap(map, observer, false);
transferRecordMaps.add(map);
// Sets listeners to in progress transfers
if (TransferState.WAITING.equals(observer.getState())
|| TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
|| TransferState.IN_PROGRESS.equals(observer.getState())) {
observer.setTransferListener(listener);
}
}
transferRecordMaps1.clear();
for(int i=0;i<transferRecordMaps.size();i++)
{
File file = new File((String) transferRecordMaps.get(i).get("fileName"));
if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
{
}
else
{
transferRecordMaps1.add(transferRecordMaps.get(i));
}
}
// assetListAdapter.notifyDataSetChanged();
}
}
Service only allow to use getApplcationContext/this/context inside the onStartCommand() method
There is no such restriction. You can use it from other methods on your Service, so long as onCreate() has already been called on that Service.
So, to show a Notification from some background thread that your Service forks from onStartCommand(), for example, use this.
Service is child of Context class, that would provide you context when you need. It behaves like an activity (child of context too.)
So same like Activity, you can call this or yourService.this(in anonymus class) keyword as a context.
In updateList() you do this:
context.getApplicationContext().startActivity(intent);
context is a member variable of your Service. However, you never initialize this variable to anything. Therefore it is null, which will cause the error you describe.
Sevices has his own context. There is easy way to have an globl context.
private Context context;
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
context = this;
}
That's all. Should work, if not let search an problem in other place.
#Edit
For clarity, your problem causes this line, because your context is not assigned, and it's null.
context.getApplicationContext().startActivity(intent);

Android: Unable to update custom notification when I kill my app

I am downloading multiple files one after the other in service. I want to update download progress in notification. But my notification doesn't update when I kill my app. Download works on different thread. Download works fine in when app is running. When I kill app from recent section, I am unable to update notification.
Here is my DownloadService class
public class DownloadService extends Service {
public static DownloadMap<String, Downloadables> map = new DownloadMap<String, Downloadables>();
private static Thread thread;
private DownloadCancelReceiver receiver;
public DownloadService() {
}
public class BackgroundThread extends Thread {
int serviceId;
private DownloadMap<String, Downloadables> map;
private SpeedRevisionDatabase helper;
private final int notificationId = 1;
private RemoteViews remoteViewsSmall, remoteViewsBig;
private NotificationManagerCompat notificationManager;
private NotificationCompat.Builder mBuilder, mBuilderComplete, downloadFailBuilder;
public BackgroundThread(int serviceId, DownloadMap<String, Downloadables> map) {
this.serviceId = serviceId;
this.map = new DownloadMap<>();
this.map.putAll(map);
}
#Override
public void run() {
remoteViewsSmall = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notification_small);
remoteViewsBig = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notification);
Intent cancelDownload = new Intent("CANCEL_DOWNLOAD");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, cancelDownload, 0);
remoteViewsBig.setOnClickPendingIntent(R.id.tvCancel, pendingIntent);
notificationManager = NotificationManagerCompat.from(DownloadService.this);
mBuilder = new NotificationCompat.Builder(DownloadService.this, "default");
initChannels(DownloadService.this);
mBuilder.setContentTitle("Download is in progress")
.setContentText("Please wait...")
.setSmallIcon(R.mipmap.download)
.setOngoing(true)
.setCustomContentView(remoteViewsSmall)
.setCustomBigContentView(remoteViewsBig)
.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationManager.notify(notificationId, mBuilder.build());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
String path = getApplicationContext().getApplicationInfo().dataDir + "/" + "UEP";
File uepFolder = new File(path);
if (!uepFolder.exists()) {
uepFolder.mkdir();
}
int i = 0;
while (map.entrySet().iterator().hasNext()) {
Log.e("WhileCheck", "Now i is " + i);
Map.Entry data = (Map.Entry) map.entrySet().iterator().next();
try {
Downloadables download = (Downloadables) data.getValue();
if (NetworkUtil.getConnectivityStatus(getApplicationContext()) == 0) {
throw new InternetDisconnectedException("Internet Disconnected");
}
HttpURLConnection urlConnection;
InputStream inputStream;
//finding file on internet
try {
URL url = new URL(download.URL);
if (url.toString().endsWith(".xps")) {
url = new URL(url.toString().replace(".xps", ".pdf"));
}
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
inputStream = urlConnection.getInputStream();
} catch (IOException e) {
Log.e("IOException", "" + e.getMessage());
i++;
map.remove(data.getKey());
notificationManager.notify(notificationId, mBuilder.build());
continue;
}
//Downloading file over internet
File file = new File(uepFolder + "/" + download.FileName + "" + download.Format + ".download");
try {
int fileSize = urlConnection.getContentLength();
FileOutputStream fileOutput = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
int count = 0;
int previousProgress = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
if (this.isInterrupted()) {
throw new InterruptedException("Thread has been kill (Destroyed)");
}
fileOutput.write(buffer, 0, bufferLength);
count += bufferLength;
int progress = (int) (count * 100L / (float) fileSize);
if (previousProgress > 999) {
updateProgress(map.insertedCount, i, progress, download.Name);
notificationManager.notify(notificationId, mBuilder.build());
previousProgress = 0;
}
previousProgress++;
}
fileOutput.close();
} catch (IOException e) {
Log.e("IOException", "" + e.getMessage());
i++;
map.remove(data.getKey());
continue;
}
File actualFile = new File(uepFolder + "/" + download.FileName + "" + download.Format);
file.renameTo(actualFile);
Log.e("Downloaded",""+actualFile.getAbsoluteFile());
} catch (InterruptedException | InternetDisconnectedException e) {
throw e;
}
i++;
map.remove(data.getKey());
Log.e("Downloaded", "Remaining files are "+map.size());
}
Log.e("WhileCheck", "While End");
// Due to thread, sometime the sequence of code flow is not in correct flow, and "Download complete" Notifaction is getting shown
// Hence this check is required.
if (this.isInterrupted()) {
throw new InterruptedException("Thread has been kill (Destroyed)");
}
notificationManager.cancel(notificationId);
mBuilderComplete = new NotificationCompat.Builder(DownloadService.this, "default");
initChannels(DownloadService.this);
mBuilderComplete.setOngoing(false)
.setContentTitle("Download Complete")
.setColor(Color.WHITE)
.setSmallIcon(R.drawable.download);
notificationManager.notify(2, mBuilderComplete.build());
Log.e("DownloadingService", "File downloaded successfully");
stopSelf();
map.insertedCount = 0;
} catch (InterruptedException e) {
closeNotification();
Log.e("InterruptedException", "" + e.getMessage());
} catch (InternetDisconnectedException e) {
stopSelf();
closeNotification();
showNotification("Internet disconnected", "Download failed. Try again later.");
Log.e("InternetDisconnect", "" + e.getMessage());
}
}
private void updateProgress(int totalFiles, int currentFileCount, int currentProgress, String fileName) {
remoteViewsSmall.setTextViewText(R.id.tvOverAll, currentFileCount + "/" + totalFiles);
remoteViewsSmall.setProgressBar(R.id.overallProgress, totalFiles, currentFileCount, false);
remoteViewsBig.setTextViewText(R.id.tvOverAll, currentFileCount + "/" + totalFiles);
remoteViewsBig.setTextViewText(R.id.tvFileName, "Downloading " + fileName);
remoteViewsBig.setTextViewText(R.id.tvCurrentProgress, currentProgress + "%");
remoteViewsBig.setProgressBar(R.id.overallProgress, totalFiles, currentFileCount, false);
remoteViewsBig.setProgressBar(R.id.currentProgress, 100, currentProgress, false);
}
public void closeNotification() {
if (notificationManager != null)
notificationManager.cancel(notificationId);
}
public void showNotification(String title, String message) {
downloadFailBuilder = new NotificationCompat.Builder(DownloadService.this, "default");
initChannels(DownloadService.this);
downloadFailBuilder.setOngoing(false)
.setContentTitle(title)
.setContentText(message)
.setColor(Color.WHITE)
.setSmallIcon(android.R.drawable.stat_sys_warning);
notificationManager.notify(3, downloadFailBuilder.build());
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
ArrayList<Downloadables> list = (ArrayList<Downloadables>) intent.getSerializableExtra("downloadList");
for (Downloadables d : list) {
String key = d.Name + "" + d.FileName;
map.put(key, d);
}
if (thread == null || !thread.isAlive()) {
thread = new BackgroundThread(startId, map);
receiver = new DownloadCancelReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
intentFilter.addAction("CANCEL_DOWNLOAD");
registerReceiver(receiver, intentFilter);
thread.start();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Log.e("Service", " Stop");
try {
thread.interrupt();
} catch (Exception e) {
Log.e("Exception", "" + e.getMessage());
}
map.clear();
unregisterReceiver(receiver);
//closeNotification();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
public DownloadCancelReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("CANCEL_DOWNLOAD")) {
Intent intent1 = new Intent(context, DownloadService.class);
context.stopService(intent1);
}
}
}
public void initChannels(Context context) {
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("default", "Channel name", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("Channel description");
channel.setImportance(NotificationManager.IMPORTANCE_LOW);
channel.setSound(null, null);
notificationManager.createNotificationChannel(channel);
}
private class InternetDisconnectedException extends Exception {
public InternetDisconnectedException(String message) {
super(message);
}
}
public static class DownloadMap<String, Downloadables> extends HashMap<String, Downloadables> {
public int insertedCount;
#Override
public Downloadables put(String key, Downloadables value) {
insertedCount++;
return super.put(key, value);
}
}
}
And From activity I start service like this.
ArrayList<Downloadables> list = helper.GetVideoFileList();
Intent intent1 = new Intent(SRDownloadActivity.this, DownloadService.class);
intent1.putExtra("downloadList", list);
startService(intent1);
I can even Add files to HashMap while downloading is in progress. It also worked fine.
I am unable to figure it out why it is not running in background since it is on different thread.
Here is my notification look like
Threads are killed by the Android OS even if the main app is still working and they dont have access to the UI thats why u should use AsyncTask class its a like a thread that works in background but it has access to the UI of the main. And the jobdispatcher class can help u assign jobs in the background
Here is a good tutorial https://youtu.be/das7FmQIGik

If Recyclerview scroll then item id change how to resolve?

public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, int index) {
holder = holder1;
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder.txtBookBookDateOFIssue.setText(pdfList.getType());
holder.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder.txtDownload.setVisibility(View.VISIBLE);
holder.layout_download_note_option.setVisibility(View.GONE);
} else {
holder.txtDownload.setVisibility(View.GONE);
holder.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
/* alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", pdfList.getFileName());
intent.putExtra("from", "url");
intent.putExtra("getSubjectName", pdfList.getSubjectName());
context.startActivity(intent);
}
});*/
alertDialog.show();
}
}
});
holder.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) !=-1) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
}
}
this is my adapter class
I have a RecyclerView. Each row has a Download button, Cancale button, and Progressbar. when click on the Download button have to Download PDF from my phone storage and have to progress Progressbar The problem is when I scroll down the recyclerview the change item Id .means I can fit 1 items on the screen at once.then scroll ItemId change

Repeatedly Download File on background Service

This is my code. When i click download button, it download twice. How to stop second time downloading? Please help me to prevent second time downloading.
this my button click listener:
downloadPackage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
downloadPackage.setEnabled(false);
SharedPreferences.Editor editor = getSharedPreferences("SETID", MODE_PRIVATE).edit();
editor.putInt("setId", setId);
editor.commit();
Intent intent = new Intent(ReadingListeningTestActivity.this, DownloadService.class);
startService(intent);
}
});
this is my
Download Service:
public class DownloadService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private NotificationManager notificationManager;
private NotificationCompat.Builder notificationBuilder;
private int totalFileSize;
SharedPreferences prefs;
private boolean isDownloading = false;
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
prefs = getSharedPreferences("SETID", MODE_PRIVATE);
int setId = prefs.getInt("setId", 0);
Log.d("SEtID", setId + "");
if (isDownloading) {
return;
} else {
Log.d("Download", "isDownloading: " + isDownloading);
isDownloading = true;
initDownload(setId);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private void initDownload(int setId) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(data.getTitle())
.setContentText("Downloading File")
.setAutoCancel(true);
notificationManager.notify(0, notificationBuilder.build());
downloadFileTest("test.zip");
return null;
}
}.execute();
}
private void downloadFileTest(String uri) {
int count;
InputStream stream = null;
OutputStream output = null;
HttpURLConnection connection = null;
String fileName = packageName(uri);
try {
URL url = new URL(Application.BASE_URL + uri);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
}
byte data[] = new byte[4096];
long fileSize = connection.getContentLength();
stream = new BufferedInputStream(connection.getInputStream());
File outputFile = getCacheDir(fileName + ".part");
output = new FileOutputStream(outputFile);
try {
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = stream.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
double current = Math.round(total / (Math.pow(1021, 2)));
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download);
timeCount++;
}
output.write(data, 0, count);
}
} catch (IOException e) {
isDownloading = false;
prefs.edit().clear().commit();
outputFile.delete();
onErrorDownload("Internet Connection Problem Retry Download");
} finally {
isDownloading = false;
prefs.edit().clear().commit();
File originalName = getCacheDir(fileName);
if (originalName.exists()) {
outputFile.delete();
throw new IOException("file exists");
}
boolean success = outputFile.renameTo(originalName);
if (success) {
if (connection != null)
connection.disconnect();
onDownloadComplete();
output.flush();
output.close();
stream.close();
}
}
} catch (IOException e) {
isDownloading = false;
prefs.edit().clear().commit();
Log.d("Test", "Main");
if (e.getMessage().equals("file exists"))
onErrorDownload("Package Already Exists");
else
onErrorDownload("Internet Connection Problem Retry Download");
}
}
private void onDownloadComplete() {
Download download = new Download();
download.setProgress(100);
sendIntent(download);
notificationManager.cancel(0);
notificationBuilder.setOngoing(false);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText("File Downloaded");
notificationManager.notify(0, notificationBuilder.build());
}
private void onErrorDownload(String message) {
Download download = new Download();
download.setProgress(download.getProgress());
sendIntent(download);
notificationManager.cancel(0);
notificationBuilder.setOngoing(false);
notificationBuilder.setProgress(0, 0, false);
notificationBuilder.setContentText(message);
notificationManager.notify(0, notificationBuilder.build());
}
private void sendNotification(Download download) {
sendIntent(download);
notificationBuilder.setProgress(100, download.getProgress(), false);
notificationBuilder.setOngoing(true);
notificationBuilder.setContentText("Downloading Progress " + download.getProgress() + "%" + " /100%");
notificationManager.notify(0, notificationBuilder.build());
}
private void sendIntent(Download download) {
Intent intent = new Intent(ReadingListeningTestActivity.MESSAGE_PROGRESS);
intent.putExtra("download", download);
LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
}
private String packageName(String uri) {
String[] parts = uri.split("/");
return parts[parts.length - 1];
}
public File getCacheDir(String packageName) {
File cache = null;
File external = getApplication().getExternalCacheDir();
if (external != null && external.exists()) {
cache = external;
} else {
cache = getApplication().getCacheDir();
}
File file = new File(cache, packageName);
return file;
}
}

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.

Categories

Resources