在内部异步任务完成之前停止服务

时间:2014-03-05 17:09:37

标签: android android-asynctask android-service android-broadcast

假设我有一个从广播接收者调用的服务:

@Override
public void onReceive( final Context pContext, Intent pIntent ) {
    String intentAction = pIntent.getAction();

    if ( intentAction.equals( TelephonyManager.ACTION_PHONE_STATE_CHANGED ) ) {
        String state = pIntent.getStringExtra( TelephonyManager.EXTRA_STATE );
        if ( state.equals( TelephonyManager.EXTRA_STATE_RINGING ) ) {
            Intent intent = new Intent( pContext, OverlayService.class );
            pContext.startService( intent );
            return;
        }

        if ( state.equals( TelephonyManager.EXTRA_STATE_IDLE ) ) {
            Intent intent = new Intent( pContext, OverlayService.class );
            pContext.stopService( intent );
            return;
        }
    }
}

该服务包含一个执行http请求的内部asynctask:

@Override
public int onStartCommand( Intent pIntent, int pFlags, int pStartId ) {
    new HttpTask().execute( getString( R.string.conf_server_url ) );

    return START_STICKY;
}

我想知道当用户在任务完成之前决定挂断电话时会发生什么。我知道任务将继续运行直到完成。这会造成内存泄漏吗?我的猜测是,只要任务没有完成,服务就无法销毁。但之后收集了吗?如果没有,有任何建议如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

为什么不保留对AsyncTask的引用并在服务的onDestroy上或者不再需要时调用cancel()?您必须检查isCancelled()然后结束任务。

相关问题