(adsbygoogle = window.adsbygoogle || []).push({});
Android status bar notifications
This article provides a sample implementation for android status bar notifications. A notification is a message that is displayed outside the application's normal UI and visible when the user opens the notification drawer.Notifications in the notification drawer appear in 2 visual styles.
- Normal View - Appears in a view that is 64dp tall.
- Big View - Appears as a normal view notification which can be expanded with a gesture.
The application manifest for this example looks as below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sourcetricks.notificationsexample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Note the inclusion of "singleTop" to the launchMode. If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.
The code to include and remove notification is quite simple. The notification icon, title and content are set using the NotificationCompat builder. We need to associate an action with the notification is tapped. This is achieved using the PendingIntent. In this example, we launch the activity as the intent. This would bring the activity to foreground since "singleTop" launch mode is specified.
// Add app running notification private void addNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Notifications Example") .setContentText("This is a test notification"); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(contentIntent); // Add as notification NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(FM_NOTIFICATION_ID, builder.build()); } // Remove notification private void removeNotification() { NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(FM_NOTIFICATION_ID); }