the required knowledge points: Notification, Service
Third party Open source framework: Android-async-http-master
the source of the push:Android projects, sometimes there is a need: customers every time, just like the server sends a request to get some important, real-time updated messages. such as the version update, whether the request is re-downloaded, etc.
The key point is: How do you keep your app's implementation running in the background and send a request to the server every time?
First, in the activity, through the StartService () to start the service
public void open (view view) {
Intent Intent = new Intent (this, pushsmsservice.class);//Jump page
StartService (Intent);//Start service
}
Second, Customize a service class, to inherit Android service class
/*******************************************************/ //SMS Push service class, in the background for a long run, each time to send a request to the server /*******************************************************/Public class Pushsmsservice extends Service {Private MyThread MyThread;//ThreadPrivate Notificationmanager Manager;//notificationmanagerPrivate Notification Notification;//notificationPrivate Pendingintent pi;//intentPrivate Asynchttpclient client;//Asynchronous HTTP clientPrivate Boolean flag = true;//Flag bit is true@Override public IBinder onbind (Intent Intent) {return null; }/****************************************< loading page >******************************************/@Override public void OnCreate () {System.out.println ("onCreate ()"); This.client = new Asynchttpclient (); This.mythread = new MyThread (); This.myThread.start ();//Start threadSuper.oncreate (); }//Destroy pagepublic void OnDestroy () {This.flag = false;//Flag bit: falseSuper.ondestroy (); }/****************************************< Notification >******************************************/ private void notification (string content, string number, string date) {manager = (Notificationmanager) getsystem Service (Context.notification_service);//Get Notification Manager for the systemnotification = new notification (r.drawable.ic_menu_compose, content, System.currenttimemillis ());//Get icons, content, time, etc.Notification.defaults = Notification.default_all;//Use default settings (such as ringtones, vibrations, flashing lights)Notification.flags = Notification.flag_auto_cancel;//The message automatically disappears in the notification bar after the user taps the messageNotification.flags |= notification.flag_no_clear;//Click Delete on the notification bar, the message will not still be deletedIntent Intent = new Intent (Getapplicationcontext (), contentactivity.class);//Jump pageIntent.putextra ("content", content);//Package ContentsIntent.putextra ("number", number);//Package numberIntent.putextra ("date", date);//Package TimePi = pendingintent.getactivity (Getapplicationcontext (), 0, intent, 0); Notification.setlatesteventinfo (Getapplicationcontext (), number + "Send SMS", content, pi); Manager.notify (0, notification);//Push messages to the status bar/****************************************< thread >******************************************/Private class MyThread extends Thread {public void run () {String URL = "Http://110.65.99.66:8 080/jerry/pushsmsservlet ";//Locate serverwhile (flag) {//Check and judge the flag bitSYSTEM.OUT.PRINTLN ("Send Request"); try {thread.sleep (10000);//Each 10 second sends a request to the server} catch (Interruptedexception e) {e.printstacktrace (); }//Send a request to the server by a Get methodClient.get (URL, new Asynchttpresponsehandler () {public void onsuccess (int statusCode, header[] Head ERs, byte[] responsebody) {try {jsonobject result = new Jsonobjec T (new String (Responsebody, "utf-8")); int state = Result.getint ("state");//Assuming an even number is an unread message if (state% 2 = = 0) { String content = result.getstring ("content"); Stri ng date = result.getstring ("date"); Stri ng number = result.getstring ("number"); Noti Fication (content, number, date); } &NB Sp } catch (Exception e) {   e.printstacktrace (); } &nbs P } &NBSP;PUBL IC void onfailure (int statusCode, header[] headers, byte[] responsebody, throwable error) {   ; Toast.maketext (Getapplicationcontext (), "Data request Failed", 0) .show (); } }); }
Iii. Registration in the manifest file3.1 Service registration:
<service android:name= ". Pushsmsservice "></service>
Iv. Permissions Configuration Issues4.1 You need to configure permissions because the notification information uses the vibrate function and network access of the phone. <uses-permission android:name= "Android.permission.VIBRATE"/> <!-vibration rights <uses-permission android:name= "Android.permission.INTERNET"/><!-Network Permissions
v. Redefining activity(for users to click on a message in the drop-down notification bar, jump to the detailed message interface) public class Contentactivity extends Activity { PROTECTE d void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstance State); Setcontentview (r.layout.activity_content); Intent Intent = Getintent (); TextView tv_content = (TextView) This.findviewbyid (r.id.tv_content); TextView tv_number = (TextView) This.findviewbyid (R.id.tv_number); TextView tv_date = (TextView) This.findviewbyid (r.id.tv_date); if (intent! = null) { String content = i Ntent.getstringextra ("content"); String number = Intent.getstringextRA ("number"); String date = Intent.getstringextra ("date"); Tv_content.settext ("contents:" + content); Tv_number.settext ("No.:" + number); Tv_date.settext ("Date:" + date); } } 5.1registering a new activity in the manifest file <activity android:name= ". Contentactivity "></activity> 5.2 Note that the above code is required to support the server, we go to create a simple server, add a servlet and an entity class can be Public Class Pushsmsservlet extends HttpServlet { private static int index = 1; public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexce ption {System.out.println (index);//list<sms> smslist = new arraylist<sms> ();SMS SMS = new SMS (Index, "jerk" + Index, "2016-08-08", "15208432222"); index++;//Smslist.add (SMS); //SMS = new SMS (0, "dumb", "2016-08-08", "15208432222"); //Smslist.add (SMS); //SMS = new SMS (1, "dumb", "2016-08-08", "13522224444"); //Smslist.add (SMS);Response.setcontenttype ("text/html"); Request.setcharacterencoding ("UTF-8"); Response.setcharacterencoding ("Utf-8"); PrintWriter out = Response.getwriter (); Gson Gson = new Gson ();//Convert data from SMS class to JSON data formatString JSON = Gson.tojson (SMS); Out.write (JSON); Out.flush (); Out.close (); }//dopostpublic void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, response); } the/****************************************< defines the class that encapsulates the message to hold >******************************************/ Public class Sms { private int state; Private String content; Private String date; private String number; Public Sms (int state, string content, string date, string number) {super (); This.state = State; this.content = content; This.date = date; This.number = number; } }This is just the core code, the rest of the please expand yourself!
Android Development--push