A demo example of a service in Android

Source: Internet
Author: User

A demo example of a service in Android
Service components are an important part of the Android system, it's easy to read the code on the Web, but you need to be coding to be familiar with it.
This article, the main paste code, do not explain too much service.
The code is looking for an example from the Internet, copy down found that the code is not exactly correct, slightly modified the next.
Androidmanifest.xml
<application        android:icon= "@drawable/ic_launcher"        android:label= "@string/app_name" >        < Activity            android:label= "@string/app_name"            android:name= ". Service. Servicemainactivity ">            <intent-filter >                <action android:name=" Android.intent.action.MAIN "/ >                <category android:name= "Android.intent.category.LAUNCHER"/>            </intent-filter>        </ Activity>         <!--registration Service-          <service android:name= "LocalService" >              < intent-filter>                  <action android:name= "Cn.fansunion.service.LocalService"/>              </intent-filter >          </service>      </application>



Servicemainactivity.java
Package Cn.fansunion.service;import Cn.fansunion.r;import Android.app.activity;import android.app.Service;import Android.content.componentname;import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public Class Servicemainactivity extends Activity {private button startbtn;private button stopbtn;private button bindbtn;private Button unbindbtn;private static final String TAG = "mainactivity";p rivate LocalService myservice; @Overridepublic void OnC Reate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.service); startBtn = ( button) Findviewbyid (r.id.start), stopbtn = (button) Findviewbyid (r.id.stop), bindbtn = (button) Findviewbyid (r.id.bind ); unbindbtn = (Button) Findviewbyid (r.id.unbind); Startbtn.setonclicklistener (new Myonclicklistener ()); StopBTn.setonclicklistener (New Myonclicklistener ()); Bindbtn.setonclicklistener (new Myonclicklistener ()); Unbindbtn.setonclicklistener (New Myonclicklistener ());} Class Myonclicklistener implements Onclicklistener {@Overridepublic void OnClick (View v) {Intent Intent = new Intent (); int Ent.setclass (Servicemainactivity.this, localservice.class); switch (V.getid ()) {case r.id.start:// Start Servicestartservice (intent); Toast ("StartService"); Break;case r.id.stop://Stop Servicestopservice (intent); Toast (" StopService ") Break;case r.id.bind://binding servicebindservice (Intent, Conn, service.bind_auto_create); Toast (" Bindservice "); Break;case r.id.unbind://lift Serviceunbindservice (conn); Toast (" Unbindservice "); break;}}            private void Toast (final String tip) {runonuithread (new Runnable () {@Override public void run () {                                     Toast.maketext (Getapplicationcontext (), Tip, Toast.length_short). Show (); }        });} Private Serviceconnection conn = new ServiceconnectioN () {@Overridepublic void onserviceconnected (componentname name, IBinder service) {LOG.E (TAG, "Connection succeeded");// When the service connection is established successfully, provide the client with the service to interact with the object (according to the Android Doc translation, do not know exactly ....) ) MyService = ((localservice.localbinder) service). GetService ();} @Overridepublic void onservicedisconnected (componentname name) {LOG.E (TAG, "disconnected"); myservice = null;}};}




Localservice.java
Package Cn.fansunion.service;import Android.app.service;import Android.content.intent;import android.os.Binder; Import Android.os.ibinder;import Android.util.log;import Android.widget.toast;public class LocalService extends Service {private static final String TAG = "MyService";p rivate final IBinder mybinder = new Localbinder (); @Overridepublic IBinder Onbind (Intent Intent) {log.e (TAG, "Onbind ()")//toast.maketext (This, "Onbind ()", Toast.length_short). Show (); return mybinder;} When you call the StartService method or the Bindservice method when you create the service (the current service is not created) call the method @overridepublic void OnCreate () {LOG.E (TAG, " OnCreate () ");//toast.maketext (This," onCreate () ", Toast.length_short). Show (); Call the method when the StartService method is invoked to start the service @overridepublic void OnStart (Intent Intent, int startid) {log.e (TAG, "OnStart ()");// Toast.maketext (This, "OnStart ()", Toast.length_short). Show (); After the service is created and started, call the method when the StopService method or Unbindservice method is called @overridepublic void OnDestroy () {LOG.E (TAG, "OnDestroy ()"); /toast.maketext (This, "OnDestroy ()", ToaSt. Length_short). Show ();} Provided to client access public class Localbinder extends Binder {LocalService getService () {return localservice.this;}}}


Service.xml Layout file
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " ><button android:id= "@+id/start" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "Start service"/><button android:id= "@+id/stop" android:layout_width= "Wrap_content" android:layout _height= "Wrap_content" android:text= "Stop Service"/><button android:id= "@+id/bind" android:layout_width= "Wrap_ Content "android:layout_height=" wrap_content "android:text=" bind service "/><button android:id=" @+id/unbind " Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "release service"/></ Linearlayout>



[2015-11-14 17:39:10-xp2p4android]------------------------------
[2015-11-14 17:39:10-xp2p4android] Android launch!
[2015-11-14 17:39:10-xp2p4android] adb is running normally.
[2015-11-14 17:39:10-xp2p4android] Performing cn.fansunion.service.ServiceMainActivity activity launch
[2015-11-14 17:39:10-xp2p4android] Automatic Target mode:using device ' 51bf63f2 '
[2015-11-14 17:39:10-xp2p4android] Uploading xp2p4android.apk onto device ' 51BF63F2 '
[2015-11-14 17:39:10-xp2p4android] Installing xp2p4android.apk ...
[2015-11-14 17:39:13-xp2p4android] success!
[2015-11-14 17:39:13-xp2p4android] Starting activity cn.fansunion.service.ServiceMainActivity on device 51bf63f2
[2015-11-14 17:39:13-xp2p4android] ActivityManager:Starting:Intent {act=android.intent.action.main Cat=[android.intent.category.launcher] cmp= Cn.fansunion/.service. Servicemainactivity}
[2015-11-14 17:39:13-xp2p4android] Attempting to connect debugger to ' cn.fansunion ' on port 8600


Run


The original code, the Toast dialog box is not shown.
In the CSDN forum found a post that may be blocked by mobile phone.
I think it's more likely to call the wrong way.
Call in service, toast appropriate?
public void OnCreate () {
LOG.E (TAG, "onCreate ()");
Toast.maketext (This, "onCreate ()", Toast.length_short). Show ();
}


Finally, refer to the user's method, in the UI thread, the new thread executes the toast.
private void Toast (final String tip) {
Runonuithread (New Runnable () {
@Override
public void Run () {
Toast.maketext (Getapplicationcontext (), Tip, Toast.length_short). Show ();
}
});
}
Yes, it's called in the activity.


This is fully explained, the online code again beautiful, still have to run under the hands.
The code of the post, is 2011 years, very old AH ~


Resources
An explanation of service components in Android
http://blog.csdn.net/zuolongsnail/article/details/6427037


Android toast display does not come out
http://bbs.csdn.net/topics/390889540

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

A demo example of a service in Android

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.