安卓开发之开启服务的两种方式

package com.lidaochen.test001;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private MyConn conn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 当 Activity 销毁的时候 要解绑服务
    @Override
    protected void onDestroy() {
        // unbindService(conn);
        super.onDestroy();
    }

    // 点击按钮通过startService开启服务
    public void click1(View v)
    {
        Intent intent = new Intent(this, DemoService.class);
        startService(intent);
    }
    // 点击按钮通过stopService关闭服务
    public void click2(View v)
    {
        Intent intent = new Intent(this, DemoService.class);
        stopService(intent);
    }
    // 点击按钮通过bindService绑定服务
    public void click3(View v)
    {
        Intent intent = new Intent(this, DemoService.class);
        // 连接到DemoService 这个服务
        conn = new MyConn();
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
    // 点击按钮手动解绑服务
    public void click4(View v)
    {
        unbindService(conn);
    }

    // 定义一个类用来监视服务的状态
    private class MyConn implements ServiceConnection
    {
        // 当服务连接成功时调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("service", "onServiceConnected!");
        }

        // 失去连接时调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("service", "onServiceDisconnected!");
        }
    }
}
package com.lidaochen.test001;

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

public class DemoService extends Service {
    public DemoService() {
    }

    // 当服务第一次创建的时候调用
    @Override
    public void onCreate() {
        Log.e("service", "onCreate!");
        super.onCreate();
    }

    // 每次调用startService都会执行下面的方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("service", "onStartCommand!");
        return super.onStartCommand(intent, flags, startId);
    }

    // 当服务销毁的时候调用
    @Override
    public void onDestroy() {
        Log.e("service", "onDestroy!");
        super.onDestroy();
    }

    // 调用 bindService 会调用下面的这个方法
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("service", "onBind!");
        return null;
    }

}
原文地址:https://www.cnblogs.com/duxie/p/11033061.html