2011-12-06 39 views
5

在我的應用程序中,我需要使用startActivity來查看文件的內容,或使用默認應用程序來打開某個文件,但有時android系統可能不會安裝所需的應用程序。如何處理ActivityNotFoundException?

我的問題是如何處理這個異常。我想烤麪包,而不是FC ..

有什麼建議嗎? THX

+0

。爲了解決這種類型的異常,您必須將您的活動註冊到清單文件中。無需註冊註冊文件中的每個活動,但是當您使用startActivity時,您必須註冊您的活動。 – anddev

+0

行..我試過了。有用。 THX – xuyao

+0

看看我編輯的答案。謝謝.. – user370305

回答

11

只需簡單地補充說,活動在您的清單文件..

一樣,

<activity android:name=".ActivityName" 
        android:label="@string/app_name"> 
     </activity> 

編輯:

我們趕上ActivityNOtFoundException把你的代碼中,

try { 

    // Your startActivity code wich throws exception 
} catch (ActivityNotFoundException activityNotFound) { 

    // Now, You can catch the exception here and do what you want 
} 

注意:當您發現此問題時要小心ActivityNotFound異常但您無法修改清單文件以運行時間,意味着一旦遇到異常,並且您希望在運行時添加此活動標記,則不能。

+0

對不起老兄..這不是我所需要的。我想讓系統決定運行哪個活動。 – xuyao

1

如果你想顯示錯誤敬酒然後

try { 
    startActivity(intent); 

} catch (ActivityNotFoundException e) { 
    // TODO: handle exception 
    //Show Toast... 
} 

錯誤發生,因爲活動沒有在清單文件中提及。

<activity android:name=".yourActivity" 
     android:label="@string/app_name"> 
</activity> 
+0

正確〜謝謝〜 – xuyao

2

我認爲你的問題更多:「我怎樣才能捕捉到某種異常並防止強制崩潰」。 這是你如何在代碼中做到這一點:

try { 
    // here is your code that can potentially throw the exception and the force crash 
} catch (ActivityNotFoundException activityNotFound) { 
    Toast.makeText(this, "your error message", Toast.LENGTH_SHORT).show(); 
    // maybe also log the exception, for future debugging? 
} 

警告,不要濫用這一點:這是危險的「默默吞下」異常,可以使您的應用程序不穩定,引進怪異,難以調試行爲。

+0

謝謝,它適用於我。 – xuyao

7

如果你要處理的異常,那麼你可以使用try/catch語句並處理它,您可以使用resolveActivity方法

if (intent.resolveActivity(getPackageManager()) != null) { 
     startActivity(intent); 
    }else { 
     Toast.makeText(this,"No suitable app found!",Toast.LENGTH_SHORT).show(); 
    }