1

I am afraid that my activity is restarted when i open it through TaskManager....

and my DefaultHttpClient object treated as fresh one..so here i am loosing the session.

I tried by overriding the onSaveInstanceState() method..but no use..

@Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState); // the UI component values are saved here.
        }

How i can get rid of this one...

ShreeshaDas
  • 2,042
  • 2
  • 17
  • 36
user1557549
  • 51
  • 2
  • 4

5 Answers5

0

You could subclass Android Applications: You can init the HttpClient there and hold the reference.

Look here

Than you can access from activity your Application object with activity.getApplication()

If your session works with cookies than you may need a persistent cookie storeage (like database or shared preferences):

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

/**
 * A persistent cookie store which implements the Apache HttpClient
 * {@link CookieStore} interface. Cookies are stored and will persist on the
 * user's device between application sessions since they are serialized and
 * stored in {@link SharedPreferences}.
 * <p>
 */
public class PersistentCookieStore implements CookieStore {
    private static final String COOKIE_PREFS = "CookiePrefsFile";
    private static final String COOKIE_NAME_STORE = "names";
    private static final String COOKIE_NAME_PREFIX = "cookie_";

    private final ConcurrentHashMap<String, Cookie> cookies;
    private final SharedPreferences cookiePrefs;

    /**
     * Construct a persistent cookie store.
     */
    public PersistentCookieStore(Context context) {
        cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
        cookies = new ConcurrentHashMap<String, Cookie>();

        // Load any previously stored cookies into the store
        String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE,
                null);
        if (storedCookieNames != null) {
            String[] cookieNames = TextUtils.split(storedCookieNames, ",");
            for (String name : cookieNames) {
                String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX
                        + name, null);
                if (encodedCookie != null) {
                    Cookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        cookies.put(name, decodedCookie);
                    }
                }
            }

            // Clear out expired cookies
            clearExpired(new Date());
        }
    }

    @Override
    public synchronized void addCookie(Cookie cookie) {
        String name = cookie.getName() + cookie.getDomain();

        // Save cookie into local store, or remove if expired
        if (!cookie.isExpired(new Date())) {
            cookies.put(name, cookie);
        } else {
            cookies.remove(name);
        }

        // Save cookie into persistent store
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        prefsWriter.putString(COOKIE_NAME_STORE,
                TextUtils.join(",", cookies.keySet()));
        prefsWriter.putString(COOKIE_NAME_PREFIX + name,
                encodeCookie(new SerializableCookie(cookie)));
        prefsWriter.commit();
    }

    @Override
    public synchronized void clear() {
        // Clear cookies from persistent store
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
        for (String name : cookies.keySet()) {
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);
        }
        prefsWriter.remove(COOKIE_NAME_STORE);
        prefsWriter.commit();

        // Clear cookies from local store
        cookies.clear();
    }

    @Override
    public synchronized boolean clearExpired(Date date) {
        boolean clearedAny = false;
        SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

        for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
            String name = entry.getKey();
            Cookie cookie = entry.getValue();
            if (cookie.isExpired(date)) {
                // Clear cookies from local store
                cookies.remove(name);

                // Clear cookies from persistent store
                prefsWriter.remove(COOKIE_NAME_PREFIX + name);

                // We've cleared at least one
                clearedAny = true;
            }
        }

        // Update names in persistent store
        if (clearedAny) {
            prefsWriter.putString(COOKIE_NAME_STORE,
                    TextUtils.join(",", cookies.keySet()));
        }
        prefsWriter.commit();

        return clearedAny;
    }

    @Override
    public synchronized List<Cookie> getCookies() {
        return new CopyOnWriteArrayList<Cookie>(cookies.values());
    }

    //
    // Cookie serialization/deserialization
    //

    protected synchronized String encodeCookie(SerializableCookie cookie) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (Exception e) {
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }

    protected synchronized Cookie decodeCookie(String cookieStr) {
        byte[] bytes = hexStringToByteArray(cookieStr);
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        Cookie cookie = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(is);
            cookie = ((SerializableCookie) ois.readObject()).getCookie();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return cookie;
    }

    // Using some super basic byte array <-> hex conversions so we don't have
    // to rely on any large Base64 libraries. Can be overridden if you like!
    protected synchronized String byteArrayToHexString(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        for (byte element : b) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase();
    }

    protected synchronized byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
                    .digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}

Do something like this:

httpClient.setCookieStoreage(new PersistentCookieStore(this)) in your application subclass where you init the httpclient

Community
  • 1
  • 1
sockeqwe
  • 15,574
  • 24
  • 88
  • 144
0

when you press button Home, activity will pause and resume when reopen. you shout put code to onCreate(). see activity lifecryde: enter image description here

0

You are probably seeing a nasty, long-standing Android bug that causes the symptoms you are describing. Have a look at my answer here: https://stackoverflow.com/a/16447508/769265

Community
  • 1
  • 1
David Wasser
  • 93,459
  • 16
  • 209
  • 274
0

You probably have to add following code inside the onCreate() event of launcher Activity.

if (!isTaskRoot()) {
    final Intent intent = getIntent();
    final String action = intent.getAction(); 
    if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) {
        finish();//Launcher Activity is not the root. So,finish it instead of launching
        return;       
    }
}
Nizam
  • 5,698
  • 9
  • 45
  • 57
-1
    android:launchMode="singleInstance"
    android:alwaysRetainTaskState="true"

Try adding this two attributes to your Activity in manifest, this will make sure newIntent is called when activity is resumed from background.

Techfist
  • 4,314
  • 6
  • 22
  • 32
  • This is a horrible solution. Please don't use special `launchMode`s to solve this kind of problem. – David Wasser Dec 06 '13 at 09:02
  • well this is not horrible, there are many situation when only single instance of task is required, in those scenario this is the perfect solution, I dont see any android guideline detailing about such issues. – Techfist Dec 06 '13 at 09:06
  • Using the `singleTask` and `singleInstance` launch modes tend to create more problems than they solve. Most developers don't understand how these really work. And if your applicaiton has more than 1 activity this will generally break it completely. The standard behaviour of Android using standard launch modes should work correctly for 99% of applications. Suggesting the use of special launch modes causes inexperienced developers to spend a lot of time chasing after problems they should never have had in the first place. – David Wasser Dec 06 '13 at 09:11
  • In most cases, Android will bring your existing task to the foreground when you relaunch your application, if you've programmed it properly. It you haven't programmed it properly, then you need to fix that and not mask it by using special launch modes. Unfortunately there is one very nasty Android bug which causes the symptom described by OP and this problem is **not solved by using special launch modes**. – David Wasser Dec 06 '13 at 09:13
  • I understood what you meant, but in scenarios where user doesn't want call to onCreate when coming back from background this holds good. – Techfist Dec 06 '13 at 09:45
  • No, you are still missing the point. If you've programmed it correctly, when your app is brought forward from the background Android **does not call `onCreate()`** That is the standard behaviour. You don't need special launch modes to make this happen. The user is seeing an Android bug and your fix won't help him, but it will confuse him and make him make other unnecessary mistakes and put him on a wild goose chase to find a problem that he created himself by using special launch modes. – David Wasser Dec 13 '13 at 14:29