Android Service Bind with Activity

本文详细阐述了Android服务的基本概念、分类、生命周期及其使用方法,并通过实例展示了应用程序内部服务和应用程序间服务的实现过程。同时,文章强调了服务作为后台组件的重要性和注意事项,如避免阻塞UI操作引发的ANR警告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是Service

Android 中的服务类似于Windows中的Windows Service。Service 是不可见的(没有界面),但却又是非常重要的。在Android中,通常使用服务来播放音乐,记录地理位置的改变,处理网络操作,操作文件I/O等等,或者启动一个服务监听一些操作。

官方对Service的定义如下:

A Service is an application component that canperform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally,a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

服务是一个没有用户界面的在后台运行执行耗时操作的应用组件。其他应用组件能够启动Service,即使当用户切换到另外的应用场景,Service也将持续在后台运行。另外,一个组件能够绑定到一个service与与之交互(IPC机制),例如,一个service可能会处理网络操作,播放音乐,操作文件I/O或者与内容提供者(content provider)交互,所有这些活动都是在后台进行。

2.Service的分类

从Android官方对Service的定义,我们可以把Service分为两类:

1.应用程序内部服务:也被称为本地服务(Local Service),用于应用程序内部,在Service外部可以调用Context.startService()启动,调用Context.stopService()结束。在内部可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。无论调用了多少次startService(),都只需调用一次stopService()来停止。

2.应用程序间服务也被称为远程服务(Remote Service)用于应用程序之间。用于android系统内部的应用程序之间。可以定义接口并把接口暴露出来,以便其他应用进行操作。客户端建立到服务对象的连接,并通过那个连接来调用服务。调用Context.bindService()方法建立连接,并启动,以调用 Context.unbindService()关闭连接。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。

3.生命周期

Service 生命周期各个阶段如下:

                                 

4.如何使用

通常service的调用流程如下:

context.startService() ->onCreate()- >onStart()->Service running--调用context.stopService() ->onDestroy() 
context.bindService()->onCreate()->onBind()->Service running--调用>onUnbind() -> onDestroy() 

注意:Service 和 Activity 是同级别的组件,service与activity一样都存在与当前进程的主线程中,所以,一些阻塞UI的操作,如果在service里进行一些耗CPU和耗时操作,可能会引发ANR警告,这时应用会弹出是强制关闭还是等待的对话框。所以,对service的理解就是和activity平级的,只不过是看不见的,在后台运行的一个组件。

5.实例

1)应用程序内部服务

关于本地服务,请参考我之前写的一篇文章

http://www.cnblogs.com/fuhui-jurassic/p/4129490.html

2)应用程序间服务

a) 布局文件

<?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"
    >
    
    <Button
     	android:layout_width="wrap_content" 
	    android:layout_height="wrap_content" 
	    android:text="Get Message"
	    android:id="@+id/button"
	    />
	<TextView  
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:id="@+id/result"
	    />
</LinearLayout>
b) IService接口

public interface IService {
	public String getName(int id);
}
c) MyService(实现IService)

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
	private String TAG = "MyService";
	private Binder binder = new MyBinder();
	
	public String getName(int id){
		Log.i(TAG, "MyService getName.");
		return "Message from Service.";
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}
	
	private final class MyBinder extends Binder implements IService{
		public String getName(int id){
			Log.i(TAG, "MyBinder getName.");
			return MyService.this.getName(23);
		}
	}
}
c) MainActivity

import com.example.myandroid_002.R;
import android.app.Activity;
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.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	
    private MyServiceConnection conn;
    private IService myservice;
    private String TAG = "MainActivity";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        conn = new MyServiceConnection();
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
        Button button = (Button) this.findViewById(R.id.button);
        
        button.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				TextView resultView = (TextView) findViewById(R.id.result);
				resultView.setText(myservice.getName(56));
				Log.i(TAG, "Get Service Result successfully.");
			}
		});
        
    }
    
    private final class MyServiceConnection implements ServiceConnection{
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			myservice = (IService)service;
			Log.i(TAG, "onServiceConnected.");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			myservice = null;
			Log.i(TAG, "onServiceDisconnected.");
		}
    }

	@Override
	protected void onDestroy() {
		unbindService(conn);
		super.onDestroy();
		Log.i(TAG, "onDestroy.");
	}
}

d)manifest.xml

<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=".MyService"/>
    </application>
e)运行效果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值