"Android" secret how to use service and thread manufacturing Android background notification bar push

Source: Internet
Author: User

Android device background notification bar Push is very annoying, mainly can use the service function of Android, after the app is clicked Home button or return key, still can in the mount background run. Anyway, the home key or the return key can only kill activity and not end the service, unlike the Windows point off key is closed program Interface + program thread by default.

The significance of this article is equivalent to making a thread in Windows, or rewriting the closing key of a Windows application, so that its application is closed only by hiding the interface and not killing the process.

Theoretically, as long as the service is not recycled by the Android system due to insufficient memory, it will continue until the device restarts, or the app's conscience point, providing a function to turn off the service.

The service is typically implemented with the Android threading mechanism, and here's a small example to illustrate the problem:


, this app starts, then turns on two processes, one is every 2 seconds the system has a toast display the current time, one is every 10 seconds to push a message in the notification bar.

This app is really rogue, you can completely change the display time to a section of Java from the remote access to the data code, the details see "Java" read the contents of the Web page (click the Open link), to the next garbage application, the file into the mobile phone memory, waiting for the end of the thread and push to the user with the notification bar, really is hehe. It is said that the user's traffic is so uproar.

However, the app also provides a button to stop the service, terminating both threads. The production process is as follows:

1, res\values\strings.xml character file, mainly the font of two buttons, not the key:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <string    name= "App_name" > Push with service and thread implementation </string>    <string name= "action_settings" >Settings</string>    <string name= "Button1" > Start service </string>    <string name= "Button2" > End of Service </string></resources>

2, after the Res\layout\activity_main.xml put the two buttons, top-down vertical linear layout, the horizontal two matching the parent layout, the vertical content of the button assigned to the corresponding ID.

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent "    android:orientation=" vertical ">    <button        Android:id= "@+id/button1"        android:layout_width= "match_parent"        android:layout_height= "Wrap_content"        android:text= "@string/button1"/>    <button        android:id= "@+id/button2"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "@string/button2"/></ Linearlayout>

3, after the formal start of our push thread production, under the SRC folder Project package here is COM. Servicedemo Create a new Timeservice.java that inherits the Android.app.Service class, such as:


Then, after pressing alt+shift+s in the blank position and then pressing V, the Onstartcommand () method under the service is rewritten and the OnDestroy () method, which can be used by any app, respectively, Use intent to specify that the StartService () method Timeservice.java for this service is triggered by StopService ().

This is known as the "Android Service life cycle": Context.startservice ()->oncreate ()->onstart ()->service running-> Context.stopservice ()->ondestroy ()->service stop. which
If the service is not running, then Android calls OnCreate () and then calls OnStart ();
If the service is already running, only OnStart () is called, so a service's OnStart method may be called repeatedly.


After getting the Onstartcommand () method and the OnDestroy () method from the parent method, do not rush to implement, with "Android" multiple activity between the use of Bundle transfer value (click Open link), the new interface activity, To first go to androidmanifest.xml registration, the new service services here, the same to Androidmanifest.xml to register the Timeservice. The code for Androidmanifest.xml is modified as follows, that is, add a line:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.servicedemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk        android:minsdkversion= "8" android:targetsdkversion= "/>" <application android:allowbackup= "true"  android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= "com.servicedemo.MainActivity" android:label= "@string/app_nam                E "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </a ctivity> <service android:name= "Com.servicedemo.TimeService" ></service><!-- Register Timeservice This service--</application></maNifest> 
4. Next, we will implement the Onstartcommand () method and the OnDestroy () method in Timeservice.

The knowledge of the "Android progress bar and message processing between threads" (Click to open link) is used here.

The shilling thread run identity Flag--isrun is true. Open two threads.

A toast is used to display the current time, here, because the toast is in the thread of the message processor, so even in the service, you can directly use the Getapplicationcontext () to get the entire Android device context. No need to engage a looper helper, this thread runs every 2 seconds until Isrun is false, and a friend who is unfamiliar with Java threads can refer to "Java" timers, threads and anonymous internal classes (click to open link) and "Java" thread concurrency, mutex, and synchronization (Click to open the link), here can not use the timer to engage, or toast will be wrong.

The other thread is the knowledge that "Android" uses notification to manipulate the device's notification bar (click the Open link) to push messages to the notification bar every 10 seconds.

Define the thread in Onstartcommand () and start, and in OnDestroy () just turn the class global variable Isrun to false, so that the two threads will die in a natural way.

The final Timeservice.java code is as follows:

