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的独立进程--> < service android:name=".service.MessageService" android:label="消息推送" android:process=".message" /> <!--或者--> <!--下面会创建一个应用私有的com.cnblogs.tianxia:message的独立进程--> < service android: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 |
public
class
MessageService
extends
Service {
//获取消息线程
private
MessageThread messageThread =
null
;
//点击查看
private
Intent messageIntent =
null
;
private
PendingIntent messagePendingIntent =
null
;
//通知栏消息
private
int
messageNotificationID =
1000
;
private
Notification messageNotification =
null
;
private
NotificationManager messageNotificatioManager =
null
;
public
IBinder onBind(Intent intent) {
return
null
;
}
@Override
public int
onStartCommand(Intent intent,
int
flags,
int
startId) {
//初始化
messageNotification =
new
Notification();
messageNotification.icon = R.drawable.icon;
messageNotification.tickerText =
"新消息"
;
messageNotification.defaults = Notification.DEFAULT_SOUND;
messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
messageIntent =
new
Intent(
this
, MessageActivity.
class
);
messagePendingIntent = PendingIntent.getActivity(
this
,
0
,messageIntent,
0
);
//开启线程
messageThread =
new
MessageThread();
messageThread.isRunning =
true
;
messageThread.start();
return
super
.onStartCommand(intent, flags, startId);
}
/**
* 从服务器端获取消息
*
*/
class MessageThread
extends
Thread{
//运行状态,下一步骤有大用
public
boolean
isRunning =
true
;
public
void 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 返回服务器要推送的消息,否则如果为空的话,不推送
*/
public
String getServerMessage(){
return
"YES!"
;
}
}
|
Where messageactivity is the activity that clicks Jump, is responsible for processing view details.
We call it in other activity:
12345 |
boolean isMessagePush = true ; //不开启就设置为false; ... if (isMessagePush){ startService( new Intent( this , MessageService. class )) }; |
Run it:
4. Stop the Service
12 |
stopService( new Intent(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