当前位置: 移动技术网 > 移动技术>移动开发>Android > android教程之service使用方法示例详解

android教程之service使用方法示例详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

service的生命周期 (适用于2.1及以上)

1. 被startservice的
无论是否有任何活动绑定到该service,都在后台运行。oncreate(若需要) -> onstart(int id, bundle args).  多次startservice,则onstart调用多次,但不会创建多个service实例,只需要一次stop。该service一直后台运行,直到stopservice或者自己的stopself()或者资源不足由平台结束。

2. 被bindservice的
调用bindservice绑定,连接建立服务一直运行。未被startservice只是bindservice,则oncreate()执行,onstart(int,bundle)不被调用;这种情况下绑定被解除,平台就可以清除该service(连接销毁后,会导致解除,解除后就会销毁)。

3. 被启动又被绑定
类似startservice的生命周期,oncreate onstart都会调用。

4. 停止服务时
stopservice时显式ondestroy()。或不再有绑定(没有启动时)时隐式调用。有bind情况下stopservice()不起作用。

以下是一个简单的实现例子,某些部分需要配合logcat观察。
acmain.java

复制代码 代码如下:

package jtapp.myservicesamples;
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.util.log;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.toast;
public class acmain extends activity implements onclicklistener {
        private static final string tag = "acmain";
        private button btnstart;
        private button btnstop;
        private button btnbind;
        private button btnexit;

    /** called when the activity is first created. */
    @override
    public void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.main);

        findview();
    }
        private void findview() {
                btnstart = (button) findviewbyid(r.id.start);
        btnstop = (button) findviewbyid(r.id.stop);
        btnbind = (button) findviewbyid(r.id.bind);
        btnexit = (button) findviewbyid(r.id.exit);

        btnstart.setonclicklistener(this);
        btnstop.setonclicklistener(this);
        btnbind.setonclicklistener(this);
        btnexit.setonclicklistener(this);
        }
        @override
        public void onclick(view v) {
                intent intent = new intent("jtapp.myservicesamples.myservice");
                switch(v.getid()) {
                case r.id.start:
                        startservice(intent);
                        toast.maketext(this,
                                        "myservice running " + myservice.msec/1000.0 + "s.",
                                        toast.length_long).show();
                        break;
                case r.id.stop:
                        stopservice(intent);
                        toast.maketext(this,
                                        "myservice running " + myservice.msec/1000.0 + "s.",
                                        toast.length_long).show();
                        break;
                case r.id.bind:
                        bindservice(intent, sc, context.bind_auto_create);
                        break;
                case r.id.exit:
                        this.finish();
                        break;
                }
        }

        private myservice servicebinder;

        private serviceconnection sc = new serviceconnection() {
                @override
                public void onservicedisconnected(componentname name) {
                        log.d(tag, "in onservicedisconnected");
                        servicebinder = null;
                }
                @override
                public void onserviceconnected(componentname name, ibinder service) {
                        log.d(tag, "in onserviceconnected");
                        servicebinder = ((myservice.mybinder)service).getservice();
                }
        };
        @override
        protected void ondestroy() {
                //this.unbindservice(sc);
                //this.stopservice(
                //                new intent("jtapp.myservicesamples.myservice"));
                super.ondestroy();
        }
}

main.xml

复制代码 代码如下:

<?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">
        <textview android:layout_width="fill_parent"
                android:layout_height="wrap_content" android:text="@string/hello" />
        <button android:text="start myservice" android:id="@+id/start"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <button android:text="stop myservice" android:id="@+id/stop"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <button android:text="bind myservice" android:id="@+id/bind"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <button android:text="exit acmain" android:id="@+id/exit"
                android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</linearlayout>

myservice.java

复制代码 代码如下:

package jtapp.myservicesamples;
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 static final string tag = "myservice";
        public static long msec = 0;
        private boolean bthreadrunning = true;

       
        private final ibinder binder = new mybinder();
        public class mybinder extends binder {
                myservice getservice() {
                        return myservice.this;
                }
        }
        @override
        public ibinder onbind(intent intent) {
                return binder;
        }
        @override
        public void oncreate() {
                new thread(new runnable(){
                        @override
                        public void run() {
                                while (bthreadrunning) {
                                        try {
                                                thread.sleep(100);
                                        } catch (interruptedexception e) {
                                        }
                                        log.i(tag, "myservice running " + (msec+=100) + "ms.");
                                }
                        }
                }).start();
        }
        @override
        public void ondestroy() {
                bthreadrunning = false;
                super.ondestroy(); // 可以不用
        }
}

anndroidmanifest.xml

复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="jtapp.myservicesamples" android:versioncode="1"
        android:versionname="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name"
                android:debuggable="true">
                <activity android:name=".acmain" 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">
                        <intent-filter>
                                <action android:name="jtapp.myservicesamples.myservice"></action>
                        </intent-filter>
                </service>
        </application>
</manifest>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网