接收器广播不工作虽然发送广播正在工作

问题描述 投票:0回答:1

Android Studio:3.0,Android Marshmallow

SendBroadcast:

package com.example.android.sendbroadcast;
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}
public void onsendbroadcast(View view){
    Log.v("Inside","OnCLICK");
    Intent intent=new Intent();
    Log.v("Intent","Created");
    intent.setAction("com.example.android.sendbroadcast");
    Log.v("Action","Set");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    sendBroadcast(intent);
    Log.v("Broadcast","Sent");
}
}

接收广播

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
public MyReceiver(){

}
@Override
public void onReceive(Context context, Intent intent) {
    Log.v("Inside","Reciever");
    Toast.makeText(context,"Broadcast Recieved",Toast.LENGTH_LONG).show();

}
}

Android Manifest.xml

 <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">
    <receiver
        android:name=".MyReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.example.android.sendbroadcast"></action>

        </intent-filter>

    </receiver>
</application>

以上发送广播正常运行。我甚至用日志检查了它。但接收广播没有运行。没有显示toast / log消息。是什么原因?

java android broadcast android-broadcast android-broadcastreceiver
1个回答
0
投票

广播可以在代码的任何部分中使用,您可以在其中获取Context实例。但是,要接收,您必须侦听特定的广播,这可以通过简单的IntentFilter完成,然后您可以使用给定的intent过滤器注册BroadcastReceiver。示例实现如下所示;

要发送一个简单的广播,我使用Context对象在这里发送它(片段和其他一些类需要):

Intent in = new Intent(Constants.NETWORK_CHANGE);
in.putExtra(Constants.NETWORK_STATE, Constants.DISCONNECTED);
context.sendBroadcast(in);

下面还详细说明了一种简单的接收方式:

首先,创建一个BroadcastReceiver实例

private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getStringExtra(Constants.NETWORK_STATE).equals(Constants.DISCONNECTED)) {
                //do something here
            }
        }
    };

接下来,使用IntentFilter注册BroadcastReceiver,在可执行类(Fragment,Activity,Service或Applcation类)的onCreate或onResume方法中有一个好处:

@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, new IntentFilter(Constants.NETWORK_CHANGE));
    }

Intent Filter是你在应用程序中获取适当调用的原因,因为android会在设备上发送大量意图。

© www.soinside.com 2019 - 2024. All rights reserved.