Introduction to ANDROID Development Service usage Analysis _android

Source: Internet
Author: User
Tags sqlite database

This example describes the usage of service in Android. Share to everyone for your reference, specific as follows:

About the service on the internet has been a lot of, here is about their own through the code to write the service of a little experience and a combination of other people to the service of a summary

Service can be understood as an invisible activity but it is different from the activity, first the service is no interface, the user can not see the interactive component level is similar to the activity is

The service defines a series of methods that are related to their own declaration cycle:

onbind (...) is a method that must be implemented to return a binding interface to the service
onCreate (); Called by system when service is first created
OnStart (...) Called when the service is started through the StartService () method call
OnDestroy (); The system calls this method when the service is no longer in use ....

This code has Mainactivity,java,myservice.java main.xml these several important documents below through these documents to the service to understand see note

The old rules start with the layout, and it's simple, just a few button

<?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 "
 > <textview android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "service test" android:gravity= "Center_horizontal"/> <button android:id= "@+id/startbutton" android:layout_width= Parent "android:layout_height=" wrap_content "android:text=" Start Service "/> <button android:id=" @+id/ Stopbutton "android:layout_width=" fill_parent "android:layout_height=" wrap_content "" Stop Service "/ > <button android:id= "@+id/bindbutton" android:layout_width= fill_parent "android:layout_height=" Wrap_ Content "android:text=" Bind Service "/> <button android:id=" @+id/unbindbutton "android:layout_width=" Fill_ Parent "android:layout_height=" wrap_content "android:text=" Unbind Service "/> </linearlayout>

 

Layout Effect Chart:

Start service file, MyService inheritance

 public class MyService extends Service {final static String TAG = "MyService";
  @Override public IBinder onbind (Intent Intent) {log.i (TAG, "onbind () ...");
  Showinfo ("Onbind () ...");
 return null;
   The//Setvice is invoked @Override public void OnCreate () {log.i () (TAG, OnCreate () ...) when it is created.
  Showinfo ("OnCreate () ...");
 Super.oncreate (); @Override public void OnStart (Intent Intent, int startid) {log.i (TAG, OnStart) is invoked when the customer invokes StartService () to start the service (
  )........");
  Showinfo ("OnStart () ...");
 Super.onstart (Intent, Startid);
  @Override public void OnDestroy () {log.i (TAG, OnDestroy () ...);
  Showinfo ("OnDestroy () ...");
 Super.ondestroy ();
  @Override public boolean onunbind (Intent Intent) {log.i (TAG, Onunbind () ...);
  Showinfo ("Onunbind () ...");
 return Super.onunbind (Intent);
 public void Showinfo (String str) {toast.maketext (this, str, toast.length_short). Show (); }
}

The above is mainly the service of several cycle functions this myservice represents a services, of course, in this area we add something substantial, such as the

Onstart (...) function to create a music player MediaPlayer play music when the service is started ...

You create a service, just like you create an activity, you have to sign up in manifest. Start registration below

<!--added service-->
<service android:name= ". MyService ">
<intent-filter >
 <action android:name=" Com.study.android.action.MY_SERVICE "/>
</intent-filter>
</service>

The service is registered successfully.  Registration success has not completed the task Oh ... There are also start services, stop services, bind services, unbind services

Package com.study.android;
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 Mainactivity extends activity {final static String ACTION = "Com.study.android.action.MY_SERVICE";
 Private Button Startbutton,stopbutton;
 Private Button Bindbutton,unbindbutton;
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.main);
  Startbutton = (Button) Findviewbyid (R.id.startbutton);
  Stopbutton = (Button) Findviewbyid (R.id.stopbutton);
  Bindbutton = (Button) Findviewbyid (R.id.bindbutton);
  Unbindbutton = (Button) Findviewbyid (R.id.unbindbutton); Turn on service Startbutton.setonclicklistener (new onClicklistener () {@Override public void OnClick (View v) {//Start service StartService (Buildintent ());
  }
 }); Startbutton the following cycle function execution order onCreate ()----->onstart ()/******************************************///Stop service Stopbutt On.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {StopService (Buildintent ())
  ;
  }
 }); Stopbutton OnDestroy ()/******************************************//Bind service bindbutton.setonclicklist The following cycle function execution sequence Ener (New Onclicklistener () {@Override public void OnClick (View v) {Bindservice (Buildintent (), Conn,service.bind
   _auto_create);
  /* The third parameter: How to create a service is generally the establishment of binding automatic creation/}});
  Bindbutton is pressed (the current service has been stop) periodic function Execution Order onCreate ()------->onbind ()/******************************************/
   Contact binding service Unbindbutton.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {
  Unbindservice (conn);
  }
 }); Unbindbutton the following cycle function execution order Onunbind ()------->ondestroy ()}///Connection object PRIVATE Serviceconnection conn = new Serviceconnection () {@Override public void Onservi ceconnected (componentname name, IBinder service) {LOG.I (service), Connection service successful!
   "); Showinfo ("Connection service successful!")
 "); @Override public void onservicedisconnected (componentname name) {log.i ("service"), Services disconnected!
  "); Showinfo (the service connection is disconnected!)
 ");
 }
 };
  Public Intent buildintent () {Intent Intent = new Intent ();
  Set Intent Property Note: Here the action attribute should correspond to the manifest service intent.setaction (action);
 return intent;
 public void Showinfo (String str) {toast.maketext (this, str, toast.length_short). Show ();

 }
}

More interested readers of Android-related content can view the site: "Summary of the usage tips for Android service components", "Summary of operational skills for Android programming", "Android Resource Operation skills Summary", " Android File Operation Tips Summary, "Android operation SQLite Database Skills Summary", "Android operation JSON format Data Skills summary", "Android Database Operation skills Summary", "Android Development introduction and Advanced Course", " Android View tips Summary and a summary of the use of Android controls

I hope this article will help you with the Android program.

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.