Tuesday, July 12, 2011

AlarmManager and NotificationManager sample code

This is not a complete tutorial on how to use AlarmManager and NotificationManager, but a simple sample.

The scenario is I want to have an alarm set to certain time. When it goes off, it show notification icon on status bar. When click on the notification, it will start an activity.

1. Create the BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager mNM;
        mNM = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, "Test Alarm",
        System.currentTimeMillis());
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, TestActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(context, context.getText(R.string.alarm_service_label), "This is a Test Alarm", contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number. We use it later to cancel.
        mNM.notify(R.string.alarm_service_label, notification);
    }
}

2. Add Receiver to Manifest.xml

<receiver android:process=":remote" android:name="AlarmReceiver"></receiver>

3. Set the alarm

public class AlarmService {
    private Context context;
    private PendingIntent mAlarmSender;
    public AlarmService(Context context) {
        this.context = context;
        mAlarmSender = PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);
    }

    public void startAlarm(){
        //Set the alarm to 10 seconds from now
        Calendar c = Calendar.getInstance();
        c.add(Calendar.SECOND, 10);
        long firstTime = c.getTimeInMillis();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, firstTime, mAlarmSender);
    }
}

How to use and customize tab(image, font)?

1. Create tabs


TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, TaskActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("task").setIndicator("Task", null).setContent(intent);
tabHost.addTab(spec); // Do the same for the other tabs
intent = new Intent().setClass(this, CalendarActivity.class);
spec = tabHost.newTabSpec("calendar").setIndicator("Calendar", null).setContent(intent);
tabHost.addTab(spec);

2. Customize tabs


TabHost tabHost = getTabHost();
LinearLayout linearLayout = (LinearLayout) tabHost.getChildAt(0);
TabWidget tw = (TabWidget) linearLayout .getChildAt(0);
RelativeLayoutfirstTabLayout = (RelativeLayout) tw.getChildAt(0);
//First tab
TextViewtabHeader = (TextView) firstTabLayout .getChildAt(1);
tabHeader .setTextSize(18); //Change text size
tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 36;
//Change first tab header height
firstTabLayout.setBackgroundResource(R.drawable.group_background_overdue);
tabHeader.setText("Tab page 1");


How to sort array list?

Sort by simple type property

1. Implement the Comparable interface


public class Item implements Comparable<Item> {

}

2. Implement the compareTo method.


@Override
public int compareTo(Item another) {
//Compare the name
return this.name.compareTo(another.name);
}

3. Call sort


List<Item> items = ..
items.sort();

Sort by user defined property

1. Create a new class


import java.util.Comparator;
public class ItemCompareByLocation implements Comparator<Item>{
@Override
public int compare(Item arg0, Item arg1) {
return arg0.getLocation().compareTo(arg1.getLocation());
}
}

2. Call sort


Collections.sort(items, new ItemCompareByLocation());

How to use Style

Create style.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="DetailTextView" parent="@android:style/TextAppearance">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">14sp</item>
<item name="android:textStyle">bold</item>
</style>
<style name="DateTimeButton" parent="@android:style/Widget.Button">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:gravity">left|center_vertical</item>
<item name="android:textSize">19sp</item>
</style>
</resources>

Use it in layout


<TextView android:id="@+id/TextView01" android:text="What" style="@style/DetailTextView" />

How to show toast?

Simple toast:


Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();

Customized toast:


LayoutInflater inflater;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.detail_toast,
(ViewGroup)arg0.findViewById(R.id.toast_layout_root));
TextView taskTextView = (TextView)
layout.findViewById(R.id.taskTextView);
taskTextView.setText(task.getName());
TextView detailTextView = (TextView)
layout.findViewById(R.id.detailTextView);
detailTextView.setText(sb.toString());
Toast toast = new Toast(context.getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();