2.四大组件之服务service ------1.初步入门

用俗话说就是长期于后台运行的程序。如果官方一点,首先是一个组件用于长期运行的任务,并且与用户没有交互。每一个服务都需要在配置文件AndroidMainfest.xml里进行声明,如何声明?

使用<service>标签,其实跟前面的activity,广播接收者receiver一样声明。

通过Context.startService()来开启服务,通过Context.stop()来停止服务。当然了,还有一种启动形式就是通过Context.bindService()的方法。

 

实例:在后台播放音乐,在后台下载

 

小栗子,服务的开启和关闭

右键新建个服务:FirestService.class

package com.example.myservice.services;

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

public class FirstService extends Service {

    public final String TAG = this.getClass().getName();

    public FirstService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy销毁.......");
    }
}

别忘了去注册(这里Android stdio自动帮我们注册好了)

服务写好了现在去MainActivity中点击按钮开启服务或者销毁服务

package com.example.myservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.example.myservice.services.FirstService;

public class MainActivity extends AppCompatActivity {

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



    //开启服务
    public void startServiceClick(View view) {
        Intent intent = new Intent();
        intent.setClass(this,FirstService.class);
        startService(intent);
    }

    //停止服务
    public void stopServiceClick(View view) {
        Intent intent = new Intent();
        intent.setClass(this,FirstService.class);
        stopService(intent);
    }
}

 

posted @ 2021-09-10 09:36  涂妖教  阅读(123)  评论(0)    收藏  举报