android 服务的绑定调用

任务: 请求一个服务器,没五秒Ping一次,检查能否Ping通

服务类:

需要注意的的是:1 利用代理模式,向Activity抛出一个Binder的子类

                             2 记得在文件清单中声明服务类                            

                     <service android:name="com.example.servicetest.ReceiverService" />

                             3 请求服务器地址需要声明权限

                     <uses-permission android:name="android.permission.INTERNET" />

PingService

package com.example.servicebind;

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;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by ls on 2016/9/18.
 * 绑定服务 利用的是代理类的模式
 * 每隔五秒钟检查服务器能否拼通,如果ping不同,报错,两秒超时,报错
 */
public class PingService extends Service {
    private static final String TAG = "PingService";
    //继承Binder返回当前服务的绑定(代理类
    public  class MyBinder extends Binder{
        //在binder内可以调用服务中的方法
        public boolean checkAccess() {
            return isCheck();
        }
    }
    //返回远程服务的状态值
    public boolean isCheck() {
        return access;
    }
    //远程服务可以访问的状态值
    private boolean access =  true;
    //定义一个标识当执行ondestroy() 时,线程中的whil()循环停止
    private boolean run =  true;
    //可以理解为经纪人代理(宋喆),服务绑定的模式理解其实就是代理模式
    //例如,你要找王宝强拍戏(服务),先去找他的经纪人代理(宋喆),经纪人可以调用艺人的一些方法,反馈给你
    MyBinder myBinder;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        myBinder = new MyBinder();//实例化代理类(先找到到宋喆
        //服务一启动就做远程服务器的Ping
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    String str = "http://192.168.56.1:8080/MyWeb/";
                    URL url = new URL(str);
                        while (run) {
                            try {
                                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                                conn.setRequestMethod("GET");//设置请求方式必须要大写
                                conn.setReadTimeout(2000);
                                conn.connect(); //Opens a connection to the resource.
                                access =  true;
                                Log.d(TAG, "run:  access  "+access);
                                Thread.sleep(5000);//每隔五秒请求一次
                            }
                            catch (Exception e) {
                                e.printStackTrace();
                                access =  false;
                                Log.d(TAG, "run:  access  "+access);
                                Thread.sleep(5000);//每隔五秒请求一次
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    access =  false;
                }
            }
        }.start();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //返回当前服务的绑定,这样就可以直接访问服务中的业务方法了,把代理人给你(Activity
        return myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        //return true 表示解除绑定并停止服务 默认是return false即是super.onUnbind(intent)
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        run = false;
    }
}
2 声明一个应用继承Application

目的:当应用程序一启动,就启动服务,确保服务长期运行

<span style="color:#6600CC;">package com.example.servicebind;

import android.app.Application;
import android.content.Intent;

/**
 * Created by ls on 2016/9/18.
 */
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent();
        intent.setClass(this, PingService.class);
        //应用程序一启动,就启动服务,这种方式可以确保服务长期运行
        startService(intent);
    }
}</span>
3Ma inActivity

目的:绑定服务,通过代理类调用服务中的方法

<span style="color:#6600CC;">package com.example.servicebind;

import android.app.Activity;
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 android.widget.Toast;

/**
 * Created by ls on 2016/9/18.
 * 绑定服务
 */
public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";
    //定义绑定的标识
    private boolean bound = true;
    //经纪人来了
    PingService.MyBinder myBinder;
    //服务的回调返回代理人(bindService是一个异步的过程
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ");
            //IBinder 是一个定义接口 子类是Binder MyBinder又继承Binder
            myBinder = (PingService.MyBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected:   only service be killed call");
        }
    };

    Intent intent = new Intent();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_servicebind);
        //窗体一启动,服务就启动/绑定
        intent.setClass(this, PingService.class);
        // 窗体启动就绑定服务
        // 使当前窗体可以调用服务中的业务,如果服务实例没有onCreate,那么就初始化服务并绑定
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    //绑定服务
    public void bind(View view) {
        //stopService(intent);
        //如果服务中没有onCreate就绑定服务
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    public void call(View view) {
        /*
    	// 绑定过程不能在调用时才执行(因为这是个异步过程)
    	Intent intent=new Intent();
    	intent.setClass(this, PingService.class);
    	bindService(intent, conn, BIND_AUTO_CREATE);
    	*/
        Toast.makeText(MainActivity.this,myBinder.checkAccess()+ "", Toast.LENGTH_SHORT).show();
    }
    //解绑
    public void unbind(View veiw) {
        unbindService(conn);
        //声明已经解除绑定
        bound = false;
    }

    //停止服务
    public void stop(View view) {
        stopService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //如果已经解绑了,就跳过
        if (bound)
            unbindService(conn);
    }
}</span>

4 activity_main.xml

<span style="color:#3366FF;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:onClick="bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="绑定服务" />
    <Button
        android:layout_marginTop="20dp"
        android:onClick="call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="调用服务" />
    <Button
        android:layout_marginTop="20dp"
        android:onClick="unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解除绑定" />
    <Button
        android:layout_marginTop="20dp"
        android:onClick="stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务" />
</LinearLayout></span>

























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独步秋风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值