WakefulBroadcastReceiver获取java.lang.ClassNotFoundException

时间:2014-01-13 15:15:35

标签: android android-intent broadcastreceiver

在我的Android项目中,我有一个Service类:

public class MyService extends Service{
   ...

   //Defined a WakefulBroadcastReceiver as a inner static class
   public static class DeviceRebootReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
              //Do something when user reboot the device
        }
  }

}

如上所述,我在WakefulBroadcastReceiver课程中将MyService定义为内部静态类。当用户重启他/她的设备时,该接收器接收广播。

我的AndroidManifest.xml如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.project"
    android:versionCode="1"
    android:versionName="2.1" >

   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.WAKE_LOCK" />
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

   <application
     ...>
      <activity ...> ... </activity>

      <service android:name="com.my.project.MyService"
               android:exported="false"/>

       <receiver
            android:name="com.my.project.MyService$DeviceRebootReceiver"
          >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
   </application>
</manifest>

但是,当我运行我的应用程序&amp;重新启动设备后,我的logcat显示错误:

Unable to instantiate receiver com.my.project.MyService$DeviceRebootReceiver: 
java.lang.ClassNotFoundException:  com.my.project.MyService$DeviceRebootReceiver in loader dalvik.system.PathClassLoader[/data/app/com.my.project-1.apk]

为什么我的接收器类无法被系统加载?

=====更新==

我还尝试将DeviceRebootReceiver作为单独的类( DeviceRebootReceiver.java ),并将AndroidManifest.xml更改为:< / p>

 <application...>
    <receiver
      android:name="com.my.project.DeviceRebootReceiver"
          >
           <intent-filter>
               <action android:name="android.intent.action.BOOT_COMPLETED" />
           </intent-filter>
     </receiver>
</application>

但我仍然在logcat中遇到类似的错误:

java.lang.RuntimeException: Unable to instantiate receiver com.my.project.DeviceRebootReceiver: java.lang.ClassNotFoundException

1 个答案:

答案 0 :(得分:3)

我遇到了同样的问题并解决了它。

关于 android-support-v4.jar 库,你应该只在项目的libs文件夹下有官方和更新的库(从ANDROID_SDK / extras / android / support /复制)和 Android私有库在项目的Java Build Path中检查。例如,我还有 ClassNotFoundException 因为我的项目使用了另一个库的 android-support-v4.jar ActionBarSherlock )甚至使用我的java构建路径中包含的官方android-support-v4.jar,所以我取消选中ActionBarSherlock项目的 Android私有库以避免这种冗余。