3

我有一个BroadcastReceiver的问题。如果我宣布在清单中的行动是这样的:Android BroadcastReceiver:无法实例化接收器 - 没有空的构造函数

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

凡在strings.xml中我有:

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

一切正常。但是,如果我将其更改为:

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

我有这样的例外,因为接收器被称为:

了java.lang.RuntimeException:无法实例化接收机com.app.activity.observer.DataEntryObserver:JAVA。 lang.InstantiationException:无法实例化类com.app.activity.observer.DataEntryObserver;没有空的构造

我会继续工作版本,但在Play商店不允许我发布的应用程序,因为它需要一个字符串值,而不是变量@字符串/ ..

我的接收器是在OuterClass并且被定义为:

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(); 

} 

}

回答

9

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

这样的:

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

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

+2

使BroadcastReceiver成为静态类是糟糕的体系结构。它会阻止你调用其中的很多方法,包括'startActivity' –

-4

需要空的构造

public DataEntryObserver() { 
    this.dLoader = null; 
} 
+1

你知道为什么吗? –

+0

这不是一个空的构造函数。 – Roberto

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(); 

    } 
} 

虽然我不知道,如果保持非空的构造会产生相同的错误。如果是这样,你将不得不删除它。

相关问题