Notification是APP 向系統發出通知時,它將先以圖標的形式顯示在通知欄中。用戶可以下拉通知欄查看通知的詳細信息。我們可以在通知欄實現自定義的效果,也可以結合service和BroadCastReceiver實現推送的效果,下面是在通知欄實現計時器的功能。
首先創造NotificationManager 對象:
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
然后再創建Builder對象:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.wzzq_logo)
.setContentTitle("標題:時間提示");
builder.setOngoing(true);//注:在這里將builder的onGoing設置為true就實現了點擊通知欄不會消失,由於我們要實現的是計數器,就要求該通知要一直顯示在通知欄上;
再創建PendIntent對象:(在這里創建PendIntent對象的話就能夠點擊通知欄跳轉到制定的activity)
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
然后將builder設置到notificationManager里
builder.setContentIntent(pendingIntent); notificationManager.notify(serviceId,builder.build());
這樣,整個的Notification部分就完成了。然而我們要實現的是計時器,計時的效果在哪呢?
我把它放在一個service里面了,通過一個線程實現計時效果。
下面是實現整個效果的service:
public class NotificationService extends Service {
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private int totalSecond;
private final int serviceId = 0X3;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.wzzq_logo)
.setContentTitle("標題:時間提示");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setOngoing(true);
builder.setContentIntent(pendingIntent);
notificationManager.notify(serviceId,builder.build());
startForeground(serviceId,builder.build());
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i<Integer.MAX_VALUE;i++){
totalSecond = PreferencesUtils.getInt(PatrolTimeNotificationService.this, AppConfig.WZZQ_PATROL_SECONDS, 0);//這里是我從項目里面拿到一個時間進行更新
if(i > totalSecond + 1){
return;
// notificationManager.cancel(0x3);
}else{
builder.setContentText(getStringTime(totalSecond));
notificationManager.notify(serviceId,builder.build());
}
try {
Thread.sleep(1000);//一秒鍾更新一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notificationManager.notify(serviceId,builder.build());
startForeground(serviceId,builder.build());
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
//這個方法是把int類型的數據轉換成時間格式
private String getStringTime(int cnt) {
int hour = cnt / 3600;
int min = cnt % 3600 / 60;
int second = cnt % 60;
return String.format(Locale.CHINA, "%02d:%02d:%02d", hour, min, second);
}
public void stopService(){
this.stopForeground(true);
}
}
最后,在需要用到的地方將service進行啟動就好了
NotificationService notificationService = new NotificationService();
Intent intent = new Intent(mContext,notificationService.getClass());
startService(intent);
這樣就實現了在通知欄顯示計時器的功能
別忘了 在manifest文件里面注冊這個service。
