Service详解

1.简介

Service运行在后台不需要依赖UI,但是依然在主线程中。

2.使用注意

2.1 startService()

startService, Service类执行方法: onCreate(),onStartCommand().

再次调用startService, 只会执行onStartCommand(). 因为onCreate()只会在Service创建的时候执行一次。每次调用 startService,都会执行onStartCommand().

stopService, Service类执行方法:onDestroy()。

我们应该始终记得在Service的onDestroy()方法里去清理掉那些不再使用的资源,防止在Service被销毁后还会有一些不再使用的对象仍占用着内存。

2.2 bindService()

bindService, Service类执行方法: onCreate(),onStartCommand().

unbindService, Service类执行方法:onDestroy().此时调用stopService()不起作用

对于startService开启的服务,调用unbindService()会让程序崩溃。

unbindService()后,再次调用unbindService(),程序会崩溃。

3.代码示例

- 模拟bindService新开线程,做一个耗时任务,发送通知给Activity,并且更新UI。

Activity类

public class ServiceActivity extends Activity implements View.OnClickListener{

    private Button mBtnStopS;
    private Button mBtnStartS;
     private Button mBtnBindS;
    private Button mBtnUnBindS;
    private TextView mTvShowTest;

    private TestService.MyBinderTest mBinderTest;
    private ServiceConnection mConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
           mBinderTest= (TestService.MyBinderTest)service;
            mBinderTest.startDownload();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

        initView();

        registerBroadcast();
    }

    private void registerBroadcast() {
        IntentFilter filter=new IntentFilter("com.exa.test");
        registerReceiver(mReceiver,filter);
    }

    private void initView() {
        mBtnStartS = (Button) findViewById(R.id.btn_start_service);
        mBtnStopS = (Button) findViewById(R.id.btn_stop_service);
        mBtnBindS = (Button) findViewById(R.id.btn_bind_service);
        mBtnUnBindS = (Button) findViewById(R.id.btn_unbind_service);
        mTvShowTest = (TextView) findViewById(R.id.tv_show_test);

        mBtnStartS.setOnClickListener(this);
        mBtnStopS.setOnClickListener(this);
        mBtnBindS.setOnClickListener(this);
        mBtnUnBindS.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent=new Intent(ServiceActivity.this,TestService.class);
        switch (v.getId()){
            case R.id.btn_start_service:
                startService(intent);
                break;
            case R.id.btn_stop_service:
                stopService(intent);
                break;
            case R.id.btn_bind_service:
                bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind_service:
                unbindService(mConnection);
                break;
        }
    }

   private BroadcastReceiver mReceiver=new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
           Log.i("TestService","ok:"+intent.getStringExtra("msg"));
           mTvShowTest.setText(intent.getStringExtra("msg")+"");
       }
   };

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
        unbindService(mConnection);
    }
}

Service类

public class TestService extends Service {

    private static final String TAG = TestService.class.getSimpleName();

    private MyBinderTest mBinderTest=new MyBinderTest();
   class MyBinderTest extends Binder{
        public void startDownload(){
            Log.i(TAG,"startDownload");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG,"run");
                    Intent intent=new Intent();
                    intent.setAction("com.exa.test");
                    intent.putExtra("msg","来自TestService的消息");
                    sendBroadcast(intent);
                }
            }).start();
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinderTest;
    }

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

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG,"onDestroy");

    }
}

你可能感兴趣的:(Service详解)