Android---Service详解(一)

  
java.lang.Object
   ↳ android.content.Context
     ↳ android.content.ContextWrapper
       ↳ android.app.Service
什么是Service服务       

     首先,先来回顾下Android四大组件中的Activity(活动)Service(服务),剩下的BroadcastReceiver(广播接收者)ContentProvider(内容提供者)的详解日后补上。Activity是应用程序的表示层,为用户展示界面,一个Activity通常展示一个可视化的界面,而且每个Activity之间是相互独立的,这些Activity一起工作,共同组成一个应用程序。但是有时候我们不需要界面显示,想让程序在后台依然运行来完成一些特殊任务,比如播放背景音乐或者启动百度地图一个后台服务进行路况实时更新等等。这些服务都是在后台运行,可以为前台的Activity提供数据更新,并触发通知,提醒用户有新变化。这些后台服务就是Service组件完成的。

     此外,Service另外一个重要的用途是通过AIDL(Android Interface Definition Language,Android接口描述语言)实现进程间通信。例如,在某一程序中,其他组件可以直接与该程序后台运行的Service服务进行交互,另外一方面,多个程序可以通过Service,可以在保证进程安全的前提下,实现它们的通信。

     使用Service服务必须在AndroidManifest.xml注册,Services 可以通过 Context.startService() 和Context.bindService()两种方法来启动.

  • Service不是一个单独的进程。
  • Service不是一个线程。
  • 当用户不需要直接和后台服务进行交互时,可以使用Context.startService()。例如,后台播放音乐或网络下载数据,它要求系统保证它们的运行将运行直到服务结束或其他明确操作阻止它们。使用start方法,程序退出,该服务不一定停止。
  • 当应用程序想为其他应用程序提供交互时,可以使用Context.bindService()。它允许程序与服务间建立长期的连接来进行交互。使用bind方法,程序退出,该服务也会停止退出。


Service的生命周期
                                                                                                                                    
                        

                                                           startService()                                           bindService()

   

   Service的生命周期没有Activity那么地繁琐,使用StartSercive()方法,如果是第一使用,则调用OnCreate()来创建服务,而客户端通过OnStartCommand(Intent,in,int)来传参数(可以使用多个这方法)。这样服务会一直运行,直到使用stopService()来停止它(停止只需要一次stopServcie(),服务就会停止)。

   客户端使用bindService()方法来与服务间建立一个稳定的连接(connection),没有服务运行,调用onCreate()来创建,之后不需要OnStartCommand()方法,而是使用 onBind(Intent) 这个方法返回了一个实现了 IBinder 接口的对象The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder).IBinder返回的是个复杂的接口,需用AIDL。

   不管使用上面两种的哪个,最后都需要用onDestroy()方法来有效地终止服务。

注册Servcie服务
<service  
    android:name="xx.xx" <strong>/<span style="font-family: Arial, Helvetica, sans-serif;">/如果Service和Activity不在同一个包内,需要添加Service的完整路径</span></strong><span style="font-family: Arial, Helvetica, sans-serif;">  </span>
    android:enabled="true" >  
    <intent-filter>  
       <action android:name="xx.xx.xx" /> //自己定义的
    </intent-filter>  
</service>

Service实例介绍
    项目如图:

package com.spoofing.servcie;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;


public class MyService extends Service{
	private int count=0;
	private boolean quit=false;
	String run,implement;
	// 创建一个内部类
	public class MyBinder extends Binder {
		public int getcount()
		{
			return count;
			
		}
		
	}

	MyBinder mbinder = new MyBinder();
	@Override
	public void onCreate() {
		System.out.println("Servcie is Created!");
		// 启动一个线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (!quit) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					count++;
				}
			}


		}).start();
	}

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("Service is Binded!");
		return mbinder;
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		this.quit=true;
		System.out.println("Service is Destroyed!");
	}


	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("Service is UnBinded!");
		return true;
		
		
	}


}

package com.spoofing.servcietest;

import com.spoofing.servcie.MyService;
import com.spoofing.servcie.MyService.MyBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	Button bind, unbind, status;
	MyService.MyBinder binder;
	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("Service connected!");
			binder = (MyBinder) service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			System.out.println("Service disconnected!");
		}

	};// 容易丢掉分号

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		bind = (Button) findViewById(R.id.bind);
		unbind = (Button) findViewById(R.id.unbind);
		status = (Button) findViewById(R.id.status);
		
		final Intent intent = new Intent();
		intent.setAction("com.spoofing.servcie.MY_SERVICE");
		intent.setPackage(this.getPackageName());
		bind.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				bindService(intent, conn, Context.BIND_AUTO_CREATE);
			}
		});

		unbind.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				unbindService(conn);

			}
		});

		status.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
Toast.makeText(MainActivity.this, "获得服务的状态是"+binder.getcount(), Toast.LENGTH_LONG).show();
			}
		});

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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="com.spoofing.servcie.MyService">
           <intent-filter>
               <action android:name="com.spoofing.servcie.MY_SERVICE"/>
           </intent-filter>
       </service> 
    </application>

</manifest>




第一次写博客,水平有限,难免有错,望各路神仙多多包涵。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值