I’m currently writing an application for the Android platform that requires a mounted SD card (or ExternalStorage). I know that it might not be the best way to require something like that, but the application will work with quite a lot of data, and I don’t even want to think about storing that on the device’s storage.
Anyway, to ensure that the application won’t run without the external storage, I do a quick check in the activity’s onCreate
method. If the card is not mounted, I want to display an error message and then quit the application.
My current approach looks like this:
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
setContentView( R.layout.main );
try
{
// initialize data storage
// will raise an exception if it fails, or the SD card is not mounted
// ...
}
catch ( Exception e )
{
AlertDialog.Builder builder = new AlertDialog.Builder( this );
builder
.setMessage( "There was an error: " + e.getMessage() )
.setCancelable( false )
.setNeutralButton( "Ok.", new DialogInterface.OnClickListener()
{
public void onClick ( DialogInterface dialog, int which )
{
MyApplication.this.finish();
}
} );
AlertDialog error = builder.create();
error.show();
return;
}
// continue ...
}
When I run the application, and the exception gets raised (I raise it manually to check if everything works), the error message is displayed correctly. However when I press the b开发者_Python百科utton, the application closes and I get an Android error, that the application was closed unexpectedly (and I should force exit).
I read some topics before on closing an application, and I know that it maybe shouldn’t happen like that. But how should I instead prevent the application from continuing to run? How do you close the application correctly when an error occurs?
But how should I instead prevent the application from continuing to run?
Finishing your current activity should be fine, as you are doing today.
How do you close the application correctly when an error occurs?
You don't. You close the component (activity, service, etc.). If this activity needs the SD card, and the SD card is unavailable, finish the activity.
Generally speaking, the less you think of an Android "application" and more of your APK having a loosely-coupled basket of components, the better.
精彩评论