Service和Fragment之间的通信及消息监听

Service和Fragment之间的通信及消息监听

前言

有些日子没写博客了,是因为我太忙了吗,不,不是这样的,我就是单纯的变懒了。

好了,言归正传。在开发中做消息推送之类的及时性比较长的项目时,我们常常会在项目中开一个service,在服务中开启一个socket和服务器保持长连接,服务器一旦有消息就将数据发送到客户端中的service中,这个时候我们就需要service和activity或者fragment之间的通讯了。

在网上搜索到的答案大部分都是在跳转或者开启的时候使用intent传递,也有一些方案是使用数据库或者文件在组件之间传递数据,但是这些方案都不够灵活,activity或者fragment中不能实时的监听到service中数据的变化。因此我在之前的项目中使用回调来解决service和activity之间的通讯问题,同理,在service和fragment之间通讯也是一样的。

上代码

首先创建一个接口ServiceCallBack,在接口中创建一个没有返回值的方法callback(String str)

package com.dimanche.test;

public interface ServiceCallBack {

    public void callback(String str);

}

然后创建一个service,在service里开启一个线程,这个线程每隔5秒向Handler中发送一次消息,模仿service从服务器中获取到新的消息向fragment发送消息,在这里声明ServiceCallBack 时一定要用static修饰,不然serviceCallBack会一直为空

package com.dimanche.test;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyService extends Service {
    private MyThread myThread;
    static ServiceCallBack serviceCallBack;

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

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e("Handler", "111");
            if (serviceCallBack != null) {
                Log.e("MyService", "我从山中来,种着兰花草");
                serviceCallBack.callback("我从山中来,种着兰花草");
            }

        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        myThread = new MyThread();
        myThread.start();
    }
	
	//注册回调函数
    public void setCallBack(ServiceCallBack serviceCallBack) {
        this.serviceCallBack = serviceCallBack;
        Log.e("MyService", "回调注册成功");
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(1);
            }

        }
    }
}

3、创建一个fragment,让fragment实现ServiceCallBack接口,在callback方法中的参数就是service中发送过来的字符串

package com.dimanche.test;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MyFragment extends Fragment implements ServiceCallBack {
    MyService myService;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        Log.e("MyFragment","onCreate");
        myService = new MyService();
        myService.setCallBack(this);
        return view;
    }

    @Override
    public void callback(String str) {
        Log.e("MyFragment",str);
        Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
    }
}

最后,在activity中加载fragment,开启service,还有就是service莫要忘了在清单文件中注册

getSupportFragmentManager().beginTransaction().add(R.id.framelayout, new MyFragment()).commit();
        startService(new Intent(MainActivity.this, MyService.class));

最后查看效果
在这里插入图片描述

结语

嗯,当然还可以用一些其他的开源框架,具体的没研究,有空再说吧
如果哪里有误还烦请指正呀
点击这里获取找到我,获取更多哦

QQ群:

image.png

微信公众号

分享小知识,记录你的小故事呀
微信公众号.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章