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

service的用法(1)

2014年01月26日 ⁄ 综合 ⁄ 共 4395字 ⁄ 字号 评论关闭

android中服务是运行在后台的东西,级别与activity差不多。既然说service是运行在后台的服务,那么它就是不可见的,没有界面的东西。你可以启动一个服务Service来播放音乐,或者记录你地理信息位置的改变,或者启动一个服务来运行并一直监听某种动作。

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()会先加载它。

提供给可被其他应用复用,比如定义一个天气预报服务,提供与其他应用调用即可。

那么先来看Service的生命周期吧:如图:


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

context.bindService()->onCreate()->onBind()->Service
running
--调用>onUnbind() ->onDestroy()从上诉可以知道分别对应本地的,,以及远程的,也对应不同的方式启动这个服务。

二.实战

我们可以定义一个本地服务继承Service,然后在这个服务里播放媒体播放器或者记录地理位置变化。通常有时候我们的Service要与Activity交互,那么可以可以定义一个内部类,返回这个Service,当然我们要考虑到如果是以绑定方式启动服务,那么内部类可以定义为继承Binder,然后返回本地服务,具体代码如下。

View
Code

我们可以从上面知道

 //定义内容类继承Binder

    public class LocalBinder extends Binder{

        //返回本地服务

        LocalService getService(){

            return LocalService.this;

        }

    }

可以返回这个服务,然后activity可以通过服务调用服务的方法了。

那么如何启动服务呢?从上面基础知识中,我们知道有2种方法,如下:

  //启动服务
private void startCustomService(){
Intent intent=new Intent(this,LocalService.class);
startService(intent);
}

第2种绑定方式:

复制代码
LocalService localService=null;
//用bindService方法启动服务
private void BinderService(){
Intent intent=new Intent(this,LocalService.class);
bindService(intent, new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName componentName, IBinder binder) {
//调用bindService方法启动服务时候,如果服务需要与activity交互,
//则通过onBind方法返回IBinder并返回当前本地服务
localService=((LocalService.LocalBinder)binder).getService();
//这里可以提示用户,或者调用服务的某些方法
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
localService=null;
//这里可以提示用户
}
}, Context.BIND_AUTO_CREATE);
}
复制代码

在绑定服务的时候,需要一个服务连接对象,ServiceConnection,服务一旦连接,就会调用onServiceConnected方法,我们可以在这个方法里面返回我们的本地服务对象,具体看代码;而在服务断开时候会调用onServiceDisconnected方法,我们可以清理一些服务资源。


下面奉上一个实例:

首先创建ExampleService

package com.dd.dd;

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

public class ExampleService extends Service {

	private static final String TAG = "ExampleService";

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.i(TAG, "ExampleService-->onCreate");//用于让输出结果到日志,显示服务是否在后台运行
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "ExampleService-->onDestroy");
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "ExampleService-->onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

}

然后在创建布局文件

就在默认布局文件中写

<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:background="#000000"
    tools:context=".MainActivity" >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_marginTop="80dp"
            android:background="@drawable/shape"
            android:text="确认" />

        <Button
            android:id="@+id/btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_marginTop="80dp"
            android:background="@drawable/shape"
            android:text="取消" />
    </LinearLayout>

</RelativeLayout>

最后在MainActivity类中输入:

public class MainActivity extends Activity {
	private Button btn1;//对应确定按钮
	private Button btn2;//对应取消按钮

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn1 = (Button) findViewById(R.id.btn1);
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						ExampleService.class);
				startService(intent);
			}
		});

		btn2 = (Button) findViewById(R.id.btn2);
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			
				Intent intent = new Intent(MainActivity.this,
						ExampleService.class);
				stopService(intent);
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}

抱歉!评论已关闭.