2016-11-27 90 views
0

我正在尝试编写BroadcastReceiver来检查Internet连接。但它不起作用。我的接收机是:启用移动连接的广播接收器不起作用

public class MobileDataOnBroadcastReceiver extends BroadcastReceiver{ 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d(MainActivity.TAG, "Broadcast received"); 
     Intent intent1 = new Intent(context, LoadPictureService.class); 
     context.startService(intent1); 
    } 
} 

当我尝试在MainActivity动态注册它,我得到“Cannot resolve symbol conn”:

当我尝试在Manifest进行注册,BroadcastReceiver只是不启动在所有。我Manifest

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.aleksandr.homework3"> 

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 

     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <receiver android:name=".MobileDataOnBroadcastReceiver"> 
      <intent-filter> 
       <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 
      </intent-filter> 
     </receiver> 
    </application> 
</manifest> 

有关于这一主题的堆栈溢出了不少问题,但没有人回答我的问题。为什么我不能动态注册BroadcastReceiver?为什么在Manifest时不工作?我应该怎么做才能使它工作?

回答

2

您需要使用this API动态注册接收器,注意第二个参数是IntentFilter。 你可以试试下面的代码

IntentFilter filter = new IntentFilter(); 
filter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION); 
// this is the constant value android.net.conn.CONNECTIVITY_CHANGE 
registerReceiver(receiver, filter); 

还要注意的是,如果你的目标API 24或以上,那么你将不会得到这个广播是通过清单项注册。

参照this

面向Android 7.0的应用程序不会收到CONNECTIVITY_ACTION广播,即使它们有清单条目以请求通知这些事件。如果运行中的应用程序请求使用BroadcastReceiver进行通知,它们仍然可以在其主线程上监听CONNECTIVITY_CHANGE。

一般来说,动态注册的接收机是这种广播的方式。只要记住在组件生命周期状态发生变化或不再需要广播时适当地取消注册它们。

+1

欲了解更多信息,请查看此视频:https://www.youtube.com/watch?v = vBjTXKpaFj8 –