使用 AsyncTask 在后台服务中添加 Android 进度对话框,出现致命异常

2024-01-03

  1. 我正在打电话异步任务从预定服务每 10 分钟运行一次。

  2. 运行服务时,进度对话框从以下位置获取异常预执行.

ERROR :

FATAL EXCEPTION: main                                                                                    
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:594)

at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)

at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)

at android.app.Dialog.show(Dialog.java:286)

EDIT 1: 警报管理器每 5 分钟调用一次服务

/*Alarm manager Service for From Server*/
private void setServerFetch() {
    // for  to Server to GPS PING
    Intent myIntent1 = new Intent(LoginPage.this, AlarmService.class);
    pendingintent1 = PendingIntent.getService(LoginPage.this, 1111, myIntent1, 0);
    AlarmManager alarmManager5 = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTimeInMillis(System.currentTimeMillis());
    calendar1.add(Calendar.SECOND, 1);
    alarmManager5.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingintent1);
    alarmManager5.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), 300 * 1000, pendingintent1);

}

呼叫服务 Onstart 中的 AsyncTask

 @Override
    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);


        try
        {

                Asynctask_Incident task=new Asynctask_Incident();
                task=new();

        }
        catch (Exception e)
        {
            e.printStackTrace();
            Log.i("PING", "EXCEPTION in reading Data from Web Async task ONstart.!");

        }

    }

异步任务类onStart Method

public class Asynctask_Incident extends AsyncTask<String, Void, Void>
    {


        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();

            runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    if (!pDialog.isShowing())
                    {
                        pDialog = new ProgressDialog(appContext);
                        pDialog.setCanceledOnTouchOutside(false);
                        pDialog.setCancelable(false);
                        pDialog.setMessage("Please Wait Updating Data From...");
                        pDialog.show();
                    }
                }
            });


        }

        @Override
        protected Void doInBackground(String... params)
        {
            try {
                getAPICall();

            } catch (Exception e) {
                e.printStackTrace();

                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }

            }

            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid)
        {

            super.onPostExecute(aVoid);

            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }


        }


    }

帮助我解决这个问题。


实际上,您无法从服务启动进度对话框,因为它需要活动上下文而不是应用程序上下文,在您的情况下,应用程序上下文为空。

更多信息请点击这里:link1 https://stackoverflow.com/a/2639515/831127 , link2 https://stackoverflow.com/a/7229248/831127 and link3 https://stackoverflow.com/a/7933358/831127

如果你想根据服务动作触发进度对话框,你可以使用观察者设计模式,看看here https://stackoverflow.com/a/13347389/831127.

Update:如果您的应用程序正在运行,您可以使用 Handler 并每 5 分钟运行一次。

这是一个完整的例子:

public class TestActivity extends AppCompatActivity {

private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            //
            new Asynctask_Incident(TestActivity.this).execute("url");
            handler.postDelayed(this, 5 * DateUtils.MINUTE_IN_MILLIS);
        }
    }, 0);
}

public class Asynctask_Incident extends AsyncTask<String, Void, Void> {


    ProgressDialog pDialog;
    Context appContext;

    public Asynctask_Incident(Context ctx) {
        appContext = ctx;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

            pDialog = new ProgressDialog(appContext);
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.setCancelable(false);
            pDialog.setMessage("Please Wait Updating Data From...");
            pDialog.show();


    }

    @Override
    protected Void doInBackground(String... params) {
        try {
            getAPICall();

        } catch (Exception e) {
            e.printStackTrace();

            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }

        }

