当Activity未聚焦时,BroadcastReceiver不起作用

时间:2019-06-27 12:34:33

标签: broadcastreceiver

我的广播接收器

public class ConnectionChangeReceiver extends BroadcastReceiver {

private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    Intent mIntent = new Intent(context, PlayerService.class);
    if (activeNetInfo != null && activeNetInfo.isConnectedOrConnecting()) {
        Log.i("TEST", "true");
            context.startService(mIntent);
        }
        listener.onConnected(true);
    } else {
        Log.i("TEST", "false");
        context.stopService(mIntent);
        listener.onConnected(false);
    }
}

interface OnConnectedListener {
    void onConnected(boolean isConnected);
}

void setOnConnectedListener(OnConnectedListener listener) {this.listener = listener;}

清单

<receiver android:name="com.vadimfedchuk1994gmail.radio.ConnectionChangeReceiver"
              android:label="NetworkConnection">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
        </intent-filter>
    </receiver>

活动中

registerReceiver(mConnectionChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

当我专注于活动时,接收者的工作就很好 但是活动不集中,在日志中不会传递有关更改网络连接的消息,例如Log.i(“ TEST”,“ true”); 我需要那个接收器一直在工作

0 个答案:

没有答案