2013-12-22 29 views
-2

我目前正在開發應用程序的一部分,以便在設備啓動時啓動。我這樣做是出於一個很好的理由,爲了運行檢測移動的後臺進程,我並不試圖在用戶打開設備時向用戶發送垃圾郵件或向他們顯示界面。

我現在面臨的問題是,像這樣的錯誤,我沒有想法是什麼,它是:Android開發java.lang.RuntimeException

12-22 17:00:53.399: E/AndroidRuntime(1629): Process: com.dd.splash, PID: 1629 
12-22 17:00:53.399: E/AndroidRuntime(1629): java.lang.RuntimeException: Unable to instantiate receiver com.dd.splash.MyActivity: java.lang.ClassCastException: com.dd.splash.MyActivity cannot be cast to android.content.BroadcastReceiver 
12-22 17:00:53.399: E/AndroidRuntime(1629): Caused by: java.lang.ClassCastException: com.dd.splash.MyActivity cannot be cast to android.content.BroadcastReceiver 

這裏是錯誤的代碼片段

AndroidManifest.xml中

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

<receiver 
     android:enabled="true" 
     android:name=".MyActivity" 
     android:permission="android.permission.RECEIVE_BOOT_COMPLETED"> 

     <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
       <category android:name="android.intent.category.DEFAULT" /> 
     </intent-filter> 

</receiver> 

MyActivity.java

public class MyActivity { 
//The code that I want in the process will go here soon! 
} 

因此,我安裝了我的ap p,重啓我的設備,並收到錯誤消息,說我的應用程序意外停止。我查看正在運行的進程,並且該應用程序不會顯示在那裏,也不會顯示在緩存的進程中。問題是什麼?看起來錯誤是說這兩個文件無法通信。我想我會犯一個愚蠢的錯誤,如果有人可以請指出。

謝謝!

回答

1

的這個錯誤告訴你的一切:

java.lang.ClassCastException:com.dd.splash.MyActivity不能轉換到android.content.BroadcastReceiver

正如你已經證明,您的MyActivity代碼是:

public class MyActivity { 

} 

因此,您希望它成爲接收器,您需要擴大廣播接收器,並覆蓋其的onReceive()方法,像這樣:

public class MyActivity extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     //code to run when receiver fires  
    } 
} 
+0

看起來好一點,但即時得到這些錯誤:'多個標記在該行 \t - 廣播接收器不能被解析爲一個類型 \t - MyActivity類型必須實現繼承的抽象方法 \t BroadcastReceiver.onReceive(Context,Intent)' – pattyd

+0

同樣,錯誤告訴你你需要做什麼:覆蓋MyActivity中的onReceive(),如我的答案所示:) – Melquiades

+0

哦,等我拿到了!我需要正確的'import'行!謝謝你的幫助!但更快速的一點,我的應用程序不會顯示在運行過程中的任何想法?也許這是因爲它還沒有做任何事情? – pattyd