Service的简单启动方式

1.什么是Service

Service是Android四大组件之一
Service是在后台运行,用户不可见,无法直接交互;
Service需要由其他程序启动;
Service可以跨平台调用。

2如何使用Service

1.startService:
    新建类继承Service;
    重写onCreate方法;
    实现onBind抽象方法;
    重写onStartCommand方法;
    重写onDestroy方法;
    在AndroidManifest中注册Service;
    在有Context环境中通过startActivity启动Service;
    在有Context环境中通过StopActivity启动Service;

2.bindService:
    新建类继承Service;
    实现onBild抽象方法;
    重写onCreate方法;
    重写onUnbind方法;
    在AndroidManifest中注册Service;
    在Context环境实现ServiceConnection接口;
    在有Context环境中通过bildActivity绑定Service;
    在有Context环境中通过unbildActivity解绑Service;

3.启动Service实例

startService内容
package com.example.practice;

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

public class MyService extends Service {
    public MyService() {

    }

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

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("0000000000000000","onStartCommand");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<=10;i++){
                    Log.e("Thread名字:"+Thread.currentThread().getName(),"$$$"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
        //本方法执行,服务就被启动,

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //当服务用不上了并要被销毁时,系统会调用本方法。
        Log.e("0000000000000000", "onDestroy");
    }

}
Activity代码
package com.example.practice;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class WActivity extends AppCompatActivity implements View.OnClickListener{
    private Button button;
    private Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_w);
        button=findViewById(R.id.start);
        button2=findViewById(R.id.finlish);
        button.setOnClickListener(this);
        button2.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(WActivity.this, MyService.class);
        switch (v.getId()){
            case R.id.start:
                intent.putExtra("StartedServiceTest", "StartedServiceTest");
                startService(intent);
                Log.e("111111","开始");
                break;
            case R.id.finlish:
                stopService(intent);
                Log.e("111111","结束");
                break;
        }

    }
}

bindService内容:

package com.example.json;

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

public class MService extends Service {
    private int count;
    private MyBinder binder = new MyBinder();
    private boolean stop;

    public class MyBinder extends Binder {
        public MService getservice() {
            return MService.this;
        }

    }

    public void fly() {
      //  new Thread(new MyThread()).start();
       Log.e("00000","开飞机 "+ count);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e("0000000000000", "onBind");
        return binder;

    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e("0000000000000", "onUnbind");
        return true;
    }

    @Override
    public void onCreate() {
        Log.e("0000000000000", "onCreate");

        super.onCreate();
    }

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

    @Override
    public void onRebind(Intent intent) {
        Log.e("0000000000000", "onRebind");
        super.onRebind(intent);
    }

    @Override
    public void onDestroy() {
        Log.e("0000000000000", "onDestroy");
        super.onDestroy();
        stop = true;
    }

    class MyThread extends Thread {
        public void run() {
            while (!stop) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
               // Log.e("0000000000000", "" + count);
            }
        }
    }
}

Activity:

package com.example.json;

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;
import android.widget.Button;

public class SerActivity extends AppCompatActivity implements View.OnClickListener {
    private MService service = null;
    private boolean isbound = false;
    private Button button;
    private Button button2;
    private Button button3;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isbound = true;
            MService.MyBinder myBinder = (MService.MyBinder) binder;
            service = myBinder.getservice();
            service.fly();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isbound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ser);
        button = findViewById(R.id.btn1);
        button2 = findViewById(R.id.btn2);
        button3 = findViewById(R.id.btn3);
        button.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
                Intent intent = new Intent(this, MService.class);
                bindService(intent, conn, BIND_AUTO_CREATE);
                break;
            case R.id.btn2:
                unbindService(conn);
                break;
            case R.id.btn3:
                Intent intent1=new Intent(SerActivity.this,LigeActivity.class);
                startActivity(intent1);
                break;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值