Package Com.servicedemo;import Android.app.notification;import Android.app.notificationmanager;import Android.app.pendingintent;import Android.app.service;import Android.content.intent;import Android.os.Handler; Import Android.os.ibinder;import android.os.message;import android.text.format.time;import android.widget.Toast; public class Timeservice extends Service {Private Boolean isrun;//thread continues the flag private Handler handler1;//Displays the current time thread message handler. Private Handler handler2;//The thread message handler for the push notification bar message. private int notificationcounter;//A counter for calculating the number of notifications. @Overridepublic ibinder onbind (Intent arg0) {//TODO auto-generated method Stubreturn null;} @Overridepublic void OnDestroy () {Super.ondestroy (); isrun = false;} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {isrun = true;final Notificationmanager Notifica Tionmanager = (Notificationmanager) getsystemservice (notification_service);//Register Notification Manager new Thread (new Runnable () {@ override//in runnable, if you want to keep the thread running, you must define the while structure yourself//if the run () method is finished, the entireThread natural Death public void run () {//define a thread abort flag while (Isrun) {try {thread.sleep);//Java threads must be dormant in the try-catch structure, every 2s seconds. } catch (Interruptedexception e) {e.printstacktrace ();} if (!isrun) {break;} Message msg = new Message (); In Android, do not direct the actual method in the thread, so that the app easily crashes, what to do, and throw it into the message processor implementation. Handler1.sendmessage (msg);}}). Start ();///The default thread does not start, must own start ()//constantly in the receiving thread of the message, according to the message parameters, processing, here is not passed the parameter handler1 = new Handler (new Handler.callback () {// So write, don't pop any leaks warning @overridepublic boolean handlemessage (Message msg) {///Android Display the current time method of the present times = new (); Time.settonow ( ); String currenttime = Time.format ("%y-%m-%d%h:%m:%s"); Toast.maketext (Getapplicationcontext (), "Current time:" + currenttime, Toast.length_short). Show (); return false;}); New Thread (new Runnable () {@Override///In Runnable, if you want the thread to run on its own, you must define the while structure yourself//if the run () method is finished, the entire thread will die naturally public void Run () {//defines a thread abort flag while (Isrun) {try {thread.sleep (10000);//Java threads Hibernate, must be in the Try-catch structure} catch (interruptedexception e) {e.printstacktrace ();} if (!isrun) {break;} Message msg = newMessage (); Handler2.sendmessage (msg);}}). Start ();//The default thread does not start, it must own start () Handler2 = new Handler (new Handler.callback () {//So write, do not eject any warning of leaks @suppresswarnings (" Deprecation ") @Override//Here notification.setlatesteventinfo,//set notification header and content will be obsolete by Eclipse flag,//But new method, The use of builder to set up notifications can only be applied to devices above android3.0, which is not available for android2.2 devices. In the current domestic part of the equipment or in the case of android2.2, or the almost compatible with all versions of Android "outdated" Method! public boolean handlemessage (Message msg) {notificationcounter++;//counter +1notification notification = new notification () ; Notification.icon = r.drawable.ic_launcher;//Set notification icon for app icon Notification.flags = notification.flag_auto_cancel;// Notification automatically disappears after you click the notification to open the referral program Notification.tickertext = "Show notification";//The text displayed in the title bar before the user does not pull the title bar Notification.when = System.currenttimemillis ();//Set send time Notification.defaults = notification.default_all;//settings Use default sound, vibrate, flash// The following three lines: In any environment of the Android device, if the click Message opens mainactivityintent intent = new Intent (Getapplicationcontext (), mainactivity.class); Pendingintent pendingintent = pendingintent.getactivity (Getapplicationcontext (), 0,intent, 0); Notification.setlatesteventinfo (Getapplicationcontext (), "Message title", "Message content," "+ Notificationcounter +" bar Notification ", pendingintent); notificationmanager.notify (notificationcounter,notification);//require the Notification Manager to send this notification, Where the first parameter is notification on the system Idreturn false;}}); Return start_sticky;//This returned value is not actually an egg, besides Start_not_sticky and Start_redeliver_intent}}

5, after the mainactivity is very simple, two button click event, a start service, another end service, in order to prevent the start of multiple services, click the end of a button to disable, open another button.

Package Com.servicedemo;import Android.os.bundle;import Android.view.view;import Android.view.View.OnClickListener ; Import Android.widget.button;import Android.app.activity;import Android.content.intent;public class MainActivity Extends Activity {private button button1;private button button2; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//Register Component button1= ( button) Findviewbyid (R.id.button1), button2= (Button) Findviewbyid (r.id.button2);//The program starts to open the service, Disable the Start button StartService (new Intent (Mainactivity.this,timeservice.class)); button1.setenabled (false);// Click event for two buttons Button1.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {StartService (new Intent (Mainactivity.this,timeservice.class)); button1.setenabled (false); button2.setenabled (True);}}); Button2.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {StopService (New Intent ( Mainactivity.this,timeservice.class));Button1.setenabled (True); button2.setenabled (false);}});}} 


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" secret how to use service and thread manufacturing Android background notification bar push

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.