2012-03-04 107 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