活动与服务间通信

实现活动控制服务

package com.example.servicetest;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button  startService ;
    private  Button stopService ;
    private Button  bindService ;
    private  Button unBindService ;
    private  MyService.DownloadBinder  downloadBinder ;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) { //绑定服务时调用
            downloadBinder = (MyService.DownloadBinder) service ;//调用了服务里的方法,实现控制服务
            downloadBinder.startDownload();
            downloadBinder.getProgress() ;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {//解除绑定事调用

        }
    };
    @Override

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

        startService = (Button)findViewById(R.id.start_service);
        stopService = (Button)findViewById(R.id.stop_service);
        bindService = (Button) findViewById(R.id.bind_service);
        unBindService = (Button) findViewById(R.id.UnBind_service);

        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unBindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start_service:
                Intent startIntent = new Intent(this , MyService.class);
                startService(startIntent);//启动服务
                break;
            case R.id.stop_service:
                Intent stopIntent = new Intent(this,MyService.class);
                stopService(stopIntent);//停止服务
                break;
            case  R.id.bind_service:
                Intent bindIntent = new Intent(this , MyService.class);
                bindService(bindIntent,connection , BIND_AUTO_CREATE);//绑定服务 第三个参数表示活动和服务绑定后自动创建服务 onCreate()会执行 但onStartCommand()
                //不会执行.
                break;
            case R.id.UnBind_service:
               // Intent stopIntent1 = new Intent(this,MyService.class); 
                // 我们可能对一个服务及调用了startService(),又调用了bindService(),
                // 这时需要同时调用stopService()和unbindService()方法,onDestory()才会执行
               // stopService(stopIntent1);//停止服务
               unbindService(connection);//解绑服务
                break;
            default:
                break;
        }
    }
}

package com.example.servicetest;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyService extends Service {
   private DownloadBinder mBinder = new DownloadBinder();
    class DownloadBinder extends Binder {
        public void startDownload(){
            Log.d("Myservice" , "--startDownload");
        }

        public int getProgress(){
            Log.d("Myservice" , "--getProgress executed");
            return 0;
        }

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent){
        return  mBinder;
    }

    @Override
    public void onCreate() { //创建服务时调用
        Log.d("Myservice" , "--OnCreate  executed");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) { //每次开启服务时调用
        Log.d("Myservice" , "--onStartCommand  executed");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() { //销毁服务时调用
        Log.d("Myservice" , "--onDestroy  executed");
        super.onDestroy();
    }



}
   <service android:name=".MyService">

        </service>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/start_service"
        android:text="Start Service"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/stop_service"
        android:text="Stop service"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/bind_service"
        android:text="Bind Service"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/UnBind_service"
        android:text="UnBind service"/>

</LinearLayout>

总结:
只要调用startService,就会回调onStartCommand()(假如该服务未被创建过,onCreate()会先于onStartCommand()执行),停止服务只需调用一次stopService()或stopSelf()方法,服务就会停下来,无论开启多少次startService();

使用bindService()获取服务的持久连接,会回调服务中的onBind()方法,onBind()返回IBind()对象的实例,可以自由和服务进行通信了。

我们可能对一个服务及调用了startService(),又调用了bindService(),这时需要同时调用stopService()和unbindService()方法,onDestory()才会执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值