how to run a service in background and managed by SharedPreferences Settings - android

I'm coding an app, where there is a PrefereceActivity which contains a SwitchPreference that start or stop a service when the user switches on or off it, and it saves the status of the switch in to SharedPreference.
Then in the MainActivity I registered A On SharedPreferenceChangeListener, which read the status of the switch, then based on the it start or Stop the service.
// This is the code in MainATY:
preferences= getPreferences(Activity.MODE_PRIVATE);
editor= preferences.edit();
preferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
boolean pushNotification= sharedPreferences.getBoolean(MyPreferences.pushNotificationKey,true);
if (pushNotification)
{
if (!NotificationService.isRunning){
Intent i = new Intent(MainActivity.this, NotificationService.class);
bindService(i,MainActivity.this,Context.BIND_AUTO_CREATE);
}
}
else{
if (NotificationService.isRunning){
unbindService(MainActivity.this);
}
}
}
});
and this is PreferenceATY code:
pushNotification.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
pushNotification= (SwitchPreference) preference;
editor.putBoolean(pushNotificationKey,pushNotification.isChecked());
if (!editor.commit())
{
Toast.makeText(MyPreferences.this, R.string.changes_saved,Toast.LENGTH_SHORT).show();
}
return true;
}
});
But it doesn't work, can you help me?
One last thing, how can I make Notifications with more than one line of the content?
This is my notification function:
String thingsToDo=new String();
while (c.moveToNext())
{
thingsToDo+=String.format("%s: %s: %s "
,c.getString(c.getColumnIndex("subject"))
,c.getString(c.getColumnIndex("typeOfEvent"))
,c.getString(c.getColumnIndex("what"))
);
thingsToDo+="/n";
}
thingsToDo.substring(0,4);
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.small_icon_diary)
.setContentTitle(getString(R.string.homework_for_tomorrow))
.setContentText(thingsToDo);
mBuilder.setShowWhen(true);
Intent i= new Intent(MainActivity.this,NotificationViewActivity.class);
Bundle b= new Bundle();
b.putString("time",time);
i.putExtra("b",b);
i.putExtra("time",time);
mBuilder.addAction(R.drawable.small_icon_diary,"Open",PendingIntent.getActivity(MainActivity.this,0,i,0));

I have solved the Question about Notification in this way:
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.small_icon_diary)
.setContentTitle(getString(R.string.homework_for_tomorrow))
.setContentText(thingsToDo)
.setStyle(new NotificationCompat.BigTextStyle().bigText(thingsTodo));

Related

SharedPreferences always shows the same thing

So I'm trying to save a value to sharedpreferences by a click of a button, and then see which value it is in another activity. (to basically set a background for activity2 based on which button they pressed in activity1)
Saving code:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
background.remove("selectedBG");
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putInt("selectedBG", 1);
background.commit();
}
if(btn2 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 2);
Toast.makeText(this, "btn2", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn3 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 3);
Toast.makeText(this, "btn3", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn4 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 4);
Toast.makeText(this, "btn4", Toast.LENGTH_SHORT).show();
background.commit();
}
}
And then, the Toast here always shows "chosenbackground:0":
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
LLayout=(LinearLayout)findViewById(R.id.llayout);
SharedPreferences background2 = getSharedPreferences("Background", MODE_PRIVATE);
int chosenBackground = background2.getInt("selectedBg", 0);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
if (chosenBackground != 0) {
if(chosenBackground==1)
{
LLayout.setBackgroundColor(Color.WHITE);
}
if(chosenBackground==2)
{
LLayout.setBackgroundColor(Color.rgb(34,34,34));
}
if(chosenBackground==3)
{
LLayout.setBackgroundColor(Color.rgb(51,68,85));
}
if(chosenBackground==4)
{
LLayout.setBackgroundColor(Color.rgb(68,34,17));
}
}
}
Answer for your question is that you have misspelled the key in second activity, in first one you are using "selectedBG" but in the second one "selectedBg". It is not the same, it's case sensitive. Correct in the second one for "selectedBG" and it should work.
Using the SharedPreferences here it's really bad idea, if u only want to pass a background or rather a color if I see it correctly. Just pass it in intent:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("EXTRA_BACKGROUND_ID", background);
startActivity(intent);
Access that intent on next activity for eg. in onCreate()
String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
#Updated
public class PreferencesUtils {
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor prefsEditor;
public static final String KEY_BACKGROUND = "BACKGROUND";
public PreferencesUtils(Context context) {
this(context, PREFS_DEFAULT);
}
public PreferencesUtils(Context context, String prefs) {
this.sharedPrefs = context.getSharedPreferences(prefs, Activity.MODE_PRIVATE);
this.prefsEditor = sharedPrefs.edit();
}
public int getValue(String key, int defaultValue){
return sharedPrefs.getInt(key, defaultValue);
}
public boolean saveValue(String key, int value){
prefsEditor.putInt(key, value);
return prefsEditor.commit();
}
}
PreferencesUtils preferencesUtils = new PreferencesUtils(this);
preferencesUtils.saveValue(PreferencesUtils.KEY_BACKGROUND, 1); //saveValue
preferencesUtils.getValue(PreferencesUtils.KEY_BACKGROUND, 0); //getValue,
second arg is defult if not found
Use if (!background2.contains("selectedBg"))
to check ,first whether the key exists and if not getInt is not able to create a key and hence always returns default value 0.Also you can use apply() instead of commit to check whether commit has taken place successfully.Debug the code more to see all possibilities
int chosenBackground=0;
if (!background2.contains("selectedBg"))
{
//is called once when after you freshly install the app
background2.putInt("selectedBG", 0);
}
else
chosenBackground = background2.getInt("selectedBg", 0);

