ProgressBar and AsyncTask - android

I currently have an AsyncTask running that updates the progress bar inside the Activity while downloading a file. The problem is when i leave the Activity and reenters, the ProgressBar will not update anymore.
I tried running the AsyncTask inside a Service but i have no idea how to send the ProgressBar value back to my Activity's UI thread.

I came to the same problem as you did:
I wanted an async task executed (as service)
I wanted to be able to rotate the device, be able to update the UI even if the task finished while the screen was off and I got no notification.
I came up with something like:
public class DatabaseIncompleteActivity extends RoboActivity {
private BroadcastReceiver receiver;
private ProgressDialog progressDialog;
#Inject
private DatabaseSetManager databaseSetManager;
#Inject
private DatabaseDownloadLogger databaseDownloadLogger;
private LocalBroadcastManager localBroadcastManager;
private String jobId;
private static final int ERROR_RETRY_DIALOG = 1;
private static final String ERROR_MESSAGE = "errorMsg";
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
localBroadcastManager = LocalBroadcastManager.getInstance( this );
showProgressDialog();
if ( getLastNonConfigurationInstance() == null ) {
startService();
}
}
private void showProgressDialog() {
progressDialog = new ProgressDialog( this );
progressDialog.setMessage( getString( R.string.please_wait ) );
progressDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
progressDialog.setIndeterminate( true );
progressDialog.setCancelable( false );
progressDialog.show();
}
private void startService() {
this.jobId = UUID.randomUUID().toString();
Intent intent = new Intent( this, ClientDatabaseDroidService.class );
intent.putExtra( ClientDatabaseDroidService.JOB_ID,
jobId );
intent.putExtra( ClientDatabaseDroidService.INTERACTIVE,
true );
startService( intent );
}
private void registerListenerReceiver() {
if ( receiver != null ) {
return;
}
localBroadcastManager.registerReceiver( this.receiver = new ClientDatabaseBroadcastReceiver(),
new IntentFilter( ClientDatabaseDroidService.PROGRESS_NOTIFICATION ) );
}
#Override
protected void onPause() {
super.onPause();
unregisterListenerReceiver();
}
#Override
protected void onResume() {
super.onResume();
DatabaseDownloadLogEntry logEntry = databaseDownloadLogger.findByJobId( jobId );
// check if service finished while we were not listening
if ( logEntry != null ) {
if ( logEntry.isSuccess() )
onFinish();
else {
Bundle bundle = new Bundle();
bundle.putString( ERROR_MESSAGE,
logEntry.getErrorMessage() );
onError( bundle );
}
return;
}
registerListenerReceiver();
}
#Override
public Object onRetainNonConfigurationInstance() {
return Boolean.TRUE;
}
final class ClientDatabaseBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive( Context context, Intent intent ) {
Bundle extras = intent.getExtras();
int eventType = extras.getInt( ClientDatabaseDroidService.EVENT_TYPE );
switch ( eventType ) {
case ClientDatabaseDroidService.EVENT_TYPE_DOWNLOADING:
onDownloading( extras );
break;
case ClientDatabaseDroidService.EVENT_TYPE_FINISHED:
onFinish();
break;
case ClientDatabaseDroidService.EVENT_TYPE_ERROR:
Bundle bundle = new Bundle();
bundle.putString( ERROR_MESSAGE,
extras.getString( ClientDatabaseDroidService.EXTRA_ERROR_MESSAGE ) );
onError( bundle );
break;
default:
throw new RuntimeException( "should not happen" );
}
}
}
private void unregisterListenerReceiver() {
if ( receiver != null ) {
localBroadcastManager.unregisterReceiver( receiver );
receiver = null;
}
}
private void onError( Bundle extras ) {
progressDialog.dismiss();
showDialog( ERROR_RETRY_DIALOG,
extras );
}
private void onFinish() {
progressDialog.dismiss();
setResult( RESULT_OK );
finish();
}
#Override
protected Dialog onCreateDialog( final int id, Bundle args ) {
if ( id == ERROR_RETRY_DIALOG ) {
Builder builder = new AlertDialog.Builder( this );
builder.setTitle( R.string.error );
builder.setMessage( "" );
builder.setPositiveButton( R.string.yes,
new OnClickListener() {
#Override
public void onClick( DialogInterface dialog, int which ) {
showProgressDialog();
startService();
}
} );
builder.setNegativeButton( R.string.no,
new OnClickListener() {
#Override
public void onClick( DialogInterface dialog, int which ) {
setResult( RESULT_CANCELED );
finish();
}
} );
return builder.create();
}
return super.onCreateDialog( id,
args );
}
#Override
protected void onPrepareDialog( int id, Dialog dialog, Bundle args ) {
if ( id == ERROR_RETRY_DIALOG ) {
( (AlertDialog) dialog ).setMessage( String.format( "%s\n\n%s",
args.getString( ERROR_MESSAGE ),
getString( R.string.do_you_wish_to_retry ) ) );
return;
}
super.onPrepareDialog( id,
dialog );
}
private void onDownloading( Bundle extras ) {
String currentDatabase = extras.getString( ClientDatabaseDroidService.EXTRA_CURRENT_CLASSIFIER );
Progress databaseProgress = extras.getParcelable( ClientDatabaseDroidService.EXTRA_DATABASE_PROGRESS );
Progress downloadProgress = extras.getParcelable( ClientDatabaseDroidService.EXTRA_DOWNLOAD_PROGRESS );
progressDialog.setIndeterminate( false );
progressDialog.setMessage( String.format( "[%d/%d] %s",
databaseProgress.getProcessed(),
databaseProgress.getSize(),
currentDatabase ) );
progressDialog.setProgress( (int) downloadProgress.getProcessed() );
progressDialog.setMax( (int) downloadProgress.getSize() );
}
}
The main idea is:
The activity communicates with service via broadcast. The following events are dispatched from service to UI: download progress (reported each x bytes), download finished, error occured
Each activity start is being assigned a unique job ID which is kept for screen rotation.
Each job result is being persisted into database (or any other persistent storage). This way I can get the job result even if broadcast received was not listening at the moment (screen was off).
hope that helps.

