Where have i to "call" my notification? I want that appears when click the checkboxpreferenced . edit MainActivity.java
import...//here all imports i need
public class MainActivity extends Activity {
CheckBoxPreference firtsDependent;
...
public void onCreate(Bundle savedInstanceState){
super onCreate(savedInstanceState);
setContentView(R.layout.main);
//and your code
}
}
private void sendSimpleNotification(){
boolean pref_opt1= PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getBoolean("firstDependent", false);
if(pref_opt1) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(service.this);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Context");
notificationBuilder.setTicker("TickerText");
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setSmallIcon(R.drawable.ic_stat_icon);
Intent notificationIntent = new Intent(this, service.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(1, notificationBuilder.build());
}
else{
mNotificationManager.cancel(SIMPLE_NOTIFICATION_ID);
}
}
the settings.java
import..//all imports i need
public class settings extends PreferenceActivity{
public void onCreate(Bundle savedInstanceState){
super onCreate(savedInstanceState);
setContentView(R.xml.settings);
}
}
this is the structure of my code..and of course i have a xml where inside there is the checkboxpreferences with id and key firstDependent
.
end edit.
I tried in onResume
and works only if i go out from preferences screen. How can i do what i want?
You'll need a checkbox listener like this one:
cb = (CheckBox)findViewById(R.id.checkBox);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
sendSimpleNotification();
}
}
For checkbox preferences use:
final CheckBoxPreference cbPR= (CheckBoxPreference) getPreferenceManager().findPreference("cbPref");
cbPR.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
sendSimpleNotification();
return true;
}
});