现在的位置: 首页 > 综合 > 正文

Android Service 服务 (一)

2017年06月11日 ⁄ 综合 ⁄ 共 3906字 ⁄ 字号 评论关闭

一、Service简介

         Service是Android中实现程序后台运行的解决方案,适用于去执行那些不需要和用户交互而且还要求长期运行的任务。Service是android 系统中的四大组件之一(Activity、Service、BroadcastReceiver、ContentProvider),它跟Activity的级别差不多,但不能自己运行只能后台运行,并且可以和其他组件进行交互。

         Service并不是运行在一个独立的进程当中的,而是依赖于创建服务时所在的应用程序进程。当某个应用程序进程被杀掉时,所有依赖于该进程的服务也会停止运行。

二、Service初实践

      创建一个Android项目TestService。

     1、新建一个服务

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;
	}
	 
	/**
	 * 服务第一次创建的时候调用
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		Toast.makeText(this, "服务的onCreate方法被调用", Toast.LENGTH_SHORT).show();
	}
	
	/**
	 * 服务每一次启动的时候调用
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Toast.makeText(this, "服务的onStartCommand方法被调用", Toast.LENGTH_SHORT).show();
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		Toast.makeText(this, "服务的onDestroy方法被调用", Toast.LENGTH_SHORT).show();
		super.onDestroy();
	}
}

    在创建一个服务时,继承Service类,重写了onCreate方法,onStartCommand方法以及onDestroy方法。

    2、修改AndroidManifest.xml

        当新建完一个服务后,需要在AndroidManifest.xml中进行注册,如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.testservice.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- 注册服务 -->
        <service android:name=".MyService"></service>
    </application>

</manifest>

       3、布局文件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="启动服务" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="停止服务" />
</LinearLayout>

      4、MainActivity.java文件

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);
		
		//获取开启服务按钮
		startService_Button = (Button) findViewById(R.id.button1);
		//获取停止服务按钮
		stopService_Button = (Button) findViewById(R.id.button2);
		
		//调用点击事件
		startService_Button.setOnClickListener(this);
		stopService_Button.setOnClickListener(this);
	}
	
	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View view) {
		switch(view.getId()){
		case R.id.button1:
			//“开启服务”按钮
			Intent startIntent = new Intent(this,MyService.class);
			//开启服务
			startService(startIntent);
			break;
		case R.id.button2:
			//“停止服务”按钮
			Intent stopIntent = new Intent(this,MyService.class);
			//停止服务
			stopService(stopIntent);
			break;
		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	

}

三、测试结果

     发布项目后,如下所示:

                   

    当点击“启动服务”按钮后,会依次弹出如下:

                          

       并且,此时你多次点击“启动服务”按钮,只会弹出上方右图,而不再弹出上方左图。因为仅仅在服务创建的时候会调用onCreate方法,但当服务启动的时候每次都会调用onStartCommand方法。

     当点击“停止服务”后,如下:

                       

总结 ,Android Service服务的启动流程如下:

      调用Context的startService方法---》onCreate方法---》onStartCommand方法---》服务运行。

Android服务的停止流程如下:

     服务运行---》调用Context的stopService方法--》onDestroy方法---》服务停止。

  

抱歉!评论已关闭.