Make in your activity static progress variable
Save progress to preferences
When you re-enter activity grab and set progress from static variable or preferences.

This is normal. Activities die when you leave them or rotate your device. Then they are recreated. AsyncTasks don't relink to the new Activity instance automatically.
Actually, RoboSpice is the library you are looking for : it will allow you to launch a download from an activity, rotate the device, leave the activity, even leave the app, even kill it using the task switcher and your download will survive. Any activity, a new instance of your former activity, or even a completely different one will be able to relink to your download.
You should download the app RoboSpice Motivations from the store, it will explain you why it's not a good idea to use AsyncTasks for networking and show you how to use RoboSpice.
To get a good & fast overview of this problem, please have a look at this infographics.
Also note that if you only download binary data and are not interested in POJOs for instance, then you can use RoboSpice still or the DownloadManager (but it's API is less intuitive than RoboSpice).

Related

Reopen Android app after some time when minimized using onPause callback

I'm developing an Android application and for some reason that has not yet been identified at random times it minimizes itself. I want to use the onPause callback function that is called when the app is minimized to programmatically reopen it.
As already mentioned, being able to make a rule to call the application reopening after a while so that it is not reopened immediately using Timer and TimerTask and a Boolean key:
private Timer mActivityTransitionTimer;
private TimerTask mActivityTransitionTimerTask;
public boolean wasInBackground;
private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 3000;
#Override
protected void onPause() {
super.onPause();
System.out.println("debug Pause/Resume: --- P A U S E ----");
startActivityTransitionTimer();
}
#Override
protected void onResume() {
super.onResume();
System.out.println("debug Pause/Resume: ---- R E S U M E ---");
stopActivityTransitionTimer();
}
public void stopActivityTransitionTimer() {
if (this.mActivityTransitionTimerTask != null) {
this.mActivityTransitionTimerTask.cancel();
}
if (this.mActivityTransitionTimer != null) {
this.mActivityTransitionTimer.cancel();
}
this.wasInBackground = false;
}
public void startActivityTransitionTimer() {
this.mActivityTransitionTimer = new Timer();
this.mActivityTransitionTimerTask = new TimerTask() {
public void run() {
wasInBackground = true;
System.out.println("debug Pause/Resume: --- NEED REOPENE --");
}
};
this.mActivityTransitionTimer.schedule(
mActivityTransitionTimerTask,
MAX_ACTIVITY_TRANSITION_TIME_MS
);
}
I need to replace NEED REOPEN log with something that makes the app reopen.
I have already tried:
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("package");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("package","package.Activity"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Nothing worked, I'm inside an activity

Android - Best practice for retrying IntentService

My Android app sends a load of files to Amazon S3. Each file URI is passed in separate calls to IntentService which performs the upload.
However, I'm wondering what is the best way to handle failures... Should I detect the failure with my IntentService's onHandleIntent() method and retry within that same method, OR should I allow the failure to be handled outside of the method (and if so, how?)?
I'm personally leaning towards the first suggestion as I would prefer any file to be successfully uploaded before subsequent files are attempted to be uploaded, but I am not sure if detecting errors and performing retries within the onHandleIntent() method is good practice(?).
This is a very nice question. I was asked this in one interview and i had failed to answer it. But i will try and answer it here after some searching for the answer.
Step-1: You start an IntentService. You can start an IntentService either from an Activity or a Fragment.
/* Starting Download Service */
DownloadResultReceiver mReceiver = new DownloadResultReceiver(new Handler());
mReceiver.setReceiver(this);
Intent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class);
/* Send optional extras to Download IntentService */
intent.putExtra("url", url);
intent.putExtra("receiver", mReceiver);
intent.putExtra("requestId", 101);
startService(intent);
Step-2: Make the class that extends IntentService.
public class DownloadService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private static final String TAG = "DownloadService";
public DownloadService() {
super(DownloadService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "Service Started!");
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
String url = intent.getStringExtra("url");
Bundle bundle = new Bundle();
if (!TextUtils.isEmpty(url)) {
/* Update UI: Download Service is Running */
receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
String[] results = downloadData(url);//make your network call here and get the data or download a file.
/* Sending result back to activity */
if (null != results && results.length > 0) {
bundle.putStringArray("result", results);
receiver.send(STATUS_FINISHED, bundle);
}
} catch (Exception e) {
/* Sending error message back to activity */
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
Log.d(TAG, "Service Stopping!");
this.stopSelf();
}
}
Step-3: To receive results back from IntentService, we can use subclass of ResultReciever. Once results are sent from Service the onReceiveResult() method will be called. Your activity handles this response and fetches the results from the Bundle. Once results are recieved, accordingly the activity instance updates the UI.
public class DownloadResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public DownloadResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
Step-4: In your MainActivity:
#Override
public void onReceiveResult(int resultCode, Bundle resultData) {
switch (resultCode) {
case DownloadService.STATUS_RUNNING:
//progress bar visible.
break;
case DownloadService.STATUS_FINISHED:
/* Hide progress & extract result from bundle */
/* Update ListView with result */
break;
case DownloadService.STATUS_ERROR:
/* Handle the error */
String error = resultData.getString(Intent.EXTRA_TEXT);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
/*It is here, i think, that you can again check (eg your net connection) and call the IntentService to restart fetching of data from the network. */
break;
}
}
I hope the above answer helps you. Any suggestions to improve the answer are most welcome. Thanks.

Launching an intent without context

What is the best way to deal with the following situation:
I have a IntentService which does synchronisation with the server (this is triggered by either an Activity coming to the foreground, or a GCM message, so onoy occasional). Sometimes there is a user action needed as a result, and the given command/request is part of the response XML.
There are basically two options, it is either a yes/no question, or a full Activity to for example select the desired language.
How can I do this, or what would be the best way? If I try to launch the Activity with the context of the IntentService nothing happens. I could write a abstract Activity, which I extends in all my Activities and sent a broadcast message which those receive and subsequent start the Activity form the activity which is active, but don't know if that is the best way to do it in Android.
Any suggestions would be appreciated!
[EDIT: as suggested some code]
public class SyncService extends IntentService{
public SyncService(){
super("SyncService");
}
#Override
protected void onHandleIntent(Intent intent) {
iDomsAndroidApp app = ((iDomsAndroidApp) getApplicationContext());
DataManager manager = app.getDataManager();
manager.updateData(this);
}
}
public class DataManager {
// For brevity, this is called with the DOM.Document with the actions to be preformed
private void checkForActions(Document doc, SyncUpdateInterface syncInterface){
NodeList objects = null;
NodeList rootNodes = doc.getElementsByTagName("actions");
for (int j = 0; j < rootNodes.getLength(); j++) {
Element rootElement = (Element) rootNodes.item(j);
if (!rootElement.getParentNode().getNodeName().equals("iDoms")) {
continue;
}
objects = ((Element) rootNodes.item(j)).getElementsByTagName("action");
break;
}
if(objects == null || objects.getLength() == 0){
Log.d(iDomsAndroidApp.TAG, "No actions");
return;
}
for (int j = 0; j < objects.getLength(); j++) {
Element element = (Element) objects.item(j);
String action = ((Element) element.getElementsByTagName("command").item(0)).getTextContent();
if(action == null) return;
Log.d(iDomsAndroidApp.TAG, "Action: " + action);
try{
if(action.equalsIgnoreCase("selectLanguage")){
if(syncInterface == null || syncInterface.getContext() == null) throw new Exception("No context, so cannot perform action");
iDomsAndroidApp app = ((iDomsAndroidApp) iDomsAndroidApp.getAppContext());
// The app.actionIntent is just a central function to pick the right intent for an action.
syncInterface.getContext().startActivity(app.actionIntent("settings", iDomsAndroidApp.context));
} else if (action.equalsIgnoreCase("markAllAsRead")) {
if(syncInterface == null | syncInterface.getContext() == null) throw new Exception("No context, so cannot perform action");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(syncInterface.getContext());
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the result somewhere
// or return them to the component that opened the dialog
iDomsAndroidApp app = ((iDomsAndroidApp) iDomsAndroidApp.getAppContext());
app.getDataManager().markAllAsRead(null);
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialogBuilder.setTitle(iDomsAndroidApp.context.getString(R.string.markAllAsRead));
alertDialogBuilder.setMessage(iDomsAndroidApp.context.getString(R.string.markAllAsReadText));
alertDialogBuilder.show();
}
} catch (Exception e){
Log.w(iDomsAndroidApp.TAG, "Problem performing the action " + element.getTextContent(), e);
sentCrashReport("Problem performing the action " + element.getTextContent(), e);
}
}
}
I tried using the my SyncInterface, as it gives the context of the IntentService, but think it is a but clumsy and doesn't work:
public interface SyncUpdateInterface {
public void doProgress(String message, int increment, int total);
public void doProgress(String message, int increment);
public void doProgress(String message);
public Context getContext();
}
You might have to rethink your approach. The intentservice only lives for the duration of the onHandleIntent() method. That is to say, once the last line of code of the onHandleIntent() method is reached, the IntentService stops itself.
Try EventBus. It provides a solution to similar problems by making communication between components (Activities, Services, Standalone classes) of an application.
Use Gradle to import library
compile 'org.greenrobot:eventbus:3.1.1'
Define an event
public class MessageEvent { /* Additional fields if needed */ }
Launch Event using
EventBus.getDefault().post(new MessageEvent());
Register component to receive event
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Receive launched even by declaring this method
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
For more information visit https://github.com/greenrobot/EventBus

onServiceConnected sometimes not called after bindService on some devices

I've looked at a number of other threads with similar titles, and none seem to cover my problem. So, here goes.
I'm using the Google market expansion files (apkx) library and sample code, with a few modifications. This code relies on receiving callbacks from a service which handles background downloading, licence checks etc.
I have a bug where the service doesn't get correctly attached, which results in a softlock. To make this more unhelpful, this bug never happens on some devices, but occurs about two thirds of the time on other devices. I believe it to be independent of Android version, certainly I have two devices running 2.3.4, one of which (a Nexus S) doesn't have the problem, the other (an HTC Evo 3D) does.
To attempt to connect to the service, bindService is called and returns true. OnBind then gets called as expected and returns a sensible value but (when the bug occurs) onServiceConnected doesn't happen (I've waited 20 minutes just in case).
Has anyone else seen anything like this? If not, any guesses for what I might have done to cause such behaviour? If no-one has any thoughts, I'll post some code tomorrow.
EDIT: Here's the relevant code. If I've missed anything, please ask.
Whilst adding this code, I found a minor bug. Fixing it caused the frequency of the problem I'm trying to solve to change from 2 times in 3 to about 1 time in 6 on the phone I'm testing it on; no idea about effects on other phones. This continues to suggest to me a race condition or similar, but I've no idea what with.
OurDownloaderActivity.java (copied and changed from Google sample code)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
//Test the licence is up to date
//if (current stored licence has expired)
{
startLicenceCheck();
initializeDownloadUI();
return;
}
...
}
#Override
protected void onResume() {
if (null != mDownloaderClientStub) {
mDownloaderClientStub.connect(this);
}
super.onResume();
}
private void startLicenceCheck()
{
Intent launchIntent = OurDownloaderActivity.this
.getIntent();
Intent intentToLaunchThisActivityFromNotification = new Intent(OurDownloaderActivity
.this, OurDownloaderActivity.this.getClass());
intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction());
if (launchIntent.getCategories() != null) {
for (String category : launchIntent.getCategories()) {
intentToLaunchThisActivityFromNotification.addCategory(category);
}
}
// Build PendingIntent used to open this activity from Notification
PendingIntent pendingIntent = PendingIntent.getActivity(OurDownloaderActivity.this,
0, intentToLaunchThisActivityFromNotification,
PendingIntent.FLAG_UPDATE_CURRENT);
DownloaderService.startLicenceCheck(this, pendingIntent, OurDownloaderService.class);
}
initializeDownloadUI()
{
mDownloaderClientStub = DownloaderClientMarshaller.CreateStub
(this, OurDownloaderService.class);
//do a load of UI setup
...
}
//This should be called by the Stub's onServiceConnected method
/**
* Critical implementation detail. In onServiceConnected we create the
* remote service and marshaler. This is how we pass the client information
* back to the service so the client can be properly notified of changes. We
* must do this every time we reconnect to the service.
*/
#Override
public void onServiceConnected(Messenger m) {
mRemoteService = DownloaderServiceMarshaller.CreateProxy(m);
mRemoteService.onClientUpdated(mDownloaderClientStub.getMessenger());
}
DownloaderService.java (in Google market expansion library but somewhat edited )
//this is the onBind call that happens fine; the value it returns is definitely not null
#Override
public IBinder onBind(Intent paramIntent) {
return this.mServiceMessenger.getBinder();
}
final private IStub mServiceStub = DownloaderServiceMarshaller.CreateStub(this);
final private Messenger mServiceMessenger = mServiceStub.getMessenger();
//MY CODE, derived from Google's code
//I have seen the bug occur with a service started by Google's code too,
//but this code happens more often so is more repeatably related to the problem
public static void startLicenceCheck(Context context, PendingIntent pendingIntent, Class<?> serviceClass)
{
String packageName = serviceClass.getPackage().getName();
String className = serviceClass.getName();
Intent fileIntent = new Intent();
fileIntent.setClassName(packageName, className);
fileIntent.putExtra(EXTRA_LICENCE_EXPIRED, true);
fileIntent.putExtra(EXTRA_PENDING_INTENT, pendingIntent);
context.startService(fileIntent);
}
#Override
protected void onHandleIntent(Intent intent) {
setServiceRunning(true);
try {
final PendingIntent pendingIntent = (PendingIntent) intent
.getParcelableExtra(EXTRA_PENDING_INTENT);
if (null != pendingIntent)
{
mNotification.setClientIntent(pendingIntent);
mPendingIntent = pendingIntent;
} else if (null != mPendingIntent) {
mNotification.setClientIntent(mPendingIntent);
} else {
Log.e(LOG_TAG, "Downloader started in bad state without notification intent.");
return;
}
if(intent.getBooleanExtra(EXTRA_LICENCE_EXPIRED, false))
{
//we are here due to startLicenceCheck
updateExpiredLVL(this);
return;
}
...
}
}
//MY CODE, based on Google's, again
public void updateExpiredLVL(final Context context) {
Context c = context.getApplicationContext();
Handler h = new Handler(c.getMainLooper());
h.post(new LVLExpiredUpdateRunnable(c));
}
private class LVLExpiredUpdateRunnable implements Runnable
{
LVLExpiredUpdateRunnable(Context context) {
mContext = context;
}
final Context mContext;
#Override
public void run() {
setServiceRunning(true);
mNotification.onDownloadStateChanged(IDownloaderClient.STATE_LVL_UPDATING);
String deviceId = getDeviceId(mContext);
final APKExpansionPolicy aep = new APKExpansionPolicy(mContext,
new AESObfuscator(getSALT(), mContext.getPackageName(), deviceId));
// Construct the LicenseChecker with a Policy.
final LicenseChecker checker = new LicenseChecker(mContext, aep,
getPublicKey() // Your public licensing key.
);
checker.checkAccess(new LicenseCheckerCallback() {
...
});
}
}
DownloaderClientMarshaller.java (in Google market expansion library)
public static IStub CreateStub(IDownloaderClient itf, Class<?> downloaderService) {
return new Stub(itf, downloaderService);
}
and the Stub class from the same file:
private static class Stub implements IStub {
private IDownloaderClient mItf = null;
private Class<?> mDownloaderServiceClass;
private boolean mBound;
private Messenger mServiceMessenger;
private Context mContext;
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ONDOWNLOADPROGRESS:
Bundle bun = msg.getData();
if ( null != mContext ) {
bun.setClassLoader(mContext.getClassLoader());
DownloadProgressInfo dpi = (DownloadProgressInfo) msg.getData()
.getParcelable(PARAM_PROGRESS);
mItf.onDownloadProgress(dpi);
}
break;
case MSG_ONDOWNLOADSTATE_CHANGED:
mItf.onDownloadStateChanged(msg.getData().getInt(PARAM_NEW_STATE));
break;
case MSG_ONSERVICECONNECTED:
mItf.onServiceConnected(
(Messenger) msg.getData().getParcelable(PARAM_MESSENGER));
break;
}
}
});
public Stub(IDownloaderClient itf, Class<?> downloaderService) {
mItf = itf;
mDownloaderServiceClass = downloaderService;
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
//this is the critical call that never happens
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mServiceMessenger = new Messenger(service);
mItf.onServiceConnected(
mServiceMessenger);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mServiceMessenger = null;
mBound = false;
}
};
#Override
public void connect(Context c) {
mContext = c;
Intent bindIntent = new Intent(c, mDownloaderServiceClass);
bindIntent.putExtra(PARAM_MESSENGER, mMessenger);
if ( !c.bindService(bindIntent, mConnection, 0) ) {
if ( Constants.LOGVV ) {
Log.d(Constants.TAG, "Service Unbound");
}
}
}
#Override
public void disconnect(Context c) {
if (mBound) {
c.unbindService(mConnection);
mBound = false;
}
mContext = null;
}
#Override
public Messenger getMessenger() {
return mMessenger;
}
}
DownloaderServiceMarshaller.java (in Google market expansion library, unchanged)
private static class Proxy implements IDownloaderService {
private Messenger mMsg;
private void send(int method, Bundle params) {
Message m = Message.obtain(null, method);
m.setData(params);
try {
mMsg.send(m);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public Proxy(Messenger msg) {
mMsg = msg;
}
#Override
public void requestAbortDownload() {
send(MSG_REQUEST_ABORT_DOWNLOAD, new Bundle());
}
#Override
public void requestPauseDownload() {
send(MSG_REQUEST_PAUSE_DOWNLOAD, new Bundle());
}
#Override
public void setDownloadFlags(int flags) {
Bundle params = new Bundle();
params.putInt(PARAMS_FLAGS, flags);
send(MSG_SET_DOWNLOAD_FLAGS, params);
}
#Override
public void requestContinueDownload() {
send(MSG_REQUEST_CONTINUE_DOWNLOAD, new Bundle());
}
#Override
public void requestDownloadStatus() {
send(MSG_REQUEST_DOWNLOAD_STATE, new Bundle());
}
#Override
public void onClientUpdated(Messenger clientMessenger) {
Bundle bundle = new Bundle(1);
bundle.putParcelable(PARAM_MESSENGER, clientMessenger);
send(MSG_REQUEST_CLIENT_UPDATE, bundle);
}
}
private static class Stub implements IStub {
private IDownloaderService mItf = null;
final Messenger mMessenger = new Messenger(new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REQUEST_ABORT_DOWNLOAD:
mItf.requestAbortDownload();
break;
case MSG_REQUEST_CONTINUE_DOWNLOAD:
mItf.requestContinueDownload();
break;
case MSG_REQUEST_PAUSE_DOWNLOAD:
mItf.requestPauseDownload();
break;
case MSG_SET_DOWNLOAD_FLAGS:
mItf.setDownloadFlags(msg.getData().getInt(PARAMS_FLAGS));
break;
case MSG_REQUEST_DOWNLOAD_STATE:
mItf.requestDownloadStatus();
break;
case MSG_REQUEST_CLIENT_UPDATE:
mItf.onClientUpdated((Messenger) msg.getData().getParcelable(
PARAM_MESSENGER));
break;
}
}
});
public Stub(IDownloaderService itf) {
mItf = itf;
}
#Override
public Messenger getMessenger() {
return mMessenger;
}
#Override
public void connect(Context c) {
}
#Override
public void disconnect(Context c) {
}
}
/**
* Returns a proxy that will marshall calls to IDownloaderService methods
*
* #param ctx
* #return
*/
public static IDownloaderService CreateProxy(Messenger msg) {
return new Proxy(msg);
}
/**
* Returns a stub object that, when connected, will listen for marshalled
* IDownloaderService methods and translate them into calls to the supplied
* interface.
*
* #param itf An implementation of IDownloaderService that will be called
* when remote method calls are unmarshalled.
* #return
*/
public static IStub CreateStub(IDownloaderService itf) {
return new Stub(itf);
}

