在其他时间调用AsyncTask obj时遇到问题-Android

如何解决在其他时间调用AsyncTask obj时遇到问题-Android

| 在我的Activity类中,实现UINotifier,该类用于在调用TimerTask对象时通知Activity类。在我的doInBackground()中,我仅调用位于ASyncTask类(connectTask)中的函数。 onPostExecute被执行,最后,我调用了位于Activity类中的方法“ ReConnect()\”。 代码及其流程为:
// OF Interface UINotifier
@Override
public void notifyUI() {
    Log.i(TAG,\"GOT MESSAGE FROM MonitorConnection\");
    monitorTimer.cancel();
    Log.i(TAG,\"Preparing to Start\");
    PrepareToStartToConnect();
    //publishProgress(4);
    int status = 1;
    if (status == 1 || status == 2)
        ReConnect();
}

// Called on \"Connect\" button
private void ConnectClicked() {
    Log.i(TAG,\"Inside Connectclicked\");
    if (isConnectEligeble()) {
        Log.i(TAG,\"isConnectionEligible = true\");
        currentState= CONNECTING;
        connectTask = new ConnectTask();
        Log.i(TAG,\"CReated ins of ConnectTask\");
        connectTask.execute(\"\");
    }
}

private void ReConnect() {
    connectTask = null;

    if (HttpUtilities.checkInternetConnection()) {
        Log.i(TAG,\"ABOUT TO RE-CONNECT\");
        ConnectClicked();
    } else {
        Log.i(TAG,\"No Interne Mesage\");
        mMessage.setText(R.string.NO_INERNET);
    }
    return;
}

private void PrepareToStartToConnect() {
    monitorTimer = null;
    monitorConn = null;
    // Make all vars,objects to null   
}

// Start TimerTask & Timer object
private void StartTimer() {
    Log.i(TAG,\"Into Start Timer\");
    monitorConn = new MonitorConnection(this);   // new MonitorConnection(connectTask);
    monitorTimer = new Timer();
    monitorTimer.schedule(monitorConn,30000);
}


/**
 * ConnectTask  AsyncTask class that handles all activities to get connected to the server
 */
private class ConnectTask extends AsyncTask<String,Integer,Boolean> implements UINotifier {
    private ProgressDialog dialog = null;
    private UServer us = null;
    private VPNServer vs = null;
    private ConfigData cd = null;
    String serverHost = \"\",errorMsg = \"\"; 
    private int status = -1; // 0 Connected  1 = ReConnect  2 = Failed to Connect

    public ConnectTask() {
        dialog  = new ProgressDialog(StartUltimate.this);
        us  = servers.get(selectedRowIndex);
        vs = us.getVpnServer(selectedProtocol,selectedPort);
        serverHost = us.getServerHost();
    }

    private void disposeAll() {
        // Dispose all objs
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        Log.i(TAG,\"Into onPostExecute()\");
        if (result == false)
            mMessage.setText(errorMsg);
        else
            mMessage.setText(\"\");
        dialog.dismiss();
        // Clean up all variables of the object
        disposeAll();
        Log.i(TAG,\"FINISHED onPostExecute()\");
        // Go out of AsyncTask and have control to other method of Activity class
        StartTimer();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        selectedServerHost = serverHost.substring(0,serverHost.indexOf(\'.\'));
        dialog.setCancelable(false);
        dialog.setIcon(R.drawable.icon);
        dialog.setTitle(\"Progessing...\");
        dialog.setMessage(String.valueOf(R.string.ui_activity_authenticating));
        dialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        // Set all updates to UI
        return;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        Log.i(TAG,\"Into doBackground...\");
        ......
        Log.i(TAG,\"Starting Connect.....\");
        StartConnect();

        return true;
    }

    @Override
    public void notifyUI() {
        Log.i(TAG,\"GOT MESSAGE FROM MonitorConnection\");
        monitorTimer.cancel();
        Log.i(TAG,\"Preparing to Start\");
        PrepareToStartToConnect();
        publishProgress(4);
        status = 1;
        if (status == 1 || status == 2)
            ReConnect();
    }


    private void StartConnect() {
        // This is empty right now      
    }
}   // END OF ConnectTask class
调用StartTimer,然后MonitorThread通知Activity类,然后调用ReConnect,后者依次调用ConnectClicked。在ConnectClicked中, connectTask =新的ConnectTask();是我得到此异常和日志的地方:
04-15 17:09:07.501: INFO/Ultimate VPN:(364): Starting Connect.....
04-15 17:09:07.501: INFO/Ultimate VPN:(364): Into onPostExecute()
04-15 17:09:07.501: INFO/Ultimate VPN:(364): FINISHED onPostExecute()
04-15 17:09:07.501: INFO/Ultimate VPN:(364): Into Start Timer
04-15 17:09:07.542: INFO/MON CONN(364): Into StartMonitor
04-15 17:09:07.542: INFO/MON CONN(364): Into checkConnection
04-15 17:09:07.671: WARN/InputManagerService(69): Window already focused,ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4073b170
04-15 17:09:08.252: INFO/System.out(364): MonitorConnection : Notifing the GUI
04-15 17:09:08.262: INFO/Ultimate VPN:(364): GOT MESSAGE FROM MonitorConnection
04-15 17:09:08.262: INFO/Ultimate VPN:(364): Preparing to Start
04-15 17:09:18.322: INFO/Ultimate VPN:(364): ABOUT TO RE-CONNECT
04-15 17:09:18.322: INFO/Ultimate VPN:(364): Inside Connectclicked
04-15 17:09:18.322: INFO/Ultimate VPN:(364): isConnectionEligible = true
04-15 17:09:18.331: WARN/dalvikvm(364): threadid=11: thread exiting with uncaught exception (group=0x40015560)
04-15 17:09:18.351: ERROR/AndroidRuntime(364): FATAL EXCEPTION: Timer-0
04-15 17:09:18.351: ERROR/AndroidRuntime(364): java.lang.RuntimeException: Can\'t create handler inside thread that has not called Looper.prepare()
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at android.os.Handler.<init>(Handler.java:121)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at android.app.Dialog.<init>(Dialog.java:101)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at android.app.AlertDialog.<init>(AlertDialog.java:63)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at android.app.ProgressDialog.<init>(ProgressDialog.java:80)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at android.app.ProgressDialog.<init>(ProgressDialog.java:76)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.StartUltimate$ConnectTask.<init>(StartUltimate.java:386)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.StartUltimate.ConnectClicked(StartUltimate.java:324)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.StartUltimate.ReConnect(StartUltimate.java:340)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.StartUltimate.notifyUI(StartUltimate.java:316)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.MonitorConnection.setConnected(MonitorConnection.java:43)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.MonitorConnection.checkConnection(MonitorConnection.java:69)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.MonitorConnection.StartMonitor(MonitorConnection.java:61)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at orange.android.vpn.MonitorConnection.run(MonitorConnection.java:52)
04-15 17:09:18.351: ERROR/AndroidRuntime(364):     at java.util.Timer$TimerImpl.run(Timer.java:284)
04-15 17:09:18.382: WARN/ActivityManager(69):   Force finishing activity orange.android.vpn/.StartUltimate
知道为什么我会收到此错误吗?我该如何解决?我尝试在ConnectTask类而不是Activity类中处理UINotifier。但是,尽管已将StartTimer添加到其中并且该线程已经在运行,但是onPost在StartConnect()之后立即被调用。然后doInBackground也停止了,所以我用这种方式进行了管理。但是两种方式我都会出错。在其他情况下,我得到... Looper ....例外。 非常感谢您的帮助。 谢谢     

解决方法

我将摆脱UINotifier(自定义实现),并考虑使用Android中的开箱即用的Handler机制来通知UI。 请参阅如何使用AsyncTask和Timer获取XML?对于类似的实现。 另外,请参阅此处的无痛线程文章:http://developer.android.com/resources/articles/painless-threading.html,以获取有关线程(和处理程序)的更多信息。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res