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

时间:2023-05-08 03:48:21 

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>

标签:android,service
0
投稿

猜你喜欢

  • 基于C#方法重载的总结详解

    2022-07-29 13:19:46
  • Android中使用Toast.cancel()方法优化toast内容显示的解决方法

    2021-12-14 05:17:03
  • Spring Security 强制退出指定用户的方法

    2022-10-04 18:13:04
  • C# 三种序列化方法分享

    2022-09-21 03:43:05
  • android动态壁纸调用的简单实例

    2023-11-17 05:43:28
  • C#域名解析简单实现方法

    2023-08-26 15:30:55
  • IntelliJ IDEA安装目录和设置目录的说明(IntelliJ IDEA快速入门)

    2021-08-16 21:17:08
  • Android中Service与Activity之间通信的几种方式

    2023-10-11 15:40:16
  • Android实现多线程下载图片的方法

    2021-10-16 08:37:43
  • 打印Java程序的线程栈信息方式

    2021-11-02 19:00:28
  • Java8 stream 中利用 groupingBy 进行多字段分组求和案例

    2023-03-22 00:54:43
  • C++ Opencv实现录制九宫格视频

    2023-08-16 04:11:28
  • 关于idea中Java Web项目的访问路径问题

    2023-01-04 21:23:32
  • mybatis-plus分页查询的实现示例

    2023-11-25 04:57:57
  • Java设计模式之Strategy模式

    2023-11-21 03:58:22
  • Unity3d实现Flappy Bird游戏

    2023-09-17 20:54:29
  • Android应用中使用ViewPager和ViewPager指示器来制作Tab标签

    2021-08-04 11:33:37
  • Qt之调用C#的动态库的解决方法

    2023-07-22 03:42:45
  • Android实现加载广告图片和倒计时的开屏布局

    2023-04-29 13:54:45
  • C# TcpClient网络编程传输文件的示例

    2021-10-16 16:01:13
  • asp之家 软件编程 m.aspxhome.com