Service服务

2种方式启动服务
package com.bw.ffuwu;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private  Intent intent;
    private MyService.MyBinder binder;
    private ServiceConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //启动服务
    public void qidong(View view) {
        intent = new Intent(this,MyService.class);

        startService(intent);
    }
    //关闭服务
    public void xiaohui(View view) {
        stopService(intent);
    }
    //绑定方式启动服务
    public void bangqidong(View view) {
        Intent intent1 = new Intent(this,MyService.class);
         connection= new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                binder= (MyService.MyBinder) iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.i("qqq", "onServiceDisconnected: "+"异常时调用");
            }
        };

        bindService(intent,connection,BIND_AUTO_CREATE);

    }
    //解绑服务
    public void jiebang(View view) {
        unbindService(connection);
    }
    //调用服务的方法
    public void diao(View view) {
        binder.callshow();
    }


}
package com.bw.ffuwu;

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

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

    //创建
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("qqq", "onCreate: ");
    }

    //运行
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("qqq", "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    //销毁
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("qqq", "onDestroy: ");
    }

    class MyBinder extends Binder{
        public void callshow(){
            show();
        }
    }

    //
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("qqq", "onBind: ");
       return new MyBinder();
    }

    public void show(){
        Log.i("qqq", "show: ");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值