调用onDestroy函数时,Receiver未注册错误

时间:2014-12-06 08:40:45

标签: android broadcastreceiver

当我创建扩展BrodcastReceiver并注册它的类时。 MainActivity中的错误Unable to destroy activity, Receiver not registered: null onDestroy()函数调用unregisterReceiver时。

的onCreate():

ConnectionChangeReceiver connectionChangeReceiver = new ConnectionChangeReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionChangeReceiver, filter);

的onDestroy():

@Override
protected void onDestroy() {
    Log.v("YourActivity", "onDestroy");
    unregisterReceiver(connectionChangeReceiver);
    super.onDestroy();
}

ConnectionChangeReceiver类:

public class ConnectionChangeReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive( Context context, Intent intent )
    {
        Toast.makeText(context, "CONN", Toast.LENGTH_SHORT).show();
    }
}

清单:UPDATE:添加<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

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

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


    <activity
        android:name="com.example.mamrezo.mapapp.MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".ConnectionChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

</application>

</manifest>

1 个答案:

答案 0 :(得分:1)

我始终register onStart中的接收者和unregister中的onStop。感谢这个答案,我知道这一点:https://stackoverflow.com/a/24391706/1203797

如果它仍然无法正常工作,只需将unregisterReceiver(connectionChangeReceiver);换成try-catch块即可,如上面发布的链接中所述。

或者您可以在manifest中注册,例如:

    <receiver android:name=".ConnectionChangeReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>