在没有 Activity 的情况下使用 LocalBroadcastManager 使用另一个 class

Using LocalBroadcastManager without Activity using another class

这不起作用,我从来没有在接收器中收到消息。我已经工作了几个小时。我想做的是使用 LocalBroadcastManager 而不 Activity 使用另一个 AppContext class.

class 1

import android.content.Context;

public class AppContext extends Application {

    private static AppContext instance;

    public AppContext() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }

}

class 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);

我也遇到了同样的问题。 不要更改 class3 中的任何内容。我认为它是完美的。 在 class2 中,创建一个扩展 BroadcastReceiver 的内部 class。

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();

如果这对您有帮助,请告诉我!