Android Top Bar Push Message Timely

  • 2021-06-29 12:09:18
  • OfStack

When using an Android device, it is often applied to pop-up push messages.Here I share the push code I wrote before with you for your reference. Friends with different opinions are welcome to make suggestions and make progress together!

More friends have searched to see this recently.This is also a separate built-in push.Push from time to time associates with servers We can use SDK cloud push to meet our needs.Related introductory content.Move down!

First XML


<!--  Android Push Service  -->
<service android:name=".MessageService"
android:enabled="true"
android:exported="true"
android:label="PushService"
android:launchMode="singleInstance"
android:persistent="true"
android:process=":push" >
<intent-filter>
<action android:name="com.xxxx.action.MY_SERVICE" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
<receiver
android:name="com.tt.xxxxx.download.GTAlarmReceiver"
android:permission="com.android.launcher.permission.INSTALL_SHORTCUT"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.android.launcher.action.INSTALL_SHORTCUT" />
</intent-filter>
</receiver>
<!--end add-->

Inside.:.These symbols are pitiful.If you don't understand it, check the field property description.

Push Class:


/********************************  class  *************************************/
package com.ttad.yxcb;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import com.tt.yingxiongchibis.download.GTDownloaderActivity;
public class MessageService extends Service {
// Get message thread 
private MessageThread messageThread = null;
// Click to view 
private Intent messageIntent = null;
private PendingIntent messagePendingIntent = null;
// Notification bar message 
private int messageNotificationID = 1000;
private Notification messageNotification = null;
private NotificationManager messageNotificatioManager = null;
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
// Initialization 
messageNotification = new Notification();
messageNotification.icon = R.drawable.app_icon_ucs;
messageNotification.tickerText = "알림";
messageNotification.defaults = Notification.DEFAULT_SOUND;
messageNotificatioManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// Click Jump activity
messageIntent = new Intent(this, GTDownloaderActivity.class);
messagePendingIntent = PendingIntent.getActivity(this,0,messageIntent,0);
// Open Thread 
messageThread = new MessageThread();
messageThread.isRunning = true;
messageThread.start();
//Toast.makeText(MessageService.this, "", Toast.LENGTH_LONG).show();
super.onCreate();
}
/**
*  Get messages from the server side 
*
*/
class MessageThread extends Thread{
// Running state, down 1 Steps are useful 
public boolean isRunning = true;
public void run() {
while(isRunning){
try {
// Rest? 10 Minute 
Thread.sleep(1000);
// Get server messages 
String serverMessage = getServerMessage();
if(serverMessage!=null&&!"".equals(serverMessage)){
// Update Notification Bar 
messageNotification.setLatestEventInfo(MessageService.this,"알림",serverMessage,messagePendingIntent);
messageNotificatioManager.notify(messageNotificationID, messageNotification);
// After each notification, notify ID Incremental 1 Next, avoid message overwriting 
messageNotificationID++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onDestroy() {
// System.exit(0);
// Or, 2 choose 1 , recommended System.exit(0) So that the process exits cleaner 
messageThread.isRunning = false;
//super.onDestroy();
}
/**
*  Server in this way Demo For example only 
* @return  Returns the message to be pushed by the server, otherwise it will not be pushed if it is empty 
*/
public String getServerMessage(){
SimpleDateFormat sdf=new SimpleDateFormat("HHmmss");
String date=sdf.format(new java.util.Date());
String in = date;
if(date.equals("195500"))
{
String str = "잠시후 전쟁터 시작됩니다. 준비해주세요.";
return str;
}
else if(date.equals("212500"))
{
String str = "잠시후 보스전 시작됩니다. 준비해주세요.";
return str;
}
else
{
return "";
}
}
}

Finally, invoke:


// Push 
Intent intent = new Intent();
//  Set up Action attribute 
intent.setAction("com.ttad.yxcb.action.MY_SERVICE");
//  Start the Service
startService(intent);
// startService(new Intent(ExTextActivity.this, MessageService.class));

Android Message Push Knowledge Supplement:

1. Introduction

The so-called message push is to send a connection from the server to the mobile device, transmitting a certain amount of information.For example, some news clients receive one or more notifications every once in a while, which is push messages from the server side.Also, some commonly used IM software, such as WeChat and GTalk, have server push capabilities.

The push method is as follows:

1) Communicate between server and client through SMS.

On the Android platform, you can achieve full real-time operation by intercepting SMS messages and parsing the message content to understand the intent of the server.The problem is that this scheme is relatively expensive and dependent on the operator.

2) Cyclic active timing acquisition

This method requires the client to make a regular or periodic access to the server-side interface to get the latest messages.Polling too slowly can cause delays in some messages, and too fast can consume a lot of network bandwidth and batteries.

3) Persistent connection

This solution solves the performance problems caused by polling, but still consumes the battery of the mobile phone.We need to start a service to maintain a long-lasting connection to the server (as is the case with Apple and Google's C2DM).However, for Android systems, when the system has low available resources, the system will force us to shut down our services or applications, in which case the connection will be forcibly interrupted. (Apple's push service works well because only one connection to the server is maintained per phone, and in fact C2DM works the same way.That is, all push services are done through a proxy server, in which case you only need to maintain a persistent connection with one server.C2DM=Cloud to Device Messaging).

Compared with the third, it is the most feasible.Write system services or start-up functions for software;Or, if system resources are low, you can restart the service in the onDestroy () method after the service is shut down, thereby enabling a way to make a persistent connection.

C2DM is built into Android's 2.2 system and is not compatible with older 1.6 to 2.1 systems.It also relies on the C2DM server provided by Google, which is often unavailable due to the domestic network environment.

The XMPP protocol, which is based on the TCP protocol, not only provides the capability of this persistent connection, enables duplex communication between server and client, but also provides a better solution without relying on system version and google server limitations.

2. XMPP Protocol

The full name of XMPP is Extensible Messaging and Presence Protocol, formerly the Jabber project, which is an open instant messaging protocol based on XML.XMPP has been contacted by netizens for its application by Google Talk and NetEasy Bubble.The key features of XMPP are a distributed instant messaging system and the use of XML streaming.XMPP is currently standardized by the IETF International Standards Organization.

Android push notification (androidpn) is an open source implementation of java based on the XMPP protocol, which contains the complete client and server side.The server side is basically modified on the basis of another open source project, openfire.

androidpn clients need to use an java-based open source XMPP protocol package asmack, which is also based on another open source project smack under openfire, but we do not need to compile it ourselves, we can use asmack.jar directly from the androidpn client.Clients make use of the XMPPConnection class provided in asmack to establish a persistent connection with the server through which they can register and authenticate users, as well as receive notifications from the server.

The androidpn server side is also implemented in java language, based on the openfire open source project, but its Web part uses the spring framework, which is different from openfire.The Androidpn server consists of two parts, one listens for the XMPP service on port 5222 and is responsible for communicating with the client's XMPPConnection class, which functions as user registration and authentication, and sends push notification messages.The other part is the Web server, which uses a lightweight HTTP server to receive users'Web requests.These two ways of servers make sense: when the corresponding TCP port is enclosed by a firewall, it can be accessed by polling, and thus helps to pass through the firewall.


Related articles: