2

我为我的应用程序提供了一项服务,该服务基本上可以解析 X 个 RSS 提要。大多数提要都相当小,但有些可能只有 1MB 左右。我在我的服务中的 AsyncTask 中解析它们。解析可能相当耗时,具体取决于用户的连接和提要的数量,但我会说最多不超过一两分钟。在服务中使用 WakeLock 是个好主意吗?

这是我的代码,到目前为止。不确定这是否是设置服务的最佳方式:

public class MainService extends Service  
{   
    private WakeLock mWakeLock;

    @Override
    public void onCreate()
    {       
        handleIntent();
    }

    @Override
   public int onStartCommand(final Intent intent, final int flags, final int startId)
    {
       return START_STICKY;
    }

   @Override 
   public void onStart(final Intent intent, final int startId) { 
       handleIntent(); 
   }

    protected void handleIntent() 
    {
        // obtain the wake lock 
        final PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE); 
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
        mWakeLock.acquire();

        if (!((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getBackgroundDataSetting()) 
        { 
            stopSelf();
            return;
        }

        new AsyncParsingTask().execute();
    }

    @Override
    public void onDestroy() 
    {
        super.onDestroy();

        mWakeLock.release();

    }   
}
4

2 回答 2

2

在服务中使用 WakeLock 是个好主意吗?

是的,如果让设备进入睡眠状态可能会给您带来问题。不过,我建议您使用 my WakefulIntentService,因为在处理WakeLock对象时有很多棘手的情况。您也不需要弄乱您自己的AsyncTaskor stopSelf(),因为那些将由IntentService(从中WakefulIntentService继承)为您处理。

于 2012-03-18T20:24:29.380 回答
0

服务在后台运行,没有必要在那里获取唤醒锁,但是您可以做的是检查您的活动是否正在运行,并在这种情况下获取唤醒锁并在活动完成时释放

于 2012-03-18T20:11:35.553 回答