Created
February 7, 2012 23:08
-
-
Save regisd/1762830 to your computer and use it in GitHub Desktop.
Android utility method to add a notification
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package info.decamps.droid.demo; | |
import android.app.Notification; | |
import android.app.NotificationManager; | |
import android.app.PendingIntent; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.app.Activity; | |
public class BaseActivity extends Activity { | |
/** | |
* Utility function to display a notification from an activity. | |
* | |
* Don't use this method as it demonstrates a bug. Please see | |
* http://regis.decamps.info/blog/?p=2529 | |
* | |
* @param contentText | |
* The text the notification holds. | |
* @param targetActivity | |
* The activity to start when the notification is clicked. | |
*/ | |
public void displayNotification(CharSequence contentText, | |
Class<?> targetActivity) { | |
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); | |
int icon = android.R.drawable.stat_notify_chat; | |
long when = System.currentTimeMillis(); | |
// I don't use ticker text | |
Notification notification = new Notification(icon, null, when); | |
Context context = this; | |
// my title is always my application name | |
String contentTitle = getString(R.string.app_name); | |
int requestCode = 0; // javadoc says "private code curently not used" | |
Intent intent = new Intent(context, targetActivity); | |
PendingIntent contentIntent = PendingIntent.getActivity(context, | |
requestCode, intent, Intent.FLAG_ACTIVITY_NEW_TASK); | |
notification.setLatestEventInfo(context, contentTitle, contentText, | |
contentIntent); | |
int id = (int) (Math.random() * 100); | |
notificationManager.notify(id, notification); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package info.decamps.droid.demo; | |
import android.os.Bundle; | |
public class NotifActivity extends BaseActivity { | |
/** Called when the activity is first created. */ | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.main); | |
displayNotification("Oh brother, thou have a message", | |
MessageActivity.class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment