Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 595|回复: 0

[实例教程]Android中的Service使用

[复制链接]

该用户从未签到

发表于 2011-10-22 13:30:43 | 显示全部楼层 |阅读模式
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"

        androidrientation="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>
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

GMT+8, 2024-5-19 03:27 , Processed in 0.389960 second(s), 46 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表