码迷,mamicode.com
首页 > 其他好文 > 详细

Service启动,绑定与交互

时间:2017-04-13 19:11:52      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:tco   ati   cal   read   err   binder   ram   ibinder   pre   

1. Service的启动方式有startServcie和bindService两种。

startService时,会经历onCreate—onStartCommand—onDestroy生命周期,

bindService时,会经历onCreate—onBind—onUnbind—onDestroy生命周期。

2. Service与Activity之间交互时,可以通过bindService获取Service的连接的Binder,进而可以获取Service的引用,这样就可以与Service进行交互了。示例中,通过Service每秒更新TextView一次。

ICounterCallback接口

package com.fxb.servicetest;

public interface ICounterCallback {
    public void count(int val);
}

CountService类

package com.fxb.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class CountService extends Service{

    private volatile boolean isRunning = true;
    private CounterBinder counterBinder = new CounterBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(MainActivity.TAG, "on bind!");
        return counterBinder;
    }

    public void startCounter(final int value, final ICounterCallback callback){
        isRunning = true;
        new AsyncTask<Integer, Integer, Void>() {
            @Override
            protected Void doInBackground(Integer... params) {
                int count = params[0];
                while(isRunning){
                    try {
                        Thread.sleep(1000);
                        count++;
                        Log.i(MainActivity.TAG, Integer.toString(count));
                        publishProgress(count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                callback.count(values[0]);
            }
        }.execute(0);
    }

    public void stopCounter(){
        isRunning = false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(MainActivity.TAG, "on create!");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(MainActivity.TAG, "on start command!");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(MainActivity.TAG, "on unbind servcie!");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        isRunning = false;
        Log.i(MainActivity.TAG, "on destroy service");
        super.onDestroy();
    }

    @Override
    public boolean stopService(Intent name) {
        Log.i(MainActivity.TAG, "on stop service!");
        return super.stopService(name);
    }

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

MainActivity类

package com.fxb.servicetest;

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.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener, ICounterCallback{

    public static final String TAG = "ServiceTest";

    private TextView tvShow;
    private Button btnStartServie, btnStopService;
    private Button btnBindService, btnUnbindService;
    private Button btnStartCounter, btnStopCounter;
    private CountService countService;

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

    private void initView(){
        tvShow = (TextView)findViewById(R.id.tvShow);
        btnStartServie = (Button)findViewById(R.id.btnStartService);
        btnStopService = (Button)findViewById(R.id.btnStopService);
        btnBindService = (Button)findViewById(R.id.btnBindService);
        btnUnbindService = (Button)findViewById(R.id.btnUnbindService);
        btnStartCounter = (Button)findViewById(R.id.btnStartCount);
        btnStopCounter = (Button)findViewById(R.id.btnStopCount);

        btnStartServie.setOnClickListener(this);
        btnStopService.setOnClickListener(this);
        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnStartCounter.setOnClickListener(this);
        btnStopCounter.setOnClickListener(this);
    }

    private void startCountService(){
        Intent intent = new Intent(MainActivity.this, CountService.class);
        startService(intent);
    }

    private void stopCountService(){
        Intent intent = new Intent(MainActivity.this, CountService.class);
        stopService(intent);
    }

    private void myBindService(){
        Intent intent = new Intent(MainActivity.this, CountService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void myUnbindService(){
        unbindService(serviceConnection);
    }

    @Override
    public void onClick(View v) {
        if(v == btnStartServie){
            Log.i(TAG, "start click");
            startCountService();
        }
        else if(v == btnStopService){
            stopCountService();
        }
        else if(v == btnBindService){
            myBindService();
        }
        else if(v == btnUnbindService){
            myUnbindService();
        }
        else if(v == btnStartCounter){
            if(countService != null){
                countService.startCounter(0, this);
            }
        }
        else if(v == btnStopCounter){
            if(v == btnStopCounter){
                countService.stopCounter();
            }
        }
    }

    @Override
    public void count(int val) {
        tvShow.setText("count:"+val);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(MainActivity.TAG, "service connected!");
            CountService.CounterBinder binder = (CountService.CounterBinder)service;
            countService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(MainActivity.TAG, "service disconnected!");
        }
    };

}

在bindService之后,点击startCount后,tvShow每隔1s更新一次,点击stopCount后停止更新。

Service启动,绑定与交互

标签:tco   ati   cal   read   err   binder   ram   ibinder   pre   

原文地址:http://www.cnblogs.com/MiniHouse/p/6705481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!