《Android那些事》——Demo浅析Service

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zzp961224/article/details/72773075

Service概念及用途[概念为转载]:

A service is an application component that can perform long-running operations in the background and does not provide a user interface。

通常service用来执行一些耗时操作,或者后台执行不提供用户交互界面的操作,例如:下载、播放音乐。


Service 中的几个主要步骤:

1.startService

2.stopService

3.bindService

4.unbindService


以下是Demo:

MainActivity.class

public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {

    private Button start_Service, stop_Service, binder_Service, unbinder_Service, getService;
    private Intent intent;

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

        start_Service = (Button) findViewById(R.id.start);
        stop_Service = (Button) findViewById(R.id.stop);
        binder_Service = (Button) findViewById(R.id.bind);
        unbinder_Service = (Button) findViewById(R.id.unbind);
        getService = (Button) findViewById(R.id.getService);

        start_Service.setOnClickListener(this);
        stop_Service.setOnClickListener(this);
        binder_Service.setOnClickListener(this);
        unbinder_Service.setOnClickListener(this);
        getService.setOnClickListener(this);

        intent = new Intent(MainActivity.this, MyService.class);
    }

    @Override
    //startService() 的调用者与服务没有联系,即使调用者退出了,服务仍然运行,
    //而bindService() 的调用者与服务绑在一起,调用者一旦退出了,服务也随即终止掉。
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:
                //每次调用startService(Intent)的时候,
                // 都会调用该Service对象的onStartCommand(Intent,int,int)方法,
                // 然后在onStartCommand方法中做一些处理。
                //另外如果一个 Service 已经被启动,其他代码再试图调用 startService() 方法,
                // 是不会执行Service中 onCreate() 的,但会重新执行一次 onStart() 。
                startService(intent);
                break;
            case R.id.stop:
                //当调用startService()而没有调用bindService() 时,stopService可以直接停止服务
                //当调用startService()同时也调用了bindService()时,stopService是不能停止在后台工作的service的,
                //除非调用unbindService()或者强制退出客户端。
                stopService(intent);
                break;
            case R.id.bind:
                //绑定service
                //bindService() 方法的意思是,把这个 Service 和调用 Service 的客户类绑起来,
                // 如果调用这个客户类被销毁,Service 也会被销毁。
                //bindService() 方法执行后 Service 会回调上边提到的 onBind()方法,
                // 你可以从这里返回一个实现了 IBind 接口的类,在客户端操作这个类就能和这个服务通信了,
                // 比如得到 Service 运行的状态或其他操作。如果 Service 还没有运行,
                // 使用这个方法启动 Service 就会调用Service中 onCreate() 方法而不会调用 onStart()。
                bindService(intent,this,BIND_AUTO_CREATE);
                break;
            case R.id.unbind:
                //解除绑定
                unbindService(this);
                break;
            case R.id.getService:
                Toast.makeText(MainActivity.this,
                        "当前service的值为:" + myService.getIndex(), Toast.LENGTH_SHORT).show();
                break;
        }
    }

    //如何得到service
    private MyService myService;

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        //当调用bindService方法后就会回调Activity的onServiceConnected,
        // 在这个方法中会向Activity中传递一个IBinder的实例,Acitity需要保存这个实例
        //在Service中需要创建一个实现IBinder的内部类(这个内部类不一定在Service中实现,但必须在Service中创建它)。
        //在OnBind()方法中需返回一个IBinder实例,不然onServiceConnected方法不会调用。
        Toast.makeText(MainActivity.this, "onServiceConnected", Toast.LENGTH_SHORT).show();
        MyService.MyBinder myBinder = (MyService.MyBinder) service;
        myService = myBinder.getMyService();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}

MyService.class

public class MyService extends Service {

    private Timer timer;
    private TimerTask timerTask;
    private int index = 0;

    @Nullable
    //与activity进行绑定
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    //得到binder对象
    private MyBinder binder = new MyBinder();

    //自定义一个类继承Binder实现通信
    public class MyBinder extends Binder {
        //获得当前Service的状态
        public MyService getMyService() {
            return MyService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //onStartCommand有4种返回值
        //START_STICKY
        //START_NOT_STICKY
        //START_REDELIVER_INTENT
        //START_STICKY_COMPATIBILITY
        startTimer();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    //开始执行Timer
    public void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                index++;
                
            }
        };
        timer.schedule(timerTask, 1000, 1000);
    }

    //停止Timer的执行
    public void stopTimer() {
        timer.cancel();
    }

    //实现可读性
    public int getIndex() {
        return index;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.usingservice.MainActivity">


    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="startService" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stopService" />

    <Button
        android:id="@+id/bind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bindService" />

    <Button
        android:id="@+id/unbind"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="unbindService" />

    <Button
        android:id="@+id/getService"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="getService" />
</LinearLayout>

UI:


猜你喜欢

转载自blog.csdn.net/zzp961224/article/details/72773075