0

我在通知/状态栏中使用秒表。

  • contentText 我得到秒表getFormattedElapsedTime()。它工作但在我关闭应用程序时停止。即使应用程序关闭,我该如何工作?

    private NotificationManager m_notificationMgr;
    private Notification m_notification;
       // Timer to update the ongoing notification
     private final long mFrequency = 100;    // milliseconds
        private final int TICK_WHAT = 2; 
        private Handler mHandler = new Handler() {
            public void handleMessage(Message m) {
                updateNotification();
                sendMessageDelayed(Message.obtain(this, TICK_WHAT), mFrequency);
            }
        };
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "created");
    
            m_stopwatch = new Stopwatch();
            m_notificationMgr = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    
            createNotification();
        }
    
    
    public void createNotification() {
            Log.d(TAG, "creating notification");
    
    
            int icon = R.drawable.icon;
            CharSequence tickerText = "Meb";
            long when = System.currentTimeMillis();
    
            m_notification = new Notification(icon, tickerText, when);
            m_notification.flags |= Notification.FLAG_ONGOING_EVENT;
            m_notification.flags |= Notification.FLAG_NO_CLEAR;
        }
    
        public void updateNotification() {
            // Log.d(TAG, "updating notification");
    
            Context context = getApplicationContext();
            CharSequence contentTitle = "Mebr";
            CharSequence contentText = getFormattedElapsedTime();
    
            Intent notificationIntent = new Intent(this, TimerFragmentActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    
            // the next two lines initialize the Notification, using the configurations above
            m_notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
            m_notificationMgr.notify(NOTIFICATION_ID, m_notification);
        }
    
        public void showNotification() {
            Log.d(TAG, "showing notification");
    
            updateNotification();       
            mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), mFrequency);
        }
    
        public void hideNotification() {
            Log.d(TAG, "removing notification");
    
            m_notificationMgr.cancel(NOTIFICATION_ID);
            mHandler.removeMessages(TICK_WHAT);
        }
    
4

1 回答 1

0

您需要从Service更新您的通知,即使在活动暂停或停止后也可以继续运行。

于 2013-05-28T04:26:32.623 回答