Android 在 class 和 activity 之间广播

Android broadcast between class and activity

我的接收器坏了。问题在 class 和 activity 之间。我正在尝试从 class 向 activity 发送消息,但无法正常工作... class 将与两个活动通信,一次一个...

我的广播代码(在activity里面):

public class MainActivity extends Activity{

BroadcastReceiver receiver;
IntentFilter filter;

private void init() {
        try {

            ...

            receiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if(action.equals("HAS_CONECT")){
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(getApplicationContext(), "IS CONECTED!", Toast.LENGTH_LONG).show();
                    }
                    else if(action.equals("ARRIVES")){
                        Toast.makeText(getApplicationContext(), "HAS ARRIVE!!!", Toast.LENGTH_LONG).show();
                    }
                }

            };

            filter = new IntentFilter("HAS_CONECT");
            registerReceiver(receiver, filter);
            filter = new IntentFilter("ARRIVES");
            registerReceiver(receiver, filter);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

...
}

还有我的代码class:

public void adviseActivity(){
    try {
        Intent i = new Intent("MESSAGE");
        i.putExtra("msg", "DATA ARRIVE");
        i.setAction("ARRIVES");
        context.sendBroadcast(i);

    } catch (Exception e) {
        System.out.print(e);
    }
}

问题出在您的 onReceive 方法中,您正在查找错误的操作。您设置的操作是 MESSAGE,但您要查找的操作 onReceiveHAS_CONECTARRIVES。 更正以下代码:

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if(action.equals("MESSAGE")){
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(getApplicationContext(), "IS CONECTED!", Toast.LENGTH_LONG).show();
                }
            }