The code is fairly simple so I’ll dump it here in it’s complete form:
package com.giantflyingsaucer; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class AndroidNotifications extends Activity { private final int NOTIFICATION_ID = 1010 ; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button)findViewById(R.id.createNotificationButton); btn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { @Override public void run() { triggerNotification(); } }; timer.schedule(timerTask, 3000 ); } }); } private void triggerNotification() { CharSequence title = "Hello" ; CharSequence message = "Hello, Android!" ; NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.icon, "A New Message!" , System.currentTimeMillis()); Intent notificationIntent = new Intent( this , AndroidNotifications. class ); PendingIntent pendingIntent = PendingIntent.getActivity( this , 0 , notificationIntent, 0 ); notification.setLatestEventInfo(AndroidNotifications. this , title, message, pendingIntent); notificationManager.notify(NOTIFICATION_ID, notification); } } |
Here is the main.xml:
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > < Button android:id = "@+id/createNotificationButton" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Create Notification" android:padding = "10dp" /> </ LinearLayout > |
Here is the final result: