服务器之家

服务器之家 > 正文

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

时间:2021-02-24 14:56     来源/作者:Android开发网

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>
标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部