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()- >onStartCommand()->Service running--调用context.stopService() ->onDestroy()

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

 

 

二.注意事项

2.1  同一服务,多次启动,服务实际执行的过程

第一次 启动服务时,运行 onCreate -->onStartCommand

后面在启动服务时,服务只执行onStartCommand

在实际使用过程中,通过Intent 传递数据,在OnStartCommand中执行




android编写Service入门中介绍了android的两种后台服务,本地和远程的。这里用本地服务做了一个模拟定时后台发短信的技术原型。


主要代码,后台服务SmsService:

package com.easymorse;

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

public class SmsService extends Service {

    private boolean started;

    private boolean threadDisable;

    private ServiceBinder serviceBinder = new ServiceBinder();

    public class ServiceBinder extends Binder implements ISmsService {

        @Override
        public boolean isStarted() {
            return started;
        }

        @Override
        public void start() {
            started=true;
            Log.d(“sms.service”, “sms service started.”);
        }

        @Override
        public void stop() {
            started=false;
            Log.d(“sms.service”, “sms service stopped.”);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return serviceBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Thread thread = new Thread() {
            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        if (started) {
                            Log.d(“sms.service”, “send a sms message.”);
                        }
                        Thread.sleep(1000 * 5);
                    } catch (InterruptedException e) {
                    }
                }
            }
        };

        thread.start();

        Log.d(“sms.service”, “sms service created.”);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        threadDisable = true;
        Log.d(“sms.service”, “sms service shutdown.”);
    }
}

 

前台的Actvity代码,SmsServiceOptions:

package com.easymorse;

import android.app.TabActivity;
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.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class SmsServiceOptions extends TabActivity {

    private RadioGroup radioGroup;

    private ISmsService smsService;

    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            smsService = (ISmsService) service;

            if (smsService.isStarted()) {
                radioGroup.check(R.id.radioButtonStart);
            } else {
                radioGroup.check(R.id.radioButtonStop);
            }

            radioGroup
                    .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(RadioGroup group,
                                int checkedId) {
                            if (checkedId == R.id.radioButtonStart) {
                                Log.d(“sms.service”, “starting service…”);
                                smsService.start();
                            } else {
                                Log.d(“sms.service”, “stopping service…”);
                                smsService.stop();
                            }
                        }
                    });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            smsService = null;
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.setTitle(“短信服务器”);
        this.bindService(new Intent(“com.easymorse.SmsService”),
                this.serviceConnection, BIND_AUTO_CREATE);

        TabHost tabHost = this.getTabHost();
        tabHost.setup();

        TabHost.TabSpec spec = tabHost.newTabSpec(“服务选项”);
        spec.setContent(R.id.Option01);
        spec.setIndicator(“服务选项”);
        tabHost.addTab(spec);

        spec = tabHost.newTabSpec(“服务状态”);
        spec.setContent(R.id.Option02);
        spec.setIndicator(“服务状态”);
        tabHost.addTab(spec);

        radioGroup = (RadioGroup) this.findViewById(R.id.radioGroup01);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unbindService(serviceConnection);
    }
}

 

另外,不要忘记在配置文件中增加对service的声明,见AndroidManafest.xml:

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
    package=”com.easymorse” android:versionCode=”1″ android:versionName=”1.0″>
    <application android:icon=”@drawable/icon” android:label=”@string/app_name”>
        <activity android:name=”.SmsServiceOptions” 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=”.SmsService”>
            <intent-filter>
                <action android:name=”com.easymorse.SmsService”></action>
            </intent-filter>
        </service>
    </application>
    <uses-sdk android:minSdkVersion=”3″ />
</manifest>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值