Android: Memory leak due to AsyncTask

I'm stuck with a memory leak that I cannot fix. I identified where it occurs, using the MemoryAnalizer but I vainly struggle to get rid of it. Here is the code:
public class MyActivity extends Activity implements SurfaceHolder.Callback {
...
Camera.PictureCallback mPictureCallbackJpeg = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera c) {
try {
// log the action
Log.e(getClass().getSimpleName(), "PICTURE CALLBACK JPEG: data.length = " + data);
// Show the ProgressDialog on this thread
pd = ProgressDialog.show(MyActivity.this, "", "Préparation", true, false);
// Start a new thread that will manage the capture
new ManageCaptureTask().execute(data, c);
}
catch(Exception e){
AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this);
...
dialog.create().show();
}
}
class ManageCaptureTask extends AsyncTask<Object, Void, Boolean> {
protected Boolean doInBackground(Object... args) {
Boolean isSuccess = false;
// initialize the bitmap before the capture
((myApp) getApplication()).setBitmapX(null);
try{
// Check if it is a real device or an emulator
TelephonyManager telmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String deviceID = telmgr.getDeviceId();
boolean isEmulator = "000000000000000".equalsIgnoreCase(deviceID);
// get the bitmap
if (isEmulator) {
((myApp) getApplication()).setBitmapX(BitmapFactory.decodeFile(imageFileName));
} else {
((myApp) getApplication()).setBitmapX(BitmapFactory.decodeByteArray((byte[]) args[0], 0, ((byte[])args[0]).length));
}
((myApp) getApplication()).setImageForDB(ImageTools.resizeBmp(((myApp) getApplication()).getBmp()));
// convert the bitmap into a grayscale image and display it in the preview
((myApp) getApplication()).setImage(makeGrayScale());
isSuccess = true;
}
catch (Exception connEx){
errorMessageFromBkgndThread = getString(R.string.errcapture);
}
return isSuccess;
}
protected void onPostExecute(Boolean result) {
// Pass the result data back to the main activity
if (MyActivity.this.pd != null) {
MyActivity.this.pd.dismiss();
}
if (result){
((ImageView) findViewById(R.id.apercu)).setImageBitmap(((myApp) getApplication()).getBmp());
((myApp) getApplication()).setBitmapX(null);
}
else{
// there was an error
ErrAlert();
}
}
}
};
private void ErrAlert(){
// notify the user about the error
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
...
dialog.create().show();
}
}
The activity is terminated on a button click, like this:
Button use = (Button) findViewById(R.id.use);
use.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, NextActivity.class);
intent.putExtra("dbID", "-1");
intent.putExtra("category", category);
((myApp) getApplication()).setBitmapX(null);
MyActivity.this.startActivity(intent);
MyActivity.this.finish();
}
});
MemoryAnalyzer indicated the memory leak at:
((myApp) getApplication()).setBitmapX(BitmapFactory.decodeByteArray((byte[]) args[0], 0, ((byte[])args[0]).length));
I am grateful for any suggestion, thank you in advance.
Is your thread garbage collected after onPostExecute is called or is it still in the memory?
A Async Task will not be canceled or destroyed at the moment the activity is dismissed. If your thread is more or less lightweight and finishes after a small time, just keep it running and add a MyActivity.this.isFinishing() clause in the onPostExecute() method.
Your Task stores a implicit reference to your Activity MyActivity.this because it is a private class inside the activity. This means that your Activity will not be garbage collected until the task exits.
You can try below code snippet
protected void onPostExecute(Boolean result) {
if(YourActivity.this.isFinished()){
//to smomething here
}
}

Categories

Resources