【问题标题】:Run asynchronous task in OnReceive() method of broadcast receiver在广播接收器的 OnReceive() 方法中运行异步任务
【发布时间】:2018-05-18 15:59:47
【问题描述】:

我想在 onReceive(Context context, Intent intent) 方法中运行异步任务。现在我想使用 OnReceive 的上下文......因为我必须使用:Cursor cursor = context.getContentResolver().query();用于获取光标,因此如果我使用全局定义的上下文,它会抛出空指针异常。所以如何获取 Onreceive() 方法的上下文以在其中运行它的异步任务。

【问题讨论】:

    标签: android


    【解决方案1】:

    只需在BroadCastReceiver中创建一个全局Context,并将onReceive()内的Context实例分配给这个全局Context实例并使用它,

    Context context;
    
    @Override
        public void onReceive(Context arg0, Intent arg1) {
            this.context = arg0;
                // now use context instance in your AsyncTask class.
            }
    

    【讨论】:

    • 嗨 Lalit poptani ...它是否强制在 OnReceive() 侧使用 Intent arg1 ?
    • 不,它在收到任何 Intent 时使用。
    • lait 在执行后还有一个问题,我正在使用 startActivityForResult(Intent.createChooser(emailIntent, "Send mail..."), ACTIVITY_CREATE); 运行其他发送电子邮件的方法;但是 ACTIVITY_CREATE 有错误……现在我该怎么办?
    • stackoverflow.com/questions/9223556/… 请参考此链接...谢谢
    • 嗨,我正在等待您的回复..请参阅上面的链接 thakns]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多