2012-03-04 106 views
1

我創建了一個擴展Service類的BackgroundService類。Android狀態通知

我有一個計時器,用來跟蹤檢查之間的持續時間。在onCreate方法中,我將其設置爲10秒,所以我期望的行爲是每10秒發送一次狀態通知消息。我遇到的問題是,每隔10秒鐘,當我啓用狀態通知時,我會聽到狀態通知「聲音」,但我沒有在屏幕頂部看到文本提示,它只出現在第一次通知服務警報中。有誰知道如何解決這一問題?

我附上了很多這個類的源代碼:謝謝!

定時器定時器;

private TimerTask updateTask = new TimerTask() { 
    @Override 
    public void run() { 
     Log.i(TAG, "Timer task doing work!"); 

     // Process junk here: 
     sendNotification("Please leave in 5 min!!!"); 
    } 
}; 

@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    return super.onStartCommand(intent, flags, startId); 
} 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    Log.i(TAG, "Background Service creating"); 

    timer = new Timer("DurationTimer"); 
    timer.schedule(updateTask, 1000L, 10*1000L); 
} 

public void sendNotification(CharSequence message) 
{ 
    // Execute Check and Notify 
    String ns = Context.NOTIFICATION_SERVICE; 
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
    int icon = R.drawable.simon; 
    CharSequence tickerText = message; 
    long when = System.currentTimeMillis(); 
    Notification notification = new Notification(icon, tickerText, when); 
    Context context = getApplicationContext(); 
    CharSequence contentTitle = "LEAVE NOW!"; 
    CharSequence contentText = "LEAVE NOW!!"; 
    Intent notificationIntent = new Intent(this, BackgroundService.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
    notification.defaults |= Notification.DEFAULT_SOUND; 
    //notification.defaults |= Notification.DEFAULT_VIBRATE; 

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
    int HELLO_ID = 1; 
    mNotificationManager.notify(HELLO_ID, notification); 
} 
+0

凱恩你告訴我你在哪裏添加了接受的代碼? – user3233280 2015-01-03 14:31:53

回答

0

每次迭代更改contentText的值。

例子:

CharSequence contentText = "LEAVE NOW!! " + System.currentTimeMillis(); 

我想你會發現,在消息文本在不斷的變化,因爲你已經有一個具有相同ID,你要發送的通知的通知。所以會發生什麼是文本只是改變。

另一種方式:

mNotificationManager.clear(HELLO_ID); 

做,你創建新的通知之前。

+0

我嘗試通過單獨使用System.currentTimeMillis()更改contentText,contentTitle和HELLO_ID值,但它沒有解決第二次未顯示通知文本的問題。你知道任何可能導致這種情況的事嗎?謝謝。 – Garrett 2012-03-04 11:52:31

+0

新的部分已添加到答案正文。 – Knossos 2012-03-04 12:10:49

+0

我使用了mNotificationManager.cancel(HELLO_ID),它工作。謝謝! – Garrett 2012-03-04 22:15:37