Android keep download onging even after clearing app from recent task - android

I am using service to download a file , but if I clear the app from recent app list then download stopped . I tried running the service as foreground but no luck . How can I achieve it ? Download multiple files in queue , even after remove the app from recent task .
public class ApkDownloadService extends Service {
public static final String EXTRA_APP_DETAILS = ApkDownloadService.class.getName().concat("_app_details");
int NOTIFICATION_ID = ((Number) System.currentTimeMillis()).intValue();
private String TAG = "ApkDownloadService";
String appId;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
NotificationManagerCompat notificationManager;
NotificationCompat.Builder mBuilder;
// Issue the initial notification with zero progress
int PROGRESS_MAX = 100;
int PROGRESS_CURRENT = 0;
int fileLength;
#Override
public void onCreate() {
super.onCreate();
notificationManager = NotificationManagerCompat.from(this);
Log.d(TAG,"onCreate");
}
#Override
public void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
Log.d(TAG,"onDestroy");
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
notificationManager.cancel(NOTIFICATION_ID);
Log.d(TAG,"onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG,"onBind");
return null;
}
#Override
public boolean onUnbind(Intent intent) {
Log.d(TAG,"onUnbind");
return super.onUnbind(intent);
}
#SuppressLint("StaticFieldLeak")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
assert intent != null;
Result result = intent.getParcelableExtra(EXTRA_APP_DETAILS);
Log.d(TAG,"onStartCommand");
appId = result.getApplicationId();
mBuilder = new NotificationCompat.Builder(this, appId);
mBuilder.setContentTitle(result.getName())
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_LOW);
mBuilder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
startForeground((int) result.getId(), mBuilder.build());
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
URL url;
try {
url = new URL(result.getPackage().getApk());
URLConnection conection = url.openConnection();
conection.connect();
fileLength = conection.getContentLength();
long total = 0;
int count, tmpPercentage = 0;
InputStream input = url.openStream();
byte[] chunk = new byte[4096];
while ((count = input.read(chunk)) != -1) {
total += count;
outputStream.write(chunk, 0, count);
PROGRESS_CURRENT = (int) ((total * 100) / fileLength);
if (PROGRESS_CURRENT > tmpPercentage) {
EventBus.getDefault().post(String.valueOf(PROGRESS_CURRENT)); // Posting download percentage
mBuilder.setContentText(PROGRESS_CURRENT + "%");
mBuilder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
tmpPercentage = PROGRESS_CURRENT;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onCancelled() {
super.onCancelled();
Log.d(TAG,"onCancelled");
}
}.execute();
return START_REDELIVER_INTENT;
}
}
I am not sure what is wrong with my foreground service . If I clear the app from recent task , download stops .

Related

Check for new chat messages at background, Android

I'm developing a application when which every 4,5 seconds the client checks whether the server responds "OK".
It's even working, But if I turn on/off the internet sometimes it stops working, it is inconsistent and I need to check the messages accurately.
And service stop like in example I gave and it re-operate outside the specified range of seconds (4.5)
I'm developing a chat, and I need to know this precisely, I need to be professional.
Start.java
public class Start extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Intent serviceIntent = new Intent(getBaseContext(), BackExec.class);
getBaseContext().startService(serviceIntent);
}
#Override
protected void onResume()
{
super.onResume();
Intent serviceIntent = new Intent(getApplicationContext(), BackExec.class);
startService(serviceIntent);
}}
BackExec.java
public class BackExec extends Service {
static Timer t;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
}
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
return START_STICKY;
}
public static String getData(){
URL site = null;
try {
site = new URL("http://192.168.0.10:8080/example/server.php");
URLConnection urlConn = site.openConnection();
urlConn.setRequestProperty("Cookie", CookieManager.getInstance().getCookie("http://192.168.0.10:8080/example"));
urlConn.setDoOutput(true);
PrintStream enviarInfos = new PrintStream(urlConn.getOutputStream());
enviarInfos.print("pac=pac");
urlConn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine;
String out = "";
while ((inputLine = in.readLine()) != null)
out = out + inputLine;
in.close();
return out;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public void onStart(Intent intent, int startId) { } // TO DO
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {} }

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;
}
}

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.

