Android课堂学习笔记————Service

什么是Service

1.Service是Android四大组件之一,和Activity的级别相当
2.Service第可以长时间运行在后台的,是不可见是没有界面的组件
3.Service是运行在主线程中的
4.Service可以跨进程调用

如何使用Service

1.新建类继承Service
2.重写onCreate方法
3.实现onBind方法
4.重写onStartCommand方法
5.重写onDestroy方法
6.在AndroidManifest中注册Service
7.在有Context环境中通过startService启动Service
8..在有Context环境中通过stopService停止Service

代码展示

java代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  //定义两个按钮来向Service发信息
    private Button startBtn;
    private Button stopBtn;
    public  String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //绑定id与监听事件
        startBtn =  findViewById(R.id.start_service);
        stopBtn =  findViewById(R.id.stop_service);
        startBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.start_service:
                //和Activity一样都用Intent传值
                Intent startIntent = new Intent(this, MyService.class);
                //启动service用startService方法
                startService(startIntent);
                break;
            case R.id.stop_service:
                Intent stopIntent = new Intent(this, MyService.class);
                //停止service用stopService方法
                stopService(stopIntent);
                break;
            default:
                break;
        }
    }
}

继承Service类

public class MyService extends Service {
    public  String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        //定义log方法在后台打印
        Log.e(TAG, "onCreate() ++++++++++++++++++++++++++++++++++++++++++"+Thread.currentThread().getName());
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand() ++++++++++++++++++++++++++++++++++++++++");

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
       throw new UnsupportedOperationException("Not yet implemented");
    }
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值