Android (Notification) message push mechanism

Source: Internet
Author: User

Learn about the Android message push mechanism from online inquiry, as follows:

1. First, the layout file code activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"android:orientation= "Vertical" > <TextView android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Hello"/> <Button Android:id= "@+id/btnstart"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Notification"/> <Button Android:id= "@+id/btnstop"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Clear"/></linearlayout>

2. Then the Java main Interface code Mainactivity.java

 PackageCom.example.notificationservice;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton btnstart; PrivateButton Btnstop; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); }    Private voidInitview () {btnstart=(Button) Findviewbyid (R.id.btnstart); Btnstop=(Button) Findviewbyid (r.id.btnstop); Btnstart.setonclicklistener ( This); Btnstop.setonclicklistener ( This); } @Override Public voidOnClick (View v) {intID =V.getid (); if(id = =R.id.btnstart) {//Start ServiceIntent Intent =NewIntent (); Intent.setaction ("YMW. My_service ");        StartService (Intent); }        if(id = =r.id.btnstop) {//Close ServiceIntent Intent =NewIntent (); Intent.setaction ("YMW. My_service ");        StopService (Intent); }} @Override Public voidonbackpressed () {System.exit (0); Super. onbackpressed (); }}

3. Then the message push service file Notificationservice.java

 PackageCom.example.notificationservice;Importandroid.app.Notification;ImportAndroid.app.NotificationManager;Importandroid.app.PendingIntent;ImportAndroid.app.Service;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.os.IBinder; Public classNotificationserviceextendsService {//Get Message Thread    PrivateMessagethread Messagethread =NULL; //Click to view    PrivateIntent messageintent =NULL; PrivatePendingintent messagependingintent =NULL; //Notification Bar Messages    Private intMessagenotificationid = 1000; PrivateNotification messagenotification =NULL; PrivateNotificationmanager Messagenotificatiomanager =NULL;  Publicibinder onbind (Intent Intent) {return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {        //InitializeMessagenotification =NewNotification (); Messagenotification.icon=R.drawable.ic_launcher; Messagenotification.tickertext= "New Message"; Messagenotification.defaults=Notification.default_sound; Messagenotificatiomanager=(Notificationmanager) Getsystemservice (Context.notification_service); Messageintent=NewIntent ( This, Mainactivity.class); Messagependingintent= Pendingintent.getactivity ( This, 0, Messageintent,0); //Open ThreadMessagethread =NewMessagethread (); Messagethread.isrunning=true;        Messagethread.start (); return Super. Onstartcommand (Intent, flags, Startid); }    /*** Get messages from server side **/    classMessagethreadextendsThread {//set whether to loop push         Public BooleanIsRunning =true;  Public voidrun () {//While (isrunning) {            Try {                //time intervalThread.Sleep (1000); //Get Server MessagesString ServerMessage =Getservermessage (); if(ServerMessage! =NULL&& "". Equals (ServerMessage)) {                    //Update Notification BarMessagenotification.setlatesteventinfo (Getapplicationcontext (),"New Message", "You have a new message." "                                    +ServerMessage, messagependingintent);                    Messagenotificatiomanager.notify (Messagenotificationid, messagenotification); //the notification ID increments once each notification, to avoid overwriting the messagemessagenotificationid++; }            } Catch(interruptedexception e) {e.printstacktrace (); }            // }}} @Override Public voidOnDestroy () {//system.exit (0);Messagethread.isrunning =false; Super. OnDestroy (); }    /*** Analog Send Message * *@returnreturns the message that the server wants to push, or if it is empty, do not push*/     PublicString getservermessage () {return"News!"; }}

4. Finally, don't forget to configure the service in the Mainfeast.xml file

The project code is linked as follows:

Http://files.cnblogs.com/_ymw/NotificationService_%E5%8D%9A%E5%AE%A2%E9%99%84%E4%BB%B6.rar

Android (Notification) message push mechanism

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.