一、使用系統定義的Notification
以下是使用示例代碼:
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener { private NotificationManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mian_water); //獲取到通知管理器 manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_wf_back: // 定義Notification的各種屬性 int icon = R.drawable.button_login; //通知圖標 CharSequence tickerText = "Hello"; //狀態欄顯示的通知文本提示 long when = System.currentTimeMillis(); //通知產生的時間,會在通知信息里顯示 Notification myNotify = new Notification(icon,tickerText,when); Context context = getApplicationContext(); //上下文 CharSequence contentTitle = "My Notification"; //通知欄標題 CharSequence contentText = "Hello World!"; //通知欄內容 Intent notificationIntent = new Intent(this,WaterActivity.class); //點擊該通知后要跳轉的Activity PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,0); myNotify.setLatestEventInfo(context, contentTitle, contentText, contentIntent); manager.notify(0x00000008, myNotify); //如果想要更新一個通知,只需要在設置好notification之后,再次調用 setLatestEventInfo(),然后重新發送一次通知即可,即再次調用notify()。 break; } } }
二、使用自定義的 Notification
要創建一個自定義的Notification,可以使用RemoteViews。
要定義自己的擴展消息,首先 要初始化一個RemoteViews對象,然后將它傳遞給Notification的contentView字段,再把PendingIntent傳遞給 contentIntent字段。
以下示例代碼是完整步驟:
1、創建一個自 定義的消息布局 my_notification.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#ffffff" android:orientation="vertical" > <TextView android:id="@+id/text_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" /> </LinearLayout>
2、 在程序代碼中使用RemoteViews的方法來定義image和text。然后把RemoteViews對象傳到contentView字段
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.my_notification); rv.setTextViewText(R.id.text_content, "hello wrold!"); myNotify.contentView = rv;
3、 為Notification的contentIntent字段定義一個Intent(注意,使用自定義View不需要 setLatestEventInfo()方法)
Intent intent = new Intent(Intent.ACTION_MAIN); PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 1); myNotify.contentIntent = contentIntent;
4、發送通知
manager.notify(0x00000008, myNotify);
5.完整代碼
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.widget.RemoteViews; public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener { private NotificationManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mian_water); //獲取到通知管理器 manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_wf_back: Notification myNotify = new Notification(); myNotify.icon = R.drawable.button_login; myNotify.tickerText = "TickerText:您有新短消息,請注意查收!"; myNotify.when = System.currentTimeMillis(); //myNotify.flags = Notification.FLAG_NO_CLEAR;// 不能夠自動清除 RemoteViews rv = new RemoteViews(getPackageName(), R.layout.my_notification); rv.setTextViewText(R.id.text_content, "hello wrold!"); myNotify.contentView = rv; Intent intent = new Intent(Intent.ACTION_MAIN); PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 1); myNotify.contentIntent = contentIntent; manager.notify(0x00000008, myNotify); //如果想要更新一個通知,只需要在設置好notification之后,再次調用 setLatestEventInfo(),然后重新發送一次通知即可,即再次調用notify()。 break; } } }
6.清除
manager.cancel(2);
參數屬性:
// 定義Notification的各種屬性 Notification notification =new Notification(R.drawable.icon, "測試", System.currentTimeMillis()); //FLAG_AUTO_CANCEL 該通知能被狀態欄的清除按鈕給清除掉 //FLAG_NO_CLEAR 該通知不能被狀態欄的清除按鈕給清除掉 //FLAG_ONGOING_EVENT 通知放置在正在運行 //FLAG_INSISTENT 是否一直進行,比如音樂一直播放,知道用戶響應 notification.flags |= Notification.FLAG_ONGOING_EVENT; // 將此通知放到通知欄的"Ongoing"即"正在運行"組中 notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在點擊了通知欄中的"清除通知"后,此通知不清除,經常與FLAG_ONGOING_EVENT一起使用 notification.flags |= Notification.FLAG_SHOW_LIGHTS; //DEFAULT_ALL 使用所有默認值,比如聲音,震動,閃屏等等 //DEFAULT_LIGHTS 使用默認閃光提示 //DEFAULT_SOUNDS 使用默認提示聲音 //DEFAULT_VIBRATE 使用默認手機震動,需加上<uses-permission android:name="android.permission.VIBRATE" />權限 notification.defaults = Notification.DEFAULT_LIGHTS; //疊加效果常量 //notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND; notification.ledARGB = Color.BLUE; notification.ledOnMS =5000; //閃光時間,毫秒 // 設置通知的事件消息 CharSequence contentTitle ="標題"; // 通知欄標題 CharSequence contentText ="內容"; // 通知欄內容 //如果需要跳轉到指定的Activity,則需要設置PendingIntent Intent notificationIntent =new Intent(A.this, B.class); // 點擊該通知后要跳轉的Activity notificationIntent.putExtra("date","需要傳遞的參數"); // FLAG_UPDATE_CURRENT 更新數據,如果有多個PendingIntent,且requestCode相同,則會替換為最新extra數據 //如果需要通過不同的extra數據,進行處理,就需要requestCode不相同 int requestCode = new Random().nextInt(); PendingIntent contentItent = PendingIntent.getActivity(this, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(this, contentTitle, contentText, contentItent); // 把Notification傳遞給NotificationManager notificationManager.notify(0, notification);
注意:
new Intent(this,this.getClass())保證了點擊通知欄里的通知可以回到該Activity
但是,假如該Activity還在后台運行,並沒有運行,通知事件響應后,系統會自動結束該Activity,然后再重新啟動Activity,這不是我們要的。
解決方法為:在manifest.xml文件中找到該Activity,添加屬性android:launchMode="singleTask“。這個屬性很明顯,就是只允許有一個該Activity運行,如果正在運行,則只能切換到當前運行的Activity,而不能重新啟動Activity。
三、創建定時器
源代碼如下:
import java.util.Timer; import java.util.TimerTask; public class WaterActivity extends Activity implements OnClickListener, OnSeekBarChangeListener { private Timer mTimer = null; private TimerTask mTimerTask = null; private int isPause = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mian_water); } private void startMyTimer(){ if (mTimer == null) { mTimer = new Timer(); } if (mTimerTask == null) { mTimerTask = new TimerTask() { @Override public void run() { do { try { if(isPause == 0) isPause = 1; else isPause = 0; Message message = new Message(); message.what = isPause; handler.sendMessage(message); } catch (IllegalStateException e) { } } while (false); } }; } if(mTimer != null && mTimerTask != null ) mTimer.schedule(mTimerTask, 0, 500); } private void stopMyTimer(){ if (mTimer != null) { mTimer.cancel(); mTimer = null; } if (mTimerTask != null) { mTimerTask.cancel(); mTimerTask = null; } } }