Android Service Services Detailed (i) _android

Source: Internet
Author: User

This paper analyzes the service of Android in detail. Share to everyone for your reference, specific as follows:

First, Service introduction

Service is a solution for running the program backstage in Android, and is designed to perform tasks that do not require interaction with the user and require long-term operation. Service is one of the four components of the Android system (activity, Service, Broadcastreceiver, ContentProvider), which is about the same level as the activity, but cannot run only in the background, And can interact with other components.

Service is not running in a separate process, but relies on the application process where the service is created. When an application process is killed, all services that depend on the process will also stop running.

Second, the first practice of service

Create an Android project Testservice.

1. Create a new service

Package com.example.testservice;
Import Android.app.Service;
Import android.content.Intent;
Import Android.os.IBinder;
Import Android.widget.Toast;
public class MyService extends Service {
  @Override public
  ibinder onbind (Intent arg0) {return
    null;
  }
  /**
   * The first time the service is created call/
  @Override public
  void OnCreate () {
    super.oncreate ();
    Toast.maketext (This, "the OnCreate method of the service is invoked", Toast.length_short). Show ();
  /**
   * Service every time the launch of the call *
   *
  @Override public
  int Onstartcommand (Intent Intent, int flags, int startid) { C23/>toast.maketext (This, "the Onstartcommand method of the service is invoked", Toast.length_short). Show ();
    Return Super.onstartcommand (Intent, flags, Startid);
  }
  @Override public
  void OnDestroy () {
    Toast.maketext (this, the OnDestroy method of the service is invoked, Toast.length_short). Show ();
    Super.ondestroy ();
  }


When you create a service, you inherit the services class, overriding the OnCreate method, the Onstartcommand method, and the OnDestroy method.

2. Modify Androidmanifest.xml

When you have completed a new service, you need to register in Androidmanifest.xml, as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <manifest "xmlns:android=" Schemas.android.com/apk/res/android "package=" Com.example.testservice "android:versioncode=" 1 "android: Versionname= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "a"/> <applicat Ion android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Andro Id:theme= "@style/apptheme" > <activity android:name= "com.example.testservice.MainActivity" android:l Abel= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/>
        ;
    <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <!--registration Service--> <service android:name= ". MyService "></service> </application> </manifest> 

3, Layout file Activity_main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
  android:layout_width= "Fill_ Parent "
  android:layout_height=" fill_parent "
  android:orientation=" vertical ">
  <button
    Android:id= "@+id/button1"
    android:layout_width= "match_parent"
    android:layout_height= "Wrap_content"
    android:text= "Start service"/>
  <button
    android:id= "@+id/button2"
    android:layout_width= Parent "
    android:layout_height=" wrap_content "
    android:text= stop Service"/>
</LinearLayout>

4, Mainactivity.java documents

Package com.example.testservice;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
  public class Mainactivity extends activity implements onclicklistener{private Button Startservice_button;
  Private Button Stopservice_button;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Get the Open service button Startservice_button = (button) Findviewbyid (R.id.button1);
    Get stop service button Stopservice_button = (button) Findviewbyid (R.id.button2);
    Call Click event Startservice_button.setonclicklistener (this);
  Stopservice_button.setonclicklistener (this);
      /** * Click event/@Override public void OnClick (view view) {switch (View.getid ()) {case R.id.button1: The "Open Service" button Intent startintent = new Intent (this,myservice.Class);
      Open service StartService (startintent);
    Break
      Case R.id.button2://"Stop Service" button Intent stopintent = new Intent (this,myservice.class);
      Stop service StopService (stopintent);
    Break
    Default:break;  } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds the items to the action
    Bar if it is present.
    Getmenuinflater (). Inflate (R.menu.main, menu);
  return true;

 }
}

Third, test results

After you publish the project, as follows:

When you click on the "Start Service" button, the following sequence pops up:

And, at this time you click on the "Start Service" button, will only pop up the top right image, and no longer pop-up above the left image. Because the OnCreate method is invoked only when the service is created, the Onstartcommand method is invoked each time when the service is started.

When you click "Stop Service", the following:

Summary: The startup process for the Android service is as follows:

Invoke the StartService method of the context---"OnCreate method---" Onstartcommand Method---"service runs.

The stop process for the Android service is as follows:

Service Running---StopService method of calling the context--"OnDestroy Method---" Service stopped.

For more information on Android components interested readers can view the site topics: "Android Basic components Usage Summary"

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.