一、开启服务的时候,如果我们是通过bindService来绑定服务并且要向服务传递数据,可以直接在Intent中设置bundle来达到效果,但是如果是我们需要从服务中返回一些数据到Activity中的时候,实现起来就有各种各样的方法,比如说使用回调,使用广播等等,今天说的是使用回调的方法。

 

二、测试源码

1、布局文件\interfaceservicecallback\app\src\main\res\layout\activity_main.xml代码如下:

 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvOut"
        android:layout_width="wrap_content"
        android:layout_height="150dp"
        android:textSize="50dp"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnBindService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start service"
        tools:layout_editor_absoluteX="129
        tools:layout_editor_absoluteY="128dp" />

</android.support.constraint.ConstraintLayout>

 

2、com/example/interfaceservicecallback/MainActivity.java

package com.example.interfaceservicecallback;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {

        private TextView tvOut;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tvOut = (TextView) findViewById(R.id.tvOut);
            findViewById(R.id.btnBindService).setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            bindService(new Intent(this, MyService.class), this, BIND_AUTO_CREATE);
        }        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyService.Binder binder = (MyService.Binder) service;
            MyService myService = binder.getService();
            myService.setCallback(new MyService.Callback() {
                @Override
                public void onDataChange(String data) {
                    Message msg = new Message();
                    msg.obj = data;
                    handler.sendMessage(msg);
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                tvOut.setText(msg.obj.toString());
            }
        };
    }

 

 

 

3、service文件com/example/interfaceservicecallback/MyService.java

package com.example.interfaceservicecallback;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.support.annotation.Nullable;
import android.util.Log;
public class MyService extends Service {
    private boolean connecting = false;
    private Callback callback;

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

    public class Binder extends android.os.Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    @Override    public void onCreate() {
        super.onCreate();
        connecting = true;
        new Thread(new Runnable() {

            @Override
            public void run() {
                int i = 0;
                while (connecting == true) {
                    i++;
                    if (callback != null) {
                        callback.onDataChange(i + "");
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public static interface Callback {
        void onDataChange(String data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        connecting = false;
    }
}

4、声明service,app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.interfaceservicecallback">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyService">
        </service>
    </application>

</manifest>

 

 

5、app运行效果

ios block回调函数 app回调_android