android2.3 api demo 学习系列(22)--App/Notification/Notifying Service Controller

因为还没有看到service的demo,这里先不对service做过多的介绍,本demo的主要意图是通过service发送notification

1、在service的onCreate方法中启动新的线程来发送notification

@Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.
        Thread notifyingThread = new Thread(null, mTask, "NotifyingService");
        mCondition = new ConditionVariable(false);
        notifyingThread.start();
    }

 2、具体执行

private Runnable mTask = new Runnable() {
        public void run() {
            for (int i = 0; i < 4; ++i) {
                showNotification(R.drawable.list,
                        R.string.app_notification_service_happy);
                if (mCondition.block(5 * 1000)) 
                    break;
                showNotification(R.drawable.launcher,
                        R.string.app_notification_service_sad);
                if (mCondition.block(5 * 1000)) 
                    break;
            }
            // Done with our work...  stop the service!
            NotifyingService.this.stopSelf();
        }
    };

 3、notification的实例化和发送

private void showNotification(int moodId, int textId) {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(textId);

        // Set the icon, scrolling text and timestamp.
        // Note that in this example, we pass null for tickerText.  We update the icon enough that
        // it is distracting to show the ticker text every time it changes.  We strongly suggest
        // that you do this as well.  (Think of of the "New hardware found" or "Network connection
        // changed" messages that always pop up)
        Notification notification = new Notification(moodId, getText(R.string.app_notification_service_title), System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NotifyingController.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.app_notification_service_title),
                       text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(MOOD_NOTIFICATIONS, notification);
    }

 里面涉及到的notification的内容基本在上一篇文章都有详细的介绍:android2.3 api demo 学习系列(21)--App/Notification/Incoming Message

效果图:


android2.3 api demo 学习系列(22)--App/Notification/Notifying Service Controller

你可能感兴趣的:(android,service,notification,notify,APIDemo)