Android Learning Series (7)--app poll server messages

Source: Internet
Author: User

This article is an essential knowledge for Android developers.

1. Polling the server
General application, the timing notification message can use the polling method to pick up messages from the server, of course, real-time message notification, recommend the use of push services.
There is a need to pay attention to the polling frequency setting to balance demand and performance.

2. Independent processes
Regardless of whether the program is running, we have to be able to notify the customer, we need a separate process background services.
We need a back-end service for a standalone process.
When registering a service in Androidmanifest.xml, there is a android:process attribute if this property is "." Begins, a global, independent process is opened for this service, and a standalone process that is private to this application is opened for this service, starting with ":". For a specific example, we created a new application, creating the main process Com.cnblogs.tianxia, then:

12345 <!--下面会创建一个全局的com.cnblogs.tianxia.message的独立进程--><serviceandroid:name=".service.MessageService" android:label="消息推送" android:process=".message" /><!--或者--><!--下面会创建一个应用私有的com.cnblogs.tianxia:message的独立进程--><serviceandroid:name=".service.MessageService" android:label="消息推送" android:process=":message" />

We don't need to build a global, this article chooses the second scenario, creating a standalone process that is currently private to the application.

3. Notify the user and click View

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475 publicclassMessageService extendsService {    //获取消息线程    privateMessageThread messageThread = null;     //点击查看    privateIntent messageIntent = null;    privatePendingIntent messagePendingIntent = null;    //通知栏消息    privateintmessageNotificationID = 1000;    privateNotification messageNotification = null;    privateNotificationManager messageNotificatioManager = null;    publicIBinder onBind(Intent intent) {        returnnull;    }    @Override    public intonStartCommand(Intent intent, intflags, intstartId) {        //初始化        messageNotification = newNotification();        messageNotification.icon = R.drawable.icon;        messageNotification.tickerText = "新消息";        messageNotification.defaults = Notification.DEFAULT_SOUND;        messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);        messageIntent = newIntent(this, MessageActivity.class);        messagePendingIntent = PendingIntent.getActivity(this,0,messageIntent,0);        //开启线程        messageThread = newMessageThread();        messageThread.isRunning = true;        messageThread.start();        returnsuper.onStartCommand(intent, flags, startId);    }        /**     * 从服务器端获取消息     *     */    class MessageThread extendsThread{        //运行状态,下一步骤有大用        publicbooleanisRunning = true;        publicvoid run() {            while(isRunning){                try{                    //休息10分钟                    Thread.sleep(600000);                    //获取服务器消息                    String serverMessage = getServerMessage();                    if(serverMessage!=null&&!"".equals(serverMessage)){                        //更新通知栏                        messageNotification.setLatestEventInfo(MessageService.this,                            "新消息","奥巴马宣布,本拉登兄弟挂了!"+serverMessage,messagePendingIntent);                        messageNotificatioManager.notify(messageNotificationID, messageNotification);                        //每次通知完,通知ID递增一下,避免消息覆盖掉                        messageNotificationID++;                    }                catch(InterruptedException e) {                    e.printStackTrace();                }            }        }    }    /**     * 这里以此方法为服务器Demo,仅作示例     * @return 返回服务器要推送的消息,否则如果为空的话,不推送     */    publicString getServerMessage(){        return"YES!";    }}

Where messageactivity is the activity that clicks Jump, is responsible for processing view details.
We call it in other activity:

12345 booleanisMessagePush = true;//不开启就设置为false;...if(isMessagePush){     startService(newIntent(this, MessageService.class))};

Run it:

4. Stop the Service

12 stopService(newIntent(MyActivity.this,MessageService.class));setMessagePush(false);//设置配置文件或数据库中flag为false

Run, stop the service, but unexpectedly did not stop, what happened? Did you write the code wrong?
The code is not wrong, it is wrong that we stopped the service, but did not stop the process, quit the thread.

5. Exit the Thread
Practice has shown that the stop () method of thread is not reliable. But we have other ways.
In front of the code, the programmer is God.
There are two methods of exiting a thread.
The first method, force exit.

12 //杀死该线程所在的进程,自然就退出了System.exit(0);

The second method, set IsRunning to False.

12 //前面说到了isRunning这个标志,设置为false后,线程的执行就从while循环中跳出来了,然后自然结束掉了messageThread.isRunning = false;

In general, we overload the OnDestroy () method in Messageservice as follows:

1234567 @Override public  void  ondestroy () {              System.exit ( 0 &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; //or, second choice, system.exit (0) is recommended so that the process exits cleaner               // Messagethread.isrunning = false; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; super .ondestroy (); }

OK, now either manual stop or force stop service from Task Manager, both the message service and the message thread can stop and exit gracefully.

Android Learning Series (7)--app poll server messages

Android Learning Series (7)--app poll server messages

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.