Togglebutton state with shared preferences not changable via asynctask

Ok I have a togglebutton in my main activity. I want the state of this button to be saved if I switch to another activity, minimize the app and a service should be able to set the button state to false (not clicked). Everything worked fine, but for some reason when I started Android Studio again it didnĀ“t work anymore?!
MainActivity:
monitor = (ToggleButton)findViewById(R.id.toggleButton);
monitor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (monitor.isChecked()) {
Intent intent = new Intent(MainActivity.this, NotifiyService.class);
startService(intent);
} else {
Intent intent = new Intent(MainActivity.this, NotifiyService.class);
stopService(intent);
}
}
});
In the onStop Method the following is executed:
if (monitor.isChecked())
{
tbstate = true;
SharedPreferences sharedPreferences1 = getSharedPreferences("tbstate",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.putBoolean("keyTB",tbstate);
editor.commit();
}
else
{
tbstate = false;
SharedPreferences sharedPreferences1 = getSharedPreferences("tbstate",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.putBoolean("keyTB",tbstate);
editor.commit();
}
The onStart Method:
//get Togglebutton state
SharedPreferences sharedPreferences6 = getSharedPreferences("tbstate", MODE_PRIVATE);
monitor.setChecked(sharedPreferences6.getBoolean("keyTB",false));
Asynctask (not complete). In the onPostExecute I set the tbstate to false and in onDestroy it is saved in the sharedpreference. Then a message pop ups which "leads" to main2activity of the same app. When I go from main2activity to mainactivity the togglebutton is still activated.
I hope it is clear what I want ;-)
#Override
public void onDestroy() {
//super.onDestroy();
Th1.interrupt();
checkhttp.cancel(false);
SharedPreferences sharedPreferences8 = getSharedPreferences("tbstate",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences8.edit();
editor.putBoolean("keyTB", tbstate);
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
stopSelf();
}
#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){
//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());
tbstate=false;
onDestroy();
}
}
}
You need call commit() method of shared preference editor after any change in shared preference..
You haven't called this in ondestroy method
It happens because onPostExecute methods executes after onDestroy of Activity and preferences didn't saved. You need to save preferences in onPostExecute method too

SharedPreference cannot save data across activities