        return null;
    }

    private void getAPICall() {

        //5 seconds delay for test, you can put your code here
        try {
            Thread.sleep(5 * DateUtils.SECOND_IN_MILLIS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPostExecute(Void aVoid) {

        super.onPostExecute(aVoid);

        if (pDialog.isShowing()) {
            pDialog.dismiss();
        }


    }


}

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AsyncTask 在后台服务中添加 Android 进度对话框,出现致命异常 的相关文章

  • gradle更新后无法找到方法(无法编译项目)

    我尝试将项目中的 gradle 版本更新为 4 1 milestone 1 以下这些说明 https developer android com studio build gradle plugin 3 0 0 migration html
  • 我在布局上看不到任何 FirebaseRecyclerAdapter 项目

    我试图将数据从 Firebase 数据库检索到我的布局 但我看不到任何项目FirebaseRecyclerAdapter在布局中 请帮忙 我按照一个教程展示了如何做到这一点 当我运行应用程序时 我没有看到任何项目 但我可以滚动 public
  • Cheesesquare:enterAlways 会产生错误的布局

    Adding enterAlways到 Cheesesquare 演示的滚动标志
  • 如何在android中显示保存在sdcard文件夹中的图像[关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 当我正在显
  • 如何正确释放Android MediaPlayer

    我正在尝试向我的 Android 应用程序添加一个按钮 当点击该按钮时它会播放 MP3 我已经让它工作了 但没有办法释放 mediaPlayer 对象 因此即使在我离开活动后它仍然会继续播放 如果我在react 方法之外初始化MediaPl
  • Dialog.setTitle 不显示标题

    我正在尝试向我的对话框添加自定义标题 但是每当我运行我的应用程序时 它都不会显示标题 我创建对话框的代码是 final Dialog passwordDialog new Dialog this passwordDialog setCont
  • 在 android 中建立与 MySQL 的池连接

    我需要从我的 Android 应用程序访问 MySQL 数据库 现在所有的工作都通过 DriverManager getConnection url 等等 但我必须从多个线程访问数据库 所以我必须使用连接池 问题1 是 com mysql
  • Android Eclipse 上的 Web 服务

    我是 android eclipse java 的新手 事实上这个论坛也是如此 有人遇到过这种情况吗 从用户那里获取输入并通过使用 android eclipse 中的 Web 服务来显示适当的结果 有可用的示例吗 非常感谢 我正在发布教程
  • 图像作为电子邮件附件

    我想构建一个应用程序 我可以在电子邮件中附加图像 打开图像并将其设置为我的壁纸 我想让它跨平台 所以你能告诉我是否可以使用phonegap 或者我是否必须为iphone和android构建一个本机应用程序 您好 如果您只想通过电子邮件附加图
  • Android - AudioRecord类不读取数据,audioData和fftArray返回零

    我是 Android 新手 一直在开发音调分析器应用程序 最低 SDK 8 我读了很多关于如何实现 Audiorecord 类的文章 但我想知道为什么它在我录制时不读取任何数据 我尝试显示 audioData 和 fftArray 的值 但
  • 我应该释放或重置 MediaPlayer 吗?

    我有自己的自定义适配器类 称为 WordAdapter 并且我正在使用媒体播放器 名为pronounce WordAdapter 类中的全局变量 我有不同的活动 其中每个列表项都有线性布局 名为linearLayout 我正在设置onCli
  • Android 如何将总天数准确更改为年、月、日?

    我正在做一个应用程序 该应用程序与根据给定的生日日期输入获取一个人的年龄有关 为此 我从下面的代码中获取从该日期到当前日期的总天数 String strThatDay 1991 05 10 SimpleDateFormat formatte
  • 没有用于警告的设置器/字段 Firebase 数据库检索数据填充列表视图

    我只是想将 Firebase 数据库中的数据填充到我的列表视图中 日志显示正在检索数据 但适配器不会将值设置为列表中单个列表项中的文本 它只说 没有二传手 场地插入值 这让我觉得我的设置器没有正确制作 但 Android Studio 自动
  • 找不到符号 NOTIFICATION_SERVICE?

    package com test app import android app Notification import android app NotificationManager import android app PendingIn
  • 在 Android 应用程序资源中使用 JSON 文件

    假设我的应用程序的原始资源文件夹中有一个包含 JSON 内容的文件 我如何将其读入应用程序 以便我可以解析 JSON See 开放原始资源 http developer android com reference android conte
  • 如何使用 AccessibilityService 在 Android 中模拟按键

    我正在编写一个辅助服务 我一直在尝试在应用程序上进行一些自动搜索 我使用accessibilityservice action paste来填充EditText 然后我需要模拟软键盘上的按键 但我不知道如何做 你们能帮我一下吗 你可以尝试A
  • 错误:(23, 13) 无法解决:com.google.android.gms:play-services:11.2.0“安装存储库和同步项目”不起作用

    我正在尝试在我的 Android 应用程序中获取位置并更新到服务器 这是我的 Gradle 代码 我在这里包含了compile com google android gms play services 11 2 0 这条线是从文档中 htt
  • 我的应用程序中的后退按钮出现问题[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 我想在手机关闭时清除共享首选项值 你
  • Dagger 2 中“HasFragmentInjector”的实际用法是什么

    我之前已经实现了 dagger2 v2 2 但现在他们也添加了 dagger android 部分 所以我正在用它创建示例项目 我知道旧的方法论 Provide and Modules and 成分等注释 但从 Dagger 2 8 开始
  • Git 实验分支还是单独的实验存储库?

    我正在开发一个 Android 应用程序 并且在整个开发周期中一直使用 Git 现在 我想构建并发布实验性功能 供人们尝试和安装 同时仍将原始的 稳定的应用程序安装在他们的设备上 现在 这意味着我需要使用不同的包名称 这会更改开发项目中的一

随机推荐