具有单个服务或不同服务的多个后台任务

时间:2014-01-02 17:41:10

标签: android service android-asynctask

我有两个很长的后台任务(彼此独立)要做。所以,我为第一个任务编写了一个服务类,里面有一个AsynTask(代码如下)。

我的问题是,对于第二项任务,我应该在同一服务类中添加另一个asynctask,还是应该创建一个新的服务类?推荐哪一个?

我的代码(正常运行):

public class MyServiceClass扩展Service {

public boolean isCancelled = false;
DownloadFile downloadFile;
@Override
public int onStartCommand(Intent intent, int flags, int startId){
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.example.MyServiceClass.STOP");
    registerReceiver(receiver, filter);
    downloadFile = new DownloadFile();
    downloadFile.execute();
    return 0;
}

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals("com.example.MyServiceClass.STOP")){
            isCancelled = true;
        }

    }
};

@Override
public void onDestroy() {
    unregisterReceiver(receiver);
    downloadFile.cancel(true);
}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

private class DownloadFile extends AsyncTask<Void, String, String> 
{
    NotificationManager mNotifyManager;
    NotificationCompat.Builder mBuilder;
    int mId = 2;
    Context context;

    @Override
    protected void onPreExecute() {
        context = getApplicationContext();
        if(context!=null){
            Intent newintent = new Intent();
            newintent.setAction("com.example.MyServiceClass.STOP");
            PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, newintent, 0);
            mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setContentTitle("Cover Download")
                .setContentText("In progress")
                .setContentIntent(pIntent)
                .setSmallIcon(R.drawable.ic_launcher);
        }
    }

    @Override
    protected String doInBackground(Void... args) {
        if(context==null)
            return null;
        try{
            publishProgress("Caching started.");
            mBuilder.setProgress(0, 0, true);
            mNotifyManager.notify(mId, mBuilder.build());
            //////////SOMEWORK /////////////////
            for(HashMap<String, String> map:data){
                if (MyServiceClass.this.isCancelled)  {
                    MyServiceClass.this.stopSelf();

                }
                if(isCancelled)
                    return null;
                //////// SOMEWORK
                mBuilder.setProgress(maxlength, i++, false);
                mNotifyManager.notify(mId, mBuilder.build());
            }
        }catch(Exception e){
            return "Download failed";
        }
        return "Download completed.";
    }

    @Override
    protected void onProgressUpdate(String... values) 
    {
        Toast.makeText(context, values[0], Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onPostExecute(String result1) 
    {
        mBuilder.setContentText(result1).setProgress(0,0,false);
        mNotifyManager.notify(mId, mBuilder.build());
        Toast.makeText(context, result1, Toast.LENGTH_SHORT).show();
        context = null;
        MyServiceClass.this.stopSelf();
    }

    @Override
    protected void onCancelled(){
        mBuilder.setContentText("Download cancelled.").setProgress(0,0,false);
        mNotifyManager.notify(mId, mBuilder.build());
        context = null;
        MyServiceClass.this.stopSelf();
    }
}

1 个答案:

答案 0 :(得分:0)

井服务类将启动后台任务(异步任务)。所以最好还有一个异步任务。你可以创建一个简单的类外侧服务并在同一个服务类中使用它