Schedule Asynctask - While? Service? Timer?

Ok, I got a Togglebutton that starts a service. The service starts a new Thread in onStartCommand. In this Thread an Asynctask is executed.
Now I want this Asynctask to be executed for example every 5 seconds. The Asynctask checks if the website is available.
-> if no, after 5 secs check again
-> if yes, show message and stop
Whats the best method with my already present code:
public class NotifiyService extends Service {
String savedsa;
Thread Th1;
boolean value;
final class TheThread implements Runnable{
int serviceID;
String savedsa1;
TheThread(int serviceID,String savedsa){
this.serviceID = serviceID;
this.savedsa1 = savedsa;
}
#Override
public void run() {
HttpTaskParams httpparams = new HttpTaskParams(value,savedsa1);
new HttpTask().execute(httpparams);
}
}
public NotifiyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences7 = getSharedPreferences("Prefsa",MODE_WORLD_READABLE);
savedsa = sharedPreferences7.getString("keysa","");
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStarted)+ "\n" + savedsa,Toast.LENGTH_LONG).show();
Th1 = new Thread(new TheThread(startId,savedsa));
Th1.start();
return START_STICKY;
}
#Override
public void onDestroy() {
//super.onDestroy();
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
private static class HttpTaskParams{
boolean value;
String address;
HttpTaskParams(boolean value, String address){
this.value = value;
this.address = address;
}
}
private class HttpTask extends AsyncTask<HttpTaskParams,Void,Boolean>{
#Override
protected Boolean doInBackground(HttpTaskParams... params) {
boolean value = params[0].value;
String address = params[0].address;
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main2Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLights(Color.YELLOW,600,600);
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
else{
Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT:
#Override
public void run() {
ScheduledExecutorService checkreg = Executors.newScheduledThreadPool(1);
scheduledFuture = checkreg.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
HttpTaskParams httpparams = new HttpTaskParams(value, savedsa1);
new HttpTask().execute(httpparams);
}
}, 0, 20, TimeUnit.SECONDS);}
#Override
public void onDestroy() {
//super.onDestroy();
Th1.interrupt();
scheduledFuture.cancel(false);
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
stopSelf();
}
I think a ScheduledExecutorService could help you.
Please check this answer.
Please let me know if this helps you.
try this /**
* Loads exchange rates form network periodically
* Returns results in broadcast message.
* Created by koss on 19.02.16.
* */
public class EcbEuropeService extends Service {
public static final String ECB_URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
public static final int UPDATE_PERIOD = 30000;
public static final int UPDATE_TICK = 1000;
public static final String NOTIFICATION = "koss.ru.oneclickrate.receiver";
public static final String EXTRA_CURRENCIES_MAP = "extra_currencies_map";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getUrlData();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public Cubes getUrlData() {
(new AsyncTask<Object, Object, Cubes>() {
Map<CurrencyType, BigDecimal> result = new EnumMap<CurrencyType, BigDecimal>(CurrencyType.class);
#Override
protected Cubes doInBackground(Object... params) {
Cubes cubes = new Cubes();
InputStream is = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(ECB_URL);
urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
cubes = EcbEuropeResponseParser.parse(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(urlConnection!=null) IOUtils.close(urlConnection);
if(is!=null) IOUtils.closeQuietly(is);
return cubes;
}
}
#Override
protected void onPostExecute(Cubes map) {
super.onPostExecute(map);
sendBroadcastMessage(map);
startTimer();
}
}).execute();
return null;
}
/**
* Restarts timer
* */
public void startTimer() {
cdt.cancel();
cdt.start();
}
CountDownTimer cdt = new CountDownTimer(UPDATE_PERIOD, UPDATE_TICK) {
#Override
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
getUrlData();
}
};
private void sendBroadcastMessage(Cubes currenciesMap) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(EXTRA_CURRENCIES_MAP, currenciesMap);
sendBroadcast(intent);
}
}

Categories

Resources