I am working on appLocker in which I have to set the password on installed application of device.
for that I have created a list in which I am getting all the installed application. User can select the the application by using checkBox and set the password on that. for that I have to get the package name of that application. I am able to get the package name of selected application and save them using Share Preferences. now I have to get that package name in an another activity. please tell me how can I get that.
this is the code where I am getting the package name.
public void onClick(View v) {
if (R.id.select_done_btn == v.getId()) {
SharedPreferences prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
int[] indexes = appListAdapter.getSelectedItemIndexes();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indexes.length; ++i) {
AppInfo appInfo = installedApps.get(indexes[i]);
sb.append(appInfo.getPackageName()).append(";");
}
Editor editor = prefs.edit();
editor.putString("lock_apps", sb.toString());
editor.commit();
and this the code section where I have to get that package name to lock the selected application in another activity..
public void run() {
while (true) {
Log.i("lock", "lockerThread run.");
String packname = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
if ("**PACKAGE NAME**".equals(packname)) {
startActivity(pwdIntent);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
In the above question
SharedPreferences prefs = getSharedPreferences(getPackageName() , MODE_PRIVATE);
prefs.getstring("key");
will give your saved string from SharedPreferences where ever you want in Application.
If you like you can go through other solution given as below for optimization
public void addTask(Task t) {
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
currentTasks.add(t);
//save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}
Similarly we can retrieve the list of tasks from the preference inside onCreate() method:
public void onCreate() {
super.onCreate();
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Related
Can anybody tell me how to maintain session for a user login. For example when the user sign- in to an application they have to be signed in unless the user logouts or uninstall the application similar to gmail in android.
Make one class for your SharedPreferences
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Now after making this class when you want to use it, use like this: make object of this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
//and now we set sharedpreference then use this like
session.setusename("USERNAME");
now whenever you want to get the username then same work is to be done for session object and call this
session.getusename();
Do same for password
You can achieve this by using AccountManager.
Code Sample
// method to add account..
private void addAccount(String username, String password) {
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type)); // account name identifier.
if (accounts.length > 0) {
return;
}
final Account account = new Account(username,
getString(R.string.account_type));
accnt_manager.addAccountExplicitly(account, password, null);
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_PASSWORD, password);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,
getString(R.string.account_type));
// intent.putExtra(AccountManager.KEY_AUTH_TOKEN_LABEL,
// PARAM_AUTHTOKEN_TYPE);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, "token");
this.setAccountAuthenticatorResult(intent.getExtras());
this.setResult(RESULT_OK, intent);
this.finish();
}
// method to retrieve account.
private boolean validateAccount() {
AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
Log.e("calback", "msg");
try {
Bundle b = arg0.getResult();
if (b.getBoolean(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE)) {
//User account exists!!..
}
} catch (OperationCanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AuthenticatorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
AccountManager accnt_manager = AccountManager
.get(getApplicationContext());
Account[] accounts = accnt_manager
.getAccountsByType(getString(R.string.account_type));
if (accounts.length <= 0) {
return false;
} else {
loginNameVal = accounts[0].name;
loginPswdVal = accnt_manager.getPassword(accounts[0]);
return true;
}
}
I have one simple way rather than maintain a session.
i.e. Just store one boolean variable with your username and password. by default set value equal to false.
After first successful login make its value to true.
Then just check its value on your Mainactivity, if it is true then jump to next activity otherwise jump to login activity.
You can use a boolean value in the SharedPreferences.
Load it before login to check if login is needed.
Save it after login.
Use SharedPreferences.
Code to save a value to sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
SharedPreferences.Editor ed=sp.edit();
ed.putInt("value", your_value);
ed.commit();
Code to get value from sharedpreferences:
SharedPreferences sp=getSharedPreferences("key", Context.MODE_PRIVATE);
int value = sp.getInt("value", default_value);
You can check login and logout by using this value.
You can obtain that behaivour in a few different ways, the one I prefer is setting a flag in the shared prefs. whe a user logs in an check it when the app is started if you get the default value the user is not loggend, else you should have your flag (i use the user name) set and avoid the log-in section.
save the user data in shared preferences till the user logs out.
once user logs out clear the data from shared preferences.
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
editor = prefs.edit();
}
public void setusename(String usename) {
editor.putString("usename", usename).commit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUcUZxeHo0UnJ5UHc
Fetch Previous Login ID in android
**After Login save Email ID is SharedPreferences**
emaidId = et_Email.getText().toString().trim();
SharedPreferences ss = getSharedPreferences("loginSession_key", 0);
Set<String> hs = ss.getStringSet("set", new HashSet<String>());
hs.add(emaidId);
SharedPreferences.Editor edit = ss.edit();
edit.clear();
edit.putStringSet("set", hs);
edit.commit();
===================onCreate()====================
===================AutoCompleteTextView set Adapter===================
**Fetch PRevious Login Email id in email EditText**
SharedPreferences sss = getSharedPreferences("loginSession_key", 0); // todo loginSession_key key name ALWAYS SAME
Log.i("chauster", "2.set = " + sss.getStringSet("set", new HashSet<String>()));
Log.e("Session", "Value->" + sss.getStringSet("set", new HashSet<String()));
ArrayList<String> al = new ArrayList<>();
al.addAll(sss.getStringSet("set", new HashSet<String>()));
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, al);
//Getting the instance of AutoCompleteTextView
et_Email.setThreshold(1);//will start working from first character
et_Email.setAdapter(adapter);//setting the adapter data into the
Using this class will help you to store all types of sessions
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void set(String key,String value) {
prefs.edit().putString(key, value).commit();
}
public String get(String key) {
String value = prefs.getString(key,"");
return value;
}
}
Through this format, you can set or get multiple objects of data, you don't need to create separate functions to store different models in SharedPreferences.
* Here in this format, you don't need to pass your object KEY for putString() and getString()
* Using the object class name you are able to identify your session object uniquely, for both setModel() and getModel()
public class Session {
private final SharedPreferences pref;
public Session(Context ctx) {
pref = PreferenceManager.getDefaultSharedPreferences(ctx);
//pref = ctx.getSharedPreferences("IDENTIFIED_NAME", Context.MODE_PRIVATE);
}
public <U> void setModel(U obj) {
pref.edit().putString(getClassName(obj), SerializeObject(obj)).apply();
}
/* Parameter Example: Class.class */
public <U> U getModel(Class<U> type) {
String user = pref.getString(type.getSimpleName(), null);
if (isEmptyOrNull(user)) {
return null;
}
return DeserializeObject(user, type);
}
/* The below functions are for support, You can move the below part to your own BaseUtil class. */
public static boolean isEmptyOrNull(String data) {
if (data == null) {
return true;
}
if (data.isEmpty() || data.trim().isEmpty()) {
return true;
}
return false;
}
public static String getClassName(Object obj) {
return obj.getClass().getSimpleName();
}
public static String SerializeObject(Object myObject) {
// serialize the object
try {
Gson gson = new Gson();
String json = gson.toJson(myObject);
return json;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public static <U> U DeserializeObject(String serializedObject, Class<U> type) {
// serialize the object
try {
if (serializedObject == null || serializedObject.isEmpty()) {
return null;
}
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
U data = gson.fromJson(serializedObject, type);
return data;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
}
Create an object class (file_name: UserModel.java)
public class UserModel {
public String userId;
public String firstName;
public String lastName;
public String email;
public String phone;
}
How to use - For setModel() and getModel()
//creating an instance of the Session class
Session session = new Session(ctx); // Here you have to pass the Context(ctx)
// setting value in the UserModel
UserModel obj = new UserModel();
obj.firstName = "Apu";
obj.lastName = "Pradhan";
obj.email = "godfindapu#gmail.com";
obj.phone = "123456789";
// set UserModel in the Session
session.setModel(obj);
//getting UserModel data from the Session
UserModel userData = session.getModel(UserModel.class);
I want to make a user don't need to login again, once after login. My code don't skip login page. How to skip login page? I have a start page. I press start button, it go to Login page. But a user have already login, make to skip the login page and go to next page.
How should I do?
JSONObject json=null;
int status=2;
String userID=null;
String teamID=null;
String teamName=null;
String admin=null;
String backNo=null;
String userName=null;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("email",edit_txt_EmailAddress.getText().toString()));//// define the parameter
postParameters.add(new BasicNameValuePair("password",edit_txt_Password.getText().toString()));
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>();
//postParameters.add(new BasicNameValuePair("userID","396797666"));
String response = null;
try {
response=CustomHttpClient.executeHttpPost("http://10.0.2.2/kwikwi/login.php", postParameters);
json=new JSONObject(response);
userID=json.getString("userID");
}
catch (Exception e) {
e.printStackTrace();
}
Log.i("USERID", userID+"");
JSONObject json_data = null;
String teamStatus ="";
String result = response.toString();
JSONObject jsonobj = null;
try{
jsonobj = new JSONObject (result);
teamStatus=jsonobj.getString("teamStatus");
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Log.i("TeamStatus", result+"");
Log.i("RESULT", teamStatus+"");
//Log.i("halo",teamStatus+"");
String[] teamSaving=new String[6];
String[] noteamSaving=new String[2];
if (blNagSetting == true){
if(teamStatus.equals("1")){
try {
Log.i("Team Kyaw Win tal","Log in ma twar buu.");
userName=jsonobj.getString("userName");
userID=jsonobj.getString("userID");
teamID=jsonobj.getString("teamID");
teamName=jsonobj.getString("teamName");
admin=jsonobj.getString("admin");
backNo=jsonobj.getString("backNo");
teamSaving[0]=userName;
teamSaving[1]=userID;
teamSaving[2]=teamID;
teamSaving[3]=teamName;
teamSaving[4]=admin;
teamSaving[5]=backNo;
Log.i("USerName", userName+"");
Log.i("UserID",userID+"");
Log.i("TeamId",teamID+"");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent teamshi=new Intent(Login.this,Team.class);
teamshi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(teamshi);
finish();
}
else if(teamStatus.equals("0"))
{
try {
Log.i("NoTeam Kyaw Win tal","Log in ma twar buu.");
userName=jsonobj.getString("userName");
userID=jsonobj.getString("userID");
noteamSaving[0]=userName;
noteamSaving[1]=userID;
Log.i("USerNameNN", userName+"");
Log.i("UserIDNN",userID+"");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent noteamshi=new Intent(Login.this,NoTeam.class);
noteamshi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(noteamshi);
finish();
}
}else
{
if(teamStatus.equals("1")){
try {
Log.i("Team Win tal","Log in hmar");
userName=jsonobj.getString("userName");
userID=jsonobj.getString("userID");
teamID=jsonobj.getString("teamID");
teamName=jsonobj.getString("teamName");
admin=jsonobj.getString("admin");
backNo=jsonobj.getString("backNo");
teamSaving[0]=userName;
teamSaving[1]=userID;
teamSaving[2]=teamID;
teamSaving[3]=teamName;
teamSaving[4]=admin;
teamSaving[5]=backNo;
Log.i("USerName", userName+"");
Log.i("UserID",userID+"");
Log.i("TeamId",teamID+"");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editor = prefsNagSetting.edit();
editor.putBoolean(NAG_SETTING, true);
editor.commit();
Intent teamshi=new Intent(Login.this,Team.class);
teamshi.putExtra("TeamSaving", teamSaving);
startActivity(teamshi);
}
else if(teamStatus.equals("0"))
{
try {
Log.i("noTeam Win tal","Log in hmar");
userName=jsonobj.getString("userName");
userID=jsonobj.getString("userID");
noteamSaving[0]=userName;
noteamSaving[1]=userID;
Log.i("USerNameNN", userName+"");
Log.i("UserIDNN",userID+"");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editor = prefsNagSetting.edit();
editor.putBoolean(NAG_SETTING, true);
editor.commit();
Intent noteamshi=new Intent(Login.this,NoTeam.class);
noteamshi.putExtra("NoTeamSaving", noteamSaving);
startActivity(noteamshi);
}
else{
showAlertDialog(Login.this,"Invalid Email and Password", "Enter Valid Email and Password", false);
}
}
}
Here is my code.
public void onClick(View arg0) {
// TODO Auto-generated method stub
isInternetPresent = conDetector.isConnectingToInternet();
Boolean save=false;
if (isInternetPresent){
isLoggedIn();
saveLoggedIn(save);
if (isLoggedIn()){
Intent team= new Intent(MainActivity.this,Team.class);
startActivity(team);
}
else{
Intent goLogin=new Intent(MainActivity.this,Login.class);
startActivity(goLogin);
}
}
else{
showAlertDialog(MainActivity.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
});
}
private boolean isLoggedIn() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
//The false represents the default value, if the variable is not stored
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
return isLoggedIn;
}
private void saveLoggedIn(boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean("isLoggedIn", value);
editor.commit();
}
That's my edit code.
In your star activity, you should verify if the user has already logged in.
How to know this?
You will need a boolean variable to know. A persistent variable. So, when you create the start activity, you will put:
if (variable){
goToLoggedActivity();
}else{
goToLogInActivity();
}
When the user logs in, you will need to set this variable to true
When the user logs out, you will need to set this variable to false
How to make it persistent?
Look at these functions.
private boolean isLoggedIn() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
//The false represents the default value, if the variable is not stored
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
return isLoggedIn;
}
private void saveLoggedIn(boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean("isLoggedIn", value);
editor.commit();
}
To Store the variable you just need to call this function above.
Another good way to make it you can see here
You can create a conditional statement in your LAUNCHER ACTIVITY. Make it like a splash screen or something
That is you can store the username and password in your shared preference along with the isRememeber=true/false. and when the user starts the app,the splash screen activity can check if the isRememeber activity has been set true or false by the user and can start the MainActivity or the LoginActivity.
Almost like this example here
Intent login=new Intent(Splashscreen.this,LoginActivity.class);
Intent Main=new Intent(Splashscreen.this,MainActivity.class);
......................
//Checking the shared preference here and storing the isRemebered value to a variable
if(isRemembered)
startActivity(Main);
else
startActivity(login);
Hope this helped you,all you have to do is make an additional activity that has to be launched as the LAUNCHER activity for more info on splash screens go here
After user login save a SharedPreference that the user logged in.
when the app starts if the user has that shared preference that means you can skip that activity and open the one you would after login.
Thing to consider - what if someone somehow fakes that SharedPreference? make sure it contains something that's validated against your server later to make sure that it was generated by a real login and wasn't faked (could even implement OAuth protocol).
I'm trying to access shared preference value created in one application from other applications I'm able to retrieve the data only if I close the app from the task manager else the changes are not reflecting.
First Activty:
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
sharedPreferences = getSharedPreferences(PREFS_READ_WRITE, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Editor prefsPrivateEditor = sharedPreferences.edit();
prefsPrivateEditor.putString(KEY_READ_WRITE, "test");
prefsPrivateEditor.commit();
To clear:
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sharedPreferences = getSharedPreferences(PREFS_READ_WRITE, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Editor prefsPrivateEditor = sharedPreferences.edit();
prefsPrivateEditor.clear();
prefsPrivateEditor.commit();
}
});
In other App I'm retrieving like this:
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.example.app", 0);
} catch (NameNotFoundException e) {
}
sharedPreferences = otherAppsContext.getSharedPreferences(PREFS_READ_WRITE, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
String authToken=sharedPreferences.getString(KEY_READ_WRITE, "WORLD READ WRITE EMPTY");
Toast.makeText(getApplicationContext(), authToken, Toast.LENGTH_SHORT).show();
Here is a bit different code, but looks like a working one
https://stackoverflow.com/a/6030399/995020
I am trying to report the install event to flurry.
I have implemented ReferralReceiver to be called when the app is being installed.
I have all the parameters in a map.
I am calling Flurry using my flurry code:
FlurryAgent.onStartSession(context, FlurryCode);
FlurryAgent.logEvent("Referral", referralParams);
FlurryAgent.onEndSession(context);
The data is being stored to the SharedPreferences but it is not being sent to flurry.
Has anyone encountered this problem.
#Override
public void onReceive(Context context, Intent intent)
{
LogManager.Info("ReferralReceiver intent.action=" + intent.getAction());
LogManager.Info("ReferralReceiver intent.DataString=" + intent.getDataString());
LogManager.Info("ReferralReceiver intent.intent=" + intent.toString());
// Workaround for Android security issue: http://code.google.com/p/android/issues/detail?id=16006
try
{
final Bundle extras = intent.getExtras();
if (extras != null) {
extras.containsKey(null);
}
}
catch (final Exception e) {
return;
}
Map<String, String> referralParams = new HashMap<String, String>();
// Return if this is not the right intent.
if (! intent.getAction().equals("com.android.vending.INSTALL_REFERRER")) { //$NON-NLS-1$
return;
}
String referrer = intent.getStringExtra("referrer"); //$NON-NLS-1$
if( referrer == null || referrer.length() == 0) {
return;
}
try
{
referrer = URLDecoder.decode(referrer, "UTF-8");
}
catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
LogManager.Info("ReferralReceiver intent.referrer=" + intent.getStringExtra("referrer"));
SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = storage.edit();
editor.putString("referrer", referrer);
editor.commit();
try {
if (intent.hasExtra("referrer")) {
String referrers[] = referrer.split("&");
for (String referrerValue : referrers)
{
String keyValue[] = referrerValue.split("=");
if (keyValue.length==2)
{
referralParams.put(keyValue[0], keyValue[1]);
}
}
}
}
catch (Exception e)
{
LogManager.Error(e);
return;
}
ReferralReceiver.storeReferralParams(context, referralParams);
String FlurryCode = SaverrUtils.GetFlurryCode();
FlurryAgent.onStartSession(context, FlurryCode);
FlurryAgent.logEvent("Referral", referralParams);
FlurryAgent.onEndSession(context);
LogManager.Info("New_Install");
}
public final static String PREFS_FILE_NAME = "ReferralParamsFile";
/*
* Stores the referral parameters in the app's sharedPreferences.
* Rewrite this function and retrieveReferralParams() if a
* different storage mechanism is preferred.
*/
public static void storeReferralParams(Context context, Map<String, String> params)
{
SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = storage.edit();
for(String key : SaverrUtils.EXPECTED_REFERRER_PARAMETERS)
{
String value = params.get(key);
if(value != null)
{
editor.putString(key, value);
}
}
editor.commit();
}
// Referral Parameters
public final static String[] EXPECTED_REFERRER_PARAMETERS = {
"utm_source",
"utm_medium",
"utm_term",
"utm_content",
"utm_campaign",
"referrer"
};
I think flurry has a minimum amount of seconds between start/end session for it to actually count. You can save all the data to shared preference or file, then when the user starts your activity check if it's been given to flurry. If it's new do FlurryAgent.logEvent(...).
I got a strange problem, that my app's SharedPreference seems lost some specific keys (not all) when the phone reboot.
Have you ever meet this problem? I used that key to store a serialized object and I did that in my own Application class.
public class Application extends android.app.Application {
static String key = "favs";
SharedPreferences settings;
public Favs favs;
#Override
public void onCreate() {
super.onCreate();
settings = PreferenceManager.getDefaultSharedPreferences(this);
String value = settings.getString(key, "");
if (value != null && value.length() > 0) {
try {
Favs = (Favs ) deSerialize(value.getBytes());
} catch (Exception ex) {
}
}
if(favs == null)
favs = new Favs ();
}
public void storeFavss() {
if (favs == null)
return;
try {
byte[] bytes = serialize(favs );
if(bytes != null)
{
String s = new String(bytes);
settings.edit().putString(key, s);
settings.edit().commit();
}
} catch (Exception ex) {
}
}
After debugging, I will show my own anwser here, hope it can help others.
the code below is bad. it seems the edit() method returns a new object each time.
settings.edit().putString(key, s);
settings.edit().commit();
If you are saving some serialized object bytes in the SharedPreference, Base64 it!
favs = (Favs ) deSerialize(value.getBytes());