【问题标题】:onActivityResult() is not called when acquiring wakelock globally and setResult() defined in handler.postDelayed() block全局获取wakelock和在handler.postDelayed()块中定义的setResult()时不调用onActivityResult()
【发布时间】:2013-02-26 22:04:31
【问题描述】:

我有一些代码在屏幕打开时执行,但是当我关闭屏幕时,执行时出现了一些问题(即使在全局获取 Wakelock 之后)。我有一个获取唤醒锁并调用活动的服务 - ExecuteScript 使用以下代码:

ExecuteScript.java:

 Intent intent = new Intent(this,ScriptActivity.class);
 intent.putExtra("code",code);
 intent.putExtra("type", type);  
 startActivityForResult(intent,REQUEST_CODE); 

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
 super.onActivityResult(requestCode, resultCode, data);
 Log.d(TAG,"The result code value inside onActivityResult() is: "+requestCode +resultCode);
 if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {              
 Log.d(TAG,"ScriptActivity finished success!!"); 
 }      

在我的 ScriptActivity(调用 Service 并执行需要 30 秒的操作)中。但是,在我的情况下没有调用 onActivityResult() 。我不确定为什么会发生这种情况。请帮帮我。

我在 handler.postDelayed() 块中定义了 setResult()。我有这样的代码:

ScriptActivity.java

Intent serviceIntent = new Intent(this,ScriptService.class);
serviceIntent.putExtra("code",code);
serviceIntent.putExtra("type",type);
startService(serviceIntent);
handler.postDelayed(new Runnable(){public void run(){     
Intent data = new Intent(ScriptActivity.this,ExecuteScript.class);
data.putExtra("returnKey1", "You can write the file to the server ");   
setResult(Activity.RESULT_OK, data);
Log.d(TAG,"**After calling the method startActivityTwo here*****");
finish();
}},30000);

更新:使用绑定服务也不起作用。对此有何想法?

【问题讨论】:

  • ExecuteSript 是一项活动,对吧?在您的处理程序 postDelayed 代码而不是 Intent data = new Intent(ScriptActivity.this,ExecuteScript.class);尝试意图数据=新意图();为什么要添加延迟顺便说一句??
  • 是的 ExecuteScript 是一个 Activity。我最初有 Intent data = new Intent(),但它没有用。所以我添加了,Intent data = new Intent(ScriptActivity.this,ExecuteScript.class);延迟是因为 ScriptService 执行的脚本最多需要 30 秒并在手机中显示 toast。因此我在处理程序中有 setResult。
  • 我使用了链接 stackoverflow.com/questions/5302085/… 并将其添加到我的代码中。但它没有任何区别。 @baboo
  • 而不是 30 秒延迟使用绑定服务,在成功绑定时它通过回调返回 setresult 并完成活动..查看绑定服务(而不是 startservice 使用绑定服务)
  • 我现在正在使用 bindService() 并删除了处理程序。在这种情况下,我得到如下执行: Activity ScriptActivity 泄漏了最初绑定在这里的 ServiceConnection 。但即使是现在,onActivityResult() 也没有被调用。我做得对吗,因为我对使用绑定服务没有太多想法。 @baboo

标签: android android-intent android-wake-lock android-handler


【解决方案1】:

当我的活动获得焦点并且我关闭屏幕时,它会停止。根据开发者页面,停止:在这种状态下,活动完全隐藏,对用户不可见;它被认为是在后台。停止时,活动实例及其成员变量等所有状态信息都将保留,但不能执行任何代码。

另外,我修改了代码,以便我的服务可以直接调用 ScriptService 类,而无需在两者之间进行任何活动。在我的服务的 onCreate() 方法中,我使用链接 releasing wakelock in different activity to where it was acquired 获取全局唤醒锁。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2020-04-05
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多