I'm working on a splash screen where it will determine whether the user has previously registered or not based on SharedPreference stored values.
Please allow me to ask this question one more time, as I've gone through so many help / tutorials and examples, it didn't help a bit. I've been stuck here for 2 days now... Any help is really really appreciated.
There are 2 activities involved. The app starts with SplashScreen activity, then if sharepreference file return non-null (means user registered before), it will start mainactivity. Else if sharepreference file return null (means first time user, it brings user to the registration activity)...
PROBLEM: whenever the app restart (even with user registered), it always go to registration page !! PLEASE HELP !!
code for SPLASHSCREEN activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timerThread.start();
}
protected void onStart() {
super.onStart();
openNextActivity();
}
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
if (sp.contains("Name")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
below is the code for REGISTRATION activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etMobilePhone = (EditText) findViewById(R.id.etMobilePhone);
tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // imei
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
writePref();
break;
}
finish();
}
private void writePref() {
String userName = etName.getText().toString(); //prepare variables values for write
String userPhone = etMobilePhone.getText().toString(); //prepare variables values for write
String userEmail = etEmail.getText().toString(); //prepare variables values for write
String userImei = tel.getDeviceId().toString(); //prepare variables values for write
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString(Name, userName); //write sharepreferences
editor.putString(Phone, userPhone); //write sharepreferences
editor.putString(Email, userEmail); //write sharepreferences
editor.putString(Imei, userImei); //write sharepreferences
editor.commit(); //sharepreference
Toast toast = Toast.makeText(getApplicationContext(), "updated sharepreferences", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,50);
toast.show();
}
Please guide me to the right directions. Thank you for reading and responding.
Change your openNextActivity() method to this:
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
String defaultValue = "na";
String storedValue = sp.getString("Name", defaultValue);
if (!storedValue.equalsIgnoreCase("na")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else { //if you get default value i.e. "na"
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
Instead of checking if the key exists, check for its value. If key not found return a default value and and check against the returned value.
Update (From Jelle's comment below): Also change your RegistrationActivity. Change editor.putString(Name, userName); into editor.putString("Name", userName);
Thanks guys... wanted to share the solution...
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString("Name", userName); //write sharepreferences
editor.putString("Phone", userPhone); //write sharepreferences
editor.putString("Email", userEmail); //write sharepreferences
editor.putString("Imei", userImei); //write sharepreferences
editor.commit(); //sharepreference
Apparently, the solution is the ""... thanks for all the wonderful people...

Android- saving data that updates before restarting the application

In the Android application I'm working on, I have one activity where the user inputs data that is saved using SharedPreferences, and is used for certain calculations on the main activity. An issue I'm having is that after saving the data, the changes do not actually take effect until after the application is restarted. Is there a way I can make it so the variables associated with these SharedPreferences are updated before restarting?
Here is where I save the data in a separate activity.
saveBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedWeight", weightString).commit();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putString("savedAge", ageString).commit();
//Intent i = new Intent("com.williammiller.capstonelapv2.MainActivity");
//startActivity(i);
finish();
}
});
And here is where I'm checking in the main activity to see what they are
String age = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedAge", "25");
String weight = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getString("savedWeight", "200");
startBn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "weight = " + weightInt + " age = " + ageInt, Toast.LENGTH_LONG).show();
}
});
You can use a BroadcastReceiver to achieve that. Do as following:
Register a BroadcastReceiver in your Main Activity:
public static final String UPDATE_ACTION = "yourpackage.update";
public static final String EXTRA_KEY_AGE = "key_age";
public static final String EXTRA_KEY_WEIGHT = "key_weight";
private BroadcastReceiver mReceiver;
// In the onCreate() method
mReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UPDATE_ACTION)){
// Here you get the update data from another activity
String age = intent.getStringExtra(EXTRA_KEY_AGE);
String weight = intent.getStringExtra(EXTRA_KEY_WEIGHT);
}
}
};
registerReceiver(receiver, new IntentFilter(UPDATE_ACTION ));
// Add the following code to onDestroy() method
unregisterReceiver(mReceiver);
Send a broadcast in your "separate activity":
public void onClick(View v) {
weightString = weightText.getText().toString();
ageString = ageText.getText().toString();
Intent intent = new Intent(MainActivity.UPDATE_ACTION );
intent.putExtra(MainActivity.EXTRA_KEY_AGE, ageString);
intent.putExtra(MainActivity.EXTRA_KEY_WEIGHT, weightString );
sendBroadcast(intent);
}
Update: Change part of the code to unregister the BroadcastReceiver when activity is destroyed.

Checkbox Preference and Checking if its enabled or disable

Im having issues with the below code on making a checkbox preference, That by default is checked. My first activity is a simple splash screen, and simply before show my imageview thread i want to check if the checkbox has been disable if so then i want to intent directly to the main activity and by default i show my image thread, or in reversed order of that.
Currently my splashscreen is launching no matter if its checked or now, Any help would be greatly appreciated
XML
<CheckBoxPreference
android:title="#string/category_tools_startupscreen"
android:summary="#string/category_tools_startupscreen_summary"
android:key="boot_animation" android:order="5" android:enabled="true"/>
SplashScreen
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("boot_animation", true)) {
setContentView(R.layout.splash_screen);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// changed from 5000 to 4000 11.29
while (waited < 3000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.MainActivity");
startActivity(i);
finish();
}
}
};
splashThread.start();
}
else {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.MainActivity");
startActivity(i);
finish();
}
}
Settings
final CheckBoxPreference checkboxPref2 = (CheckBoxPreference) getPreferenceManager().findPreference("boot_animation");
checkboxPref2.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue instanceof Boolean){
Boolean boolVal = (Boolean)newValue;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("checked", boolVal);
editor.commit();
}
return true;
}
});
In your splash screen
PreferenceManager.setDefaultValues(this, R.xml.your_setting_xml, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("boot_animation", true)) {
.........
You do not even need the code you posted for the Settings

Categories

Resources