【问题标题】:best practice for handling exceptions in Background threads in Android apps在 Android 应用程序的后台线程中处理异常的最佳实践
【发布时间】:2015-09-30 10:36:29
【问题描述】:

我的后台线程中有多个 try/catch 块,用于初始化和加载数据/DB。 起初我只是将throw new RuntimeException( e ); 放在了 catch 中,但我认为我应该处理它们而不是仅仅扔掉它们,希望有人来处理它.. 在这种情况下,顺便说一下,应用程序只会崩溃。

处理这些情况的最佳做法是什么(在后台线程中),尤其是在 Android 应用中?

谢谢。

编辑:

private static class DatabaseLoaderHelper extends SQLiteOpenHelper 
{
    private static final int DB_VERSION = 1;
    private static String DB_PATH = "" ;

    private DatabaseLoaderHelper( WeakReference<Context> contextWrapper )
    {
        super( contextWrapper.get(), DB_NAME , null, DB_VERSION );
        DB_PATH = contextWrapper.get().getDatabasePath( DB_NAME ).getAbsolutePath();

        boolean dataBaseExist = checkDatabaseExist( contextWrapper );
        if ( !dataBaseExist )
        {
            try
            {
                copyDatabase( contextWrapper.get() );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );

            }
        }
    }

    private void copyDatabase( Context context ) throws IOException
    {
        InputStream myInput = null;
        String outFileName = null;
        OutputStream myOutput = null;

        try
        {
            myInput = context.getAssets().open( DB_NAME );

            outFileName = DB_PATH;

            myOutput = new FileOutputStream( outFileName );

            byte[] buffer = new byte[ 1024 ];
            int length;

            while ( ( length = myInput.read( buffer ) ) > 0 )
            {
                myOutput.write( buffer, 0, length );
            }
        }      
        catch( IOException e )
        {

        }
        finally
        {
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }
    }

    private boolean checkDatabaseExist( WeakReference<Context> contextWrapper )
    {

        File dbFile = new File( DB_PATH + DB_NAME );
        if ( !dbFile.getParentFile().exists() )
        {
            dbFile.getParentFile().mkdir();
            return false;
        }
        return dbFile.exists();
    }

【问题讨论】:

  • 这取决于异常的类型以及可能导致它发生的原因。真的没有万能的答案。也许如果您更改问题并提供更具体的信息,我们可以建议一种适合该情况的方法。例如,这只是在您自己的应用程序中,还是您希望第三方通过某些 IPC 机制(意图、绑定服务、ContentProvider 等)调用您的应用程序/使用您的数据?当这些异常发生时,你有合适的后备方案吗?这些异常真的发生了吗?等
  • 我在帖子中添加了一个程序简介,其中有一些我需要以某种方式处理的异常。它是 SQLOpenHelper 的子类,在 doInBackground() 中被初始化和调用。谢谢。顺便说一句,我也不知道在最后我关闭资源文件的地方该做什么。例如,如果 myOutput.close() 将引发异常 - myInput.close() 将不会被调用...我该如何解决这个问题?

标签: java android multithreading exception background


【解决方案1】:

如果您使用的是 AsyncTask,通常的做法是在 doBackground() 中捕获异常并将其分配给类成员 Exception 变量并在 onPostExecute() 中处理它。

【讨论】:

    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    相关资源
    最近更新 更多