[Android开发入门]初识Service

        作者:sundroid

       个人站点:sundroid.cn    邮箱: hfutsnjc@163.com   微博:http://weibo.com/Sundroid

   Service是Android系统中类似Activity的一种组件,不能够自己启动,也不能与用户交互,只能运行于后台,主要适用于运行于后台的功能(比如请求网络,退出音乐程序后继续播放音乐),

     Service和Activity一样也具有生命周期,其分别为onCreate()、onStart()和onDestory()。

      

        

       从上图可见,Service的整个生命周期其实与onCreate()、终止于onDestory()。实现Service需要继承Service,其启动方法有两种,startService()和bindService(),相对应的结束方式分别为stopServie()和unbindService()。

      startService()和bindService()两个方法都可以启动Service,但是两者的应用场合有所不同,使用startService()方法启动服务,调用者与服务之间没有关联,即使调用者退出了,服务仍然运行,使用bindService()方法启动服务,调用者与服务绑定在一起,调用者一旦退出,服务也就终止了。


 倒计时方法一实现

MainActivity

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;



public class MainActivity extends Activity {
    private Button startService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService = (Button) findViewById(R.id.startService);
        //开启服务
        startService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,CountService.class);
                startService(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //程序结束后停止服务
        Intent intent = new Intent(MainActivity.this,CountService.class);
        stopService(intent);
    }
}


CountService

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


/**
 * Created by sundroid on 2015/3/6.
 */
public class CountService extends Service{

    private int seconds=60;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //新建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(seconds!=0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i("TIME","Time remain "+seconds);
                    seconds--;
                }
                Log.i("SERVICE","Time up");
            }
        }).start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
倒计时方法二实现
MainActivity

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;




public class MainActivity extends Activity {


    private CountService countService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(MainActivity.this,CountService.class);
        //进入Activity时,开启服务
        bindService(intent,conn, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //程序结束后停止服务
       this.unbindService(conn);    }
     private ServiceConnection conn = new ServiceConnection() {
         @Override
         public void onServiceConnected(ComponentName name, IBinder service) {
           countService = ((CountService.ServiceBinder)service).getService();
         }

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


CountService

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


/**
 * Created by sundroid on 2015/3/6.
 */
public class CountService extends Service{

    private int seconds = 60;
    private ServiceBinder serviceBinder;

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

    @Override
    public void onCreate() {
        super.onCreate();
        //新建一个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(seconds!=0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i("TIME","Time remain "+seconds);
                    seconds--;
                }
                Log.i("SERVICE","Time up");
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class ServiceBinder extends Binder{
        public CountService getService(){
            return CountService.this;
        }
    }
}

manifest配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.sundroid.androidreview" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>xz
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".CountService"></service>
    </application>

</manifest>


BInder 的通信机制


运行结果

03-06 11:33:51.118    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 13
03-06 11:33:52.119    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 12
03-06 11:33:53.121    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 11
03-06 11:33:54.122    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 10
03-06 11:33:55.123    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 9
03-06 11:33:56.124    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 8
03-06 11:33:57.126    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 7
03-06 11:33:58.128    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 6
03-06 11:33:59.129    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 5
03-06 11:34:00.130    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 4
03-06 11:34:01.131    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 3
03-06 11:34:02.132    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 2
03-06 11:34:03.133    2359-2383/cn.sundroid.androidreview I/TIME﹕ Time remain 1
03-06 11:34:03.134    2359-2383/cn.sundroid.androidreview I/SERVICE﹕ Time up


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值