Service(一) - Service简介及开启服务停止服务用

2019-01-27  本文已影响0人  世道无情

1. Service简介


服务,四大组件之一,主要用于在后台处理一些 耗时的逻辑、或者执行一些需要长期运行的任务,必要情况可以在 程序退出到桌面时,让Service在后台继续保持运行状态;

2. Service基本用法


1>:启动服务(StartService)和停止服务(StopService)

在Activity中 通过StartService启动服务,通过StopService停止服务


图片.png
代码如下:
MyService代码如下:
/**
 * ================================================
 * Email: 2185134304@qq.com
 * Created by Novate 2018/12/18 15:09
 * Version 1.0
 * Params:
 * Description:
 * 备注:任何一个 Service在整个应用程序范围内都是通用的,也就是说 MyService 不仅可以和ServiceActivity关联,
 *       还可以和任何一个Activity关联
 * ================================================
*/

public class MyService extends Service {

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

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("TAG" , "onDestroy__executed") ;
    }

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

}
ServiceActivity代码如下:
/**
 * ================================================
 * Email: 2185134304@qq.com
 * Created by Novate 2018/12/18 15:37
 * Version 1.0
 * Params:
 * Description:    在Activity中演示:启动服务StartService 与 StopService停止服务
 * ================================================
*/

public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {

    private Button startService;
    private Button stopService;
    private Intent intent;

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

        startService = (Button) findViewById(R.id.start_service);
        stopService = (Button) findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            // 启动服务
            case R.id.start_service:
                 intent = new Intent(ServiceActivity.this , MyService.class);
                 startService(intent) ;

                 break;
            // 停止服务
            case R.id.stop_service:
                 intent = new Intent(ServiceActivity.this , MyService.class);
                 stopService(intent) ;
                 break;
        }
    }
}

打印log如下:
点击 StartService 启动服务:

onCreate__executed
onStartCommand__executed

点击 StopService 停止服务:

onDestroy__executed

startService:开启服务,点击第一次会打印 onCreate__executed、onStartCommand__executed,以后点击只会执行 onStartCommand__executed,不会执行 onCreate__executed,说明 onCreate只会执行一次;
stopService:停止服务,执行onDestroy__executed,调用后就将 MyService停止掉;

上一篇 下一篇

猜你喜欢

热点阅读