2016-11-27 92 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 –