使用不带Activity的LocalBroadcastManager使用另一个类

时间:2017-02-16 02:03:30

标签: java android localbroadcastmanager

这不起作用,我从未在接收器中收到消息。我已经工作了几个小时。我正在尝试做的是使用LocalBroadcastManager而不使用另一个AppContext类的Activity。

第1课

import android.content.Context;

public class AppContext extends Application {

    private static AppContext instance;

    public AppContext() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }

}

第2课

@Override
public void onResume() {

    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //receive your message here

            String message = intent.getStringExtra("message");
            Log.d("receiver", "Got message: " + message);

            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

        }

    };

    LocalBroadcastManager.getInstance(AppContext.getContext()).registerReceiver(receiver,
            new IntentFilter("custom-event-name"));

CLASS3

                Log.d("sender", "Broadcasting message");
                Intent intent = new Intent("custom-event-name");
                // You can also include some extra data.
                intent.putExtra("message", "99999");
                LocalBroadcastManager.getInstance(AppContext.getContext()).sendBroadcast(intent);

1 个答案:

答案 0 :(得分:1)

我也有同样的问题。 不要改变第3课中的任何内容。我觉得它很完美。 在class2中,创建一个扩展BroadcastReceiver的内部类。

private class Class2Receiver extends BroadcastReceiver 
{
        @Override
        public void onReceive(Context context, Intent intent) 
{
            Class2.this.class2Refresh();
         }
    }

// class2Refresh():在此方法中接收您的消息

在class2中,onResume()方法,实例化如下:

Class2 class2Rec=new Class2.Class2Receiver();
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(class2Rec,new IntentFilter("custom-event-name"));
        class2Refresh();

请告诉我这是否有帮助!