如果应用程序关闭,Android IntentService 无法完成任务

标签 android android-intent service android-service intentservice

我正在使用 IntentService 将数据保存到 SQLDatabase 并将数据上传到 Parse。如果我保持应用程序运行,IntentService 工作正常。如果我最小化它(通过按主页按钮),它也会正确执行。

但是如果我按下导航按钮并毁掉应用程序(应用程序屏幕缩小并且您将其关闭);然后 IntentService 停止运行(它甚至不调用 onDestory)。

我想要的是让服务执行所有任务;并毁灭自己。因此,不需要 START_STICKY ( Intent ),因为我不希望它在后台连续运行。

启动 IntentService

Intent intent_publishService = new Intent(getApplicationContext(), PublishService.class);

Bundle basket_storyData = new Bundle();
basket_storyData.putAll( packStoryData() );
intent_publishService.putExtra(KEY_BASKET_STORY_DATA, basket_storyData);

intent_publishService.putParcelableArrayListExtra(KEY_BASKET_IMAGE_DATA, (ArrayList<? extends Parcelable>) final_image_data);
startService(intent_publishService);

PublishService.class( fragment )

@Override
protected void onHandleIntent(Intent intent)
{
    Log.i(TAG, "ONHANDLEINTENT" );

    context = getApplicationContext();

    final String KEY_BASKET_IMAGE_DATA = "key_basket_image_data";
    final String KEY_BASKET_STORY_DATA = "key_basket_story_data";
    final String KEY_BASKET_EXTRA      = "key_basket_extra";


    ArrayList<ImagesData> _iDataSave = new ArrayList<ImagesData>();
    _iDataSave.addAll( (Collection<? extends ImagesData>) intent.getParcelableArrayListExtra(KEY_BASKET_IMAGE_DATA) );

    Log.i(TAG, "_iDataSize:" + Integer.toString(_iDataSave.size()) );

    //Get Bundle Values
    Bundle storyBundle = intent.getBundleExtra(KEY_BASKET_STORY_DATA);

    publishStory(storyBundle, _iDataSave);
}

编辑1: list 声明

<service android:name="com.example.create.main.PublishService" />

已解决

最佳答案

在这种情况下,您将需要 START_STICKY 来向 Android 表明您希望在应用程序终止后尝试继续工作。

当用户从应用程序选择器上滑开时,将无条件终止应用程序进程。您无法阻止这种情况的发生 - 其目的是让用户控制当时正在运行的内容。

关于如果应用程序关闭,Android IntentService 无法完成任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832582/

相关文章:

java - 如何创建唯一 key 并使用它在 Firebase 中发送数据?

android - 如何禁用 Android 日历(应用程序)的选择字段?

javascript - 变量未定义 : AngularJS

hibernate - 为什么将@Transactional与@Service一起使用而不是与@Controller一起使用

android - 想要从contacts.db中获取列索引以直接打开viber聊天屏幕

android - 启动模式和 Intent.setFlag

android - 当我从图库中选择图片时,onCreate 在 onActivityResult 之后调用

java - 尝试通过通知实现警报

android - 在 Android 中进行下一步之前需要完成长任务时的正确设计

android - 从 android for work 应用程序访问 SD 卡数据