在AsyncTask中管理异常

时间:2015-11-02 09:42:51

标签: android exception exception-handling android-asynctask

我有这段代码:

Timer

这是from threading import Thread from time import sleep def call_at_interval(period, callback, args): while True: sleep(period) callback(*args) def setInterval(period, callback, *args): Thread(target=call_at_interval, args=(period, callback, args)).start() def hello(word): print("hello", word) setInterval(10, hello, 'world!') 方法签名:

 public void remote(final Backup backup) {
        local(backup);
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                BackupSendInfo sendInfo = new BackupSendInfo()
                        .setFile(getLastBackup()) // <---
                        .setFileName(getBackupName(backup))
                        .setBackup(backup)
                        .setDeviceId(device)
                        .setApp(config.getAppName());
                fileSender.send(sendInfo);
            }
        });
    }

正如您所看到的,它会抛出getLastBackup,但我无法在private File getLastBackup() throws BackupException; 方法签名中添加BackupException延期,因为它位于另一个帖子中。

我该如何处理这种情况? 我希望throws BackuPException方法抛出BackupException

1 个答案:

答案 0 :(得分:0)

我得到了解决方案。也许,它不是最好的。

我在AsyncTask之外得到lastBackup,这样我就可以声明throws BackupException

 public void remote(final Backup backup) throws BackupException {
        local(backup);
        final File lastBackup = getLastBackup();
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                BackupSendInfo sendInfo = new BackupSendInfo()
                        .setFile(lastBackup)
                        .setFileName(getBackupName(backup))
                        .setBackup(backup)
                        .setDeviceId("Desconocido") //TODO leer dispositivo del fichero deviceName
                        .setApp(config.getAppName());
                fileSender.send(sendInfo);
            }
        });
    }