adsense

Sunday, May 19, 2013

Customized Preferences

The PreferenceScreen can be customized to accept different kinds of settings. For example there is no "time" preference built into android.  However, we can easily do this by extending the DialogPreference class.

The code below allows you to set a time on the preference screen.  We accomplish this by overriding the dialog view to a TimePicker and bind it to our local variables.

We also override its view on the Preference screen to display the current chosen time so we don't have to click through it to see what it is set to.







public class TimePreference extends DialogPreference {
private int lastHour=0;
private int lastMinute=0;
private boolean is24HourFormat;
private TimePicker picker=null;
private TextView timeDisplay;

public TimePreference(Context ctxt) {
this(ctxt, null);
}

public TimePreference(Context ctxt, AttributeSet attrs) {
this(ctxt, attrs, 0);
}

@SuppressLint("NewApi")
public TimePreference(Context ctxt, AttributeSet attrs, int defStyle) {
super(ctxt, attrs, defStyle);

is24HourFormat = DateFormat.is24HourFormat(ctxt);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}

@Override
public String toString() {
if(is24HourFormat) {
return ((lastHour < 10) ? "0" : "")
+ Integer.toString(lastHour)
+ ":" + ((lastMinute < 10) ? "0" : "")
+ Integer.toString(lastMinute);
} else {
int myHour = lastHour % 12;
return ((myHour == 0) ? "12" : ((myHour < 10) ? "0" : "") + Integer.toString(myHour))
+ ":" + ((lastMinute < 10) ? "0" : "")
+ Integer.toString(lastMinute)
+ ((lastHour >= 12) ? " PM" : " AM");
}
}

@Override
protected View onCreateDialogView() {
picker=new TimePicker(getContext().getApplicationContext());
return(picker);
}

@Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setIs24HourView(is24HourFormat);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}

@Override
protected View onCreateView (ViewGroup parent) {
View prefView = super.onCreateView(parent);
LinearLayout layout = new LinearLayout(parent.getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 2);
layout.addView(prefView, lp);
timeDisplay = new TextView(parent.getContext());
timeDisplay.setGravity(Gravity.BOTTOM | Gravity.RIGHT);
timeDisplay.setText(toString());
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 1);
layout.addView(timeDisplay, lp2);
return layout;
}

@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);

if (positiveResult) {
picker.clearFocus();
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();

String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);

if (callChangeListener(time)) {
persistString(time);
timeDisplay.setText(toString());
}
}
}

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}

@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time=null;

if (restoreValue) {
if (defaultValue==null) {
time=getPersistedString("00:00");
}
else {
time=getPersistedString(defaultValue.toString());
}
}
else {
if (defaultValue==null) {
time="00:00";
}
else {
time=defaultValue.toString();
}
if (shouldPersist()) {
persistString(time);
}
}

String[] timeParts=time.split(":");
lastHour=Integer.parseInt(timeParts[0]);
lastMinute=Integer.parseInt(timeParts[1]);;
}
}

Monday, May 13, 2013

How to create notifications

Setting up Notifications 


Notifications in Android are represented by the Notification class. To create notifications you use the NotificationManager class which can be received from the Context, e.g. an activity or a service, via the getSystemService() method.

A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.



 To perform a broadcast via a pending intent get a PendingIntent via the getBroadcast() method of the PendingIntent class. To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().

The code would look something like this:



CharSequence from = "Program Name";
CharSequence message = "You have a message!" ;

NotificationManager nm = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent
.getActivity(this, 0, new Intent(), 0);


Notification notif = new Notification(R.drawable.icon,
message, System.currentTimeMillis());

notif.defaults=Notification.DEFAULT_ALL;
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = 0xff00ff00;
notif.ledOnMS = 300;
notif.ledOffMS = 1000;
notif.setLatestEventInfo(this, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;

nm.notify(1, notif);

You can customize the notification by setting properties and methods of your Notification object. 

Canceling Notifications 


The user can dismiss all notification or if you set your notification to auto-cancel it is also removed once the user selects it.

You can also call the cancel() for a specific notification ID on the NotificationManager. The cancelAll() method call removes all of the notifications you previously issued.



Saturday, May 11, 2013

Reacting to Preference changes

When a user changes a preference your program needs to react and update according to the change. The way to catch the change is to use PreferenceChangeListner. It implemented like this:



listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// code goes here to implement changes
}

};

prefs.registerOnSharedPreferenceChangeListener(listener);



Calling an IntentService from BroadcastReceiver triggered by AlarmManager


I needed to check a RSS feed once daily and notify the user.  I setup an alarm manager to trigger my BroadcastReceiver class.
AlarmManager am=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);           Intent intent = new Intent(this, Receiver.class);

intent.putExtra(ONE_TIME, Boolean.FALSE);

PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);

am.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pi);

The Receiver class calls an IntentService which fetches the updates. And then notifies the user through NotificationManager:

Don't forget to add your receiver to the maifest file! eg..    <receiver android:process=":remote" android:name="Receiver"></receiver>  

public class Receiver extends BroadcastReceiver {

NotificationManager nm;



@Override

public void onReceive(Context context, Intent intent) {



Intent service = new Intent(context, UpdateNumbers.class);
context.startService(service);

.
.
.
.
.


nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);

CharSequence from = "Nithin";


CharSequence message = "Crazy About Android...";

PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);



Notification notif = new Notification(R.drawable.icon,
"You Won...", System.currentTimeMillis());

notif.defaults=Notification.DEFAULT_ALL;
notif.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.ledARGB = 0xff00ff00;
notif.ledOnMS = 300;
notif.ledOffMS = 1000;

notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);