HomeHealth basics for Android Projects 2: Service, androidhomehealth

Source: Internet
Author: User

HomeHealth basics for Android Projects 2: Service, androidhomehealth

1. Service Introduction

A Service is one of the four main components in the android system (Activity, Service, BroadcastReceiver, and ContentProvider). It is similar to the Activity level, but cannot run on its own and can only run on the background, and can interact with other components. Service can be used in many applications. For example, when a user starts another Activity during multimedia playback, the program will continue playing the video in the background, for example, detecting file changes on the SD card, or record the changes in your location in the background. In short, the service is always stored in the background.

There are two ways to start a Service:Context. startService ()AndContext. bindService ()


2. Service start Process

Context. startService () Startup Process:

Context. startService ()-> onCreate ()-> onStart ()-> Service running-> context. stopService ()-> onDestroy ()-> Service stop


If the Service is not running, android first calls onCreate () and then calls onStart ();

If the Service is already running, only onStart () is called. Therefore, the onStart method of a Service may be called multiple times.

If stopService is called onDestroy directly, if the caller directly exits without calling stopService, the Service will continue to run in the background. After the Service is started, the caller can use stopService to close the Service.

Therefore, the life cycle for calling startService is onCreate --> onStart (which can be called multiple times) --> onDestroy


Context. bindService () Startup Process:

Context. bindService ()-> onCreate ()-> onBind ()-> Service running-> onUnbind ()-> onDestroy ()-> Service stop
 

OnBind () returns an IBind interface instance to the client. IBind allows the client to call back the Service methods, such as obtaining the Service instance, running status, or other operations. At this time, the caller (such as Activity) will be bound with the Service, and the Context will exit, and Srevice will call onUnbind-> onDestroy to exit accordingly.

Therefore, the life cycle of calling bindService is onCreate --> onBind (only once, cannot be bound multiple times) --> onUnbind --> onDestory.

During each Service enabling and disabling process, only onStart can be called multiple times (through multiple startService calls), other onCreate, onBind, onUnbind, onDestory can only be called once in a lifecycle.

 


3. Service Lifecycle

The lifecycle of a Service is not as complex as that of an Activity. It only inherits three methods: onCreate (), onStart (), and onDestroy ().

When we start the Service for the first time, we call the onCreate () and onStart () Methods successively. when the Service is stopped, the onDestroy () method is executed.

Note that if the Service has been started, when we start the Service again, the onCreate () method is not executed, but the onStart () method is directly executed.

It can use Service. stopSelf () method or Service. the stopSelfResult () method is used to stop a service. You only need to call the stopService () method once to stop the service, no matter how many times you call the start service method.


Iv. Sample Code

(1)StartService example

The project includes two classes: MainActivity. java and PlayService. java.

MainActivity. java defines two buttons to control the playing and stopping of music respectively.

Use startService and stopService to switch between the Activity and Service, start the Service, and cancel the Service. If you do not need a button, you can start and cancel the Service in OnCreate and OnDestrpy of the Activity.

The AndroidManifest. xml file is as follows:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.serviceactivity"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >                <service android:enabled="true" android:name=".PlayService" />    </application>    </manifest>

Layout file activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <Button         android:id="@+id/button_on"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="open"/><Button         android:id="@+id/button_off"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/button_on"        android:text="close"/><TextView     android:id="@+id/txt"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/button_off"        android:text="we will via"    /></RelativeLayout>


The MainActivity. java code is as follows:

package com.example.hellowendy;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {/** Called when the activity is first created. */Button buttonOn, buttonOff;String TAG = "ServiceActivity";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);buttonOn = (Button) findViewById(R.id.button_on);buttonOff = (Button) findViewById(R.id.button_off);buttonOn.setOnClickListener(this);buttonOff.setOnClickListener(this);Log.v(TAG, "ActivityonCreate");}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case (R.id.button_on):Log.v(TAG, "ActivitystartService");this.startService(new Intent(this, PlayService.class));// startService(new Intent(this, PlayService.class));break;case (R.id.button_off): {Log.v(TAG, "ActivitystopService");this.stopService(new Intent(this, PlayService.class));// stopService(new Intent(this, PlayService.class));}break;default:break;}}@Overrideprotected void onStop() {// TODO Auto-generated method stubsuper.onStop();Log.v(TAG, "ActivityonStop");}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubLog.v(TAG, "ActivityonDestroy");super.onDestroy();}}


The PlayService. java code is as follows:

/***** // ***** @ Author Administrator **/package com. example. hellowendy; import java. io. IOException; import android. app. service; import android. content. intent; import android. media. mediaPlayer; import android. OS. IBinder; import android. util. log; import android. widget. textView; import android. widget. toast; public class PlayService extends Service {String TAG = "ServiceActivity"; MediaPlayer mediaPlayer; @ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn null ;} @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); Toast. makeText (this, "Play Service Created", Toast. LENGTH_LONG ). show (); Log. v (TAG, "ServiceonCreate"); // TextView txtview; // txtview = (TextView) findViewById(R.id.txt); <span style = "white-space: pre "> </span> // The Song cong.mp3 from the primary resource," the year in a hurry ", <span style =" color: # ff0000; font-family: 'black Verdana ', Arial, Helvetica, sans-serif; font-size: 14px; line-height: 21px; "> the cong.mp3 directory is hellowendy-> res </span> <span style =" font-family: 'Black Verdana ', Arial, Helvetica, sans-serif; font-size: 14px; line-height: 21px; "> <span style =" color: # ff0000; ">-> raw-> cong.mp3 </span> mediaPlayer = MediaPlayer. create (this, R. raw. cong );
} @ Overridepublic void onStart (Intent intent, int startId) {// TODO Auto-generated method stub/super. onStart (intent, startId); // super. onStart ();/** // you can create a connection to the music in OnCreate, or create mediaPlayer = * MediaPlayer in OnStart. create (this, R. raw. test); */Toast. makeText (this, "Play Service onStart", Toast. LENGTH_LONG ). show (); Log. v (TAG, "ServiceonStart"); mediaPlayer. start () ;}@ Overridepublic void onDestroy () {// TODO Auto-generated method stubsuper. onDestroy (); Toast. makeText (this, "Play Service Stopped", Toast. LENGTH_LONG ). show (); Log. v (TAG, "ServiconDestroy"); mediaPlayer. stop ();}}







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.