4

I have a problem with a BroadcastReceiver. If I declare the action in the manifest in this way:

    <receiver android:name="com.app.activity.observer.DataEntryObserver" >
        <intent-filter>
            <action android:name= "@string/action_db_updated" />
        </intent-filter>
    </receiver>

where in the strings.xml I have:

       <string name="action_db_updated">com.app.DB_UPDATED</string>

everything works well. But if I change it to:

    <receiver android:name="com.app.activity.observer.DataEntryObserver" >
        <intent-filter>
            <action android:name= "com.app.DB_UPDATED" />
        </intent-filter>
    </receiver>

I have this exception as the receiver is called:

java.lang.RuntimeException: Unable to instantiate receiver com.app.activity.observer.DataEntryObserver: java.lang.InstantiationException: can't instantiate class com.app.activity.observer.DataEntryObserver; no empty constructor

I would keep the working version but the Play store doesn't allow me to publish the app because it expects a string value and not a variable @string/..

my receiver is an outerclass and is defined as:

   public class DataEntryObserver extends BroadcastReceiver{

private AppUsageLoader dLoader;


public DataEntryObserver(AppUsageLoader dLoader) {
    this.dLoader = dLoader;

    IntentFilter filter = new IntentFilter(
            ReaLifeApplication.ACTION_DB_UPDATED);
    dLoader.getContext().registerReceiver(this, filter);
}


@Override
public void onReceive(Context arg0, Intent arg1) {

    // Tell the loader about the change.
    dLoader.onContentChanged();

}

}

4

3 回答 3

10

使该类成为静态类,否则它会被“视为”为原始包含类实例的一部分。

因此:

public static class DataEntryObserver extends BroadcastReceiver{
public DeviceAdminSampleReceiver() {
            super();
        }
...

https://stackoverflow.com/a/10305338/1285325

于 2015-01-21T11:40:43.123 回答
5

你需要一个像这样的空构造函数:

public class DataEntryObserver extends BroadcastReceiver{

    private AppUsageLoader dLoader;

    // Empty constructor
    public DataEntryObserver() { }

    public DataEntryObserver(AppUsageLoader dLoader) {
        this.dLoader = dLoader;

        IntentFilter filter = new IntentFilter(
                ReaLifeApplication.ACTION_DB_UPDATED);
        dLoader.getContext().registerReceiver(this, filter);
    }


    @Override
    public void onReceive(Context arg0, Intent arg1) {

        // Tell the loader about the change.
        dLoader.onContentChanged();

    }
}

虽然我不确定保留非空构造函数是否会产生相同的错误。如果是这样,您将不得不将其删除。

于 2014-08-27T00:32:19.707 回答
-4

需要清空构造函数

public DataEntryObserver() {
    this.dLoader = null;
}
于 2014-02-07T03:22:48.237 回答