adsense

Thursday, November 21, 2013

Listeners and Callbacks

There are three ways to setup a listener in Android:

  • android:onClick="myClickHandler"
This calls the method myClickHandler(View v) in the Activity. It's importent to know that the Activity is responsible for this method. Even if you are using this in a layout of a Fragment.
  • implements OnClickListener
You have to override the onClick(View v). If you have more Views, which are clickable, you can use this to bundle all code of the views in this method. This is better maintainable. Also it reduces Object creation. If you have multiple buttons, IMO this is better than associate multiple click listeners to the buttons.
onClick(View v){
    switch(v.getId())
    case R.id.button1:
       // do something related to this button 1
    case R.id.button2:
       // do something related to this button 2
    ...
}
  • setOnClickListener(new View.OnClickListener()
If you have one view set the listener directly for more readability by using an anonymous class. With this you mostly have the implementation of the listener in the scope of the view.
There is no real convention when to use the second or third approach. It's mostly opinion based . But be careful with the first approach, especially in Fragment scenarios.

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);

Monday, January 28, 2013

Can I use this Intent?

Android offers a very powerful and yet easy to use tool called intents. An intent can be use to turn applications into high-level libraries and make code re-use something even better than before. The Android Home screen and AnyCut use intents extensively to create shortcuts for instance. While it is nice to be able to make use of a loosely coupled API, there is no guarantee that the intent you send will be received by another application. This happens in particular with 3rd party apps, like Panoramio and its RADAR intent.
While working on a new application, I came up with a very simple way to find out whether the system contains any application capable of responding to the intent you want to use. I implemented this technique in my application to gray out the menu item that the user would normally click to trigger the intent. The code is pretty simple and easy to follow:




/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param context The application's environment.
* @param action The Intent action to check for availability.
*
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
Here is how I use it:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
final boolean scanAvailable = isIntentAvailable(this,
"com.google.zxing.client.android.SCAN");

MenuItem item;
item = menu.findItem(R.id.menu_item_add);
item.setEnabled(scanAvailable);

return super.onPrepareOptionsMenu(menu);
}
In this example, the menu is grayed out if the Barcode Scanner application is not installed. Another, simpler, way to do this is to catch the ActivityNotFoundException when calling startActivity() but it only lets you react to the problem, you cannot predict it and update the UI accordingly to prevent the user from doing something that won't work. The technique described here can also be used at startup time to ask the user whether he'd like to install the missing package, you can then simply redirect him to the Android Market by using the appropriate URI.
Note: this article was originally posted on my personal blog.

Tuesday, January 1, 2013

android:onClick(XML) vs. OnClickListeners (code)

1. Activity as OnClickListener
You can make your Activity implement View.OnClickListener interface which is generally a good idea. It makes clear explanation that your Activity can receive messages from Buttons.

2. Use android:onClick attribute in XML definition of a Button.
In my opinion is the best solution.
Here we need to do two things: 1. in XML layout of our Activity when we define a Button we need to add an attribute: android:onClick="onButtonClick" where we define the name of the method we need to implement in our Activity. 2. Implement public void onButtonClick(View v) method in our Activity.


Clean and clear solution. Less code. Brilliant! :)




The advantage of 2th way to do it is that first you type less(Activity isn't implementing interface, you don't need to have a variable for your button, you don't do  findViewById and setOnClickListener etc.), which is always good and clean, second you don't deal with scopes too much so here it's just another public method in your Activity.
Also you always know where to find your action.
The down side is if you'd reuse xml layout where you've defined android:onClick attribute on a Button somewhere else you would have to implement the method defined in the attribute all the the time. Otherwise you'd get a crash because of unfound/unimplemented method.

Have fun:)

These two code snippets are totally the same but just implemented in two different ways.
Code Implementation:

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myFancyMethod(v);
}
});

// some more code

public void myFancyMethod(View v) {
// does something very interesting
}
Above is a code implementation of an OnClickListener. And not the XML implementation.
XML Implementation:


<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myFancyMethod" />
<!-- even more layout elements -->
Now in the background Android does nothing else than the Java code calling your method on a click event.
Note that with the XML above, Android will look for the onClick method myFancyMethod() only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.