This is not a complete tutorial on how to use AlarmManager and NotificationManager, but a simple sample.
The scenario is I want to have a 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);
}
}
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");
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());
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" />
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();
There are some icons and xmls under C:\Android\android-sdk-windows-1.6_r1\platforms\android-1.5(or other version)\data\res\drawable
To use different icons for standard control, we can copy the xml file and icons used in the xml to our own \drawable folder and set it in the layout xml
1) Grab the checkbox_background.xml and checkbox.xml from above folder and copy to the drawable folder in my project
2) Copy all the PNG files for the checkbox to the drawable folder in my project
3) Change the layout to use the checkbox (In my case, it is a CheckedTextView)
android:checkMark="@drawable/checkbox"

Set Layout_weight to greater than 0


When I use anything other than textview in a listview, the context menu stop working. Now to have a check box in a list view, I have to use CheckedTextView. But the text in CheckedTextView appears on the left side of the checkbox. I don’t know how to change it, so I use a CheckedTextView with no text and a TextView.
<CheckedTextView android:id="@+id/categoryCheckedTextView"
android:layout_width="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:layout_height="wrap_content"
android:clickable="true">
</CheckedTextView>
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Packing List");
alertDialog.setMessage("Could not find the file.");
alertDialog.show();
Use KEYPAD_7 or KEYPAD_9 on you desktop. You need to turn off your Num Lock.
To dynamically change the background color, use myView.setBackgroundResource(R.color.my_color) instead myView.setBackgroundColor(R.color.my_color)
How to align text in text view?
When trying to align the text to the right in text , set the “layout_gravity” to right doesn’t work. Need to set “gravity” to right.
PackageInfo pi;
String versionName = "";
try {
pi = getPackageManager().getPackageInfo(getPackageName(), 0);
versionName = pi.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
TextView itemTextView = (TextView)itemView.findViewById(R.id.itemTextView);
itemTextView.setText(item.getItem() + "(" + Integer.toString(item.getQuantity()) + ")");
if (item.isChecked())
itemTextView.setPaintFlags(itemTextView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
else
itemTextView.setPaintFlags(itemTextView.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
How to show HTML content in Android?
You can use WebView to display HTML content in Android.
WebView webView = (WebView)helpView.findViewById(R.id.helpWebView);
String data = fileUtitlity.readFileToString(R.raw.help);
webView.loadData(data, "text/html", "UTF-8");
How to loop through Hashtable in Java?
Hashtable<DateTime, String> alarms = new Hashtable<DateTime, String>();
Enumeration<DateTime> keys = alarms.keys();
while( keys.hasMoreElements() ) {
DateTime alarmTime = keys.nextElement();
String value = alarms.get(alarmTime);
alarmService.startAlarm(alarmTime, value);
}
To remove a view from the layout, use View.GONE. View.Invisible will save the space
taskProgressBar.setVisibility(View.GONE);
taskTextView.setBackgroundResource(android.R.color.transparent);
How to set system color?
routineTextView.setTextColor(context.getResources().getColor(android.R.color.primary_text_dark));
How to set color to gradient color?
Define group_background_overdue.xml in drawable folder:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="4dp" />
<gradient
android:angle="270"
android:startColor="#F6A59D"
android:endColor="#F41A0B" />
</shape>
Then set the color using the following code:
groupTextView.setBackgroundResource(R.drawable.group_background_overdue);
How to read file to String and how to convert bytes to string?
public String readFileToString(int resId){
InputStream ins = context.getResources().openRawResource(resId);
int size;
String file = "";
try {
size = ins.available();
// Read the entire resource into a local byte buffer.
byte[] buffer = new byte[size];
ins.read(buffer);
file = new String(buffer, 0, size, "UTF8");
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
How to set Android default icon for menu items?
android:icon="@android:drawable/ic_menu_preferences"
The following code is the serialization part of the Category class in PackingList project. Since the category has an arraylist of items, I have to put it in Bundle. To de-serialize it, I need to retrieve items from the Bundle. To do that, I was using Bundle d = in.readBundle(). However, I received “ClassNotFound exception when unmarshallingâ€. I have to pass in the ClassLoader so it knows it’s for the Item.
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(category);
Bundle b = new Bundle();
b.putParcelableArrayList("items", items);
dest.writeBundle(b);
}
public static final Parcelable.Creator<Category> CREATOR =
new Parcelable.Creator<Category>() {
public Category createFromParcel(Parcel in) {
Category category = new Category();
category.category = in.readString();
Bundle b = in.readBundle(Item.class.getClassLoader());
category.items = b.getParcelableArrayList("items");
return category;
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
……
dialog = ProgressDialog.show(this, "",
"Loading Calendar and Tasks. Please wait...", true);
……
CalendarThread calendarThread = new CalendarThread();
calendarThread.start();
}
private class CalendarThread extends Thread {
@Override
public void run() {
//Long running process
……
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//Process after the long running process
……
dialog.dismiss();
}
};
}
This blog shows you an example on how to create custom dialog. For more information on creating different kind of dialogs, please visit http://developer.android.com/guide/topics/ui/dialogs.html
1. Create layout for the dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10sp">
<EditText android:text=""
android:id="@+id/categoryEditText"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:singleLine="true">
</EditText>
</LinearLayout>
2. Override onCreateDialog in the Activity
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case CATEGORY_DETAIL:
LayoutInflater li = LayoutInflater.from(this);
View categoryDetailView = li.inflate(R.layout.category_detail, null);
AlertDialog.Builder categoryDetailBuilder = new AlertDialog.Builder(this);
categoryDetailBuilder.setTitle("Edit Category");
categoryDetailBuilder.setView(categoryDetailView);
AlertDialog categoryDetail = categoryDetailBuilder.create();
categoryDetail.setButton("OK", new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
AlertDialog categoryDetail = (AlertDialog)dialog;
EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
if (categories.get(selectedIndex)!=null){
//... some code
}
});
categoryDetail.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}});
return categoryDetail;
default:
break;
}
return null;
}
3. Override onPrepareDialog to dynamically set default value before the dialog is open
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case CATEGORY_DETAIL:
AlertDialog categoryDetail = (AlertDialog)dialog;
EditText et = (EditText)categoryDetail.findViewById(R.id.categoryEditText);
et.setText(defaultValue);
break;
default:
break;
}
}
4. Call showDialog to display the dialog
static final private int CATEGORY_DETAIL = 1;
//... some code
showDialog(CATEGORY_DETAIL);