停止Android服务

时间:2012-06-18 05:21:28

标签: android android-asynctask android-service

我在AsyncTask中使用 service编写了一个程序,用于从网上下载图像。下载过程正常。我使用notification来表示下载进度,我还有两个按钮用于开始下载和停止下载
但是当我点击停止按钮时,正在进行的下载无法停止。通知管理器继续相同。

主要活动:

public class ServicedownloadActivity extends Activity implements
        OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.button1) {
            Intent intent = new Intent(ServicedownloadActivity.this,
                    Myclass.class);
            startService(intent);

        }
        if (v.getId() == R.id.button2) {

            Intent intent = new Intent(ServicedownloadActivity.this,
                    Myclass.class);
            stopService(intent);
        }
    }
}

类包含serivce和asynchTask

public class Myclass extends Service {

    URLConnection connection;
    private final Random mGenerator = new Random();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public int getRandomNumber() {
        return mGenerator.nextInt(100);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("df", "From oncreate");
        Toast.makeText(this, "on create", Toast.LENGTH_SHORT).show();

    }
    class DownloadWebPageTask extends AsyncTask<String, String, String> {
        String responseTextt;
        NotificationManager notificationManager;
        Notification notification;
        CharSequence contentText;
        Context context;
        CharSequence contentTitle;
        PendingIntent contentIntent;
        int HELLO_ID = 1;
        long time;
        int icon;
        CharSequence tickerText;

        public void downloadNotification() {
            String ns = Context.NOTIFICATION_SERVICE;
            notificationManager = (NotificationManager) getSystemService(ns);
            icon = R.drawable.ic_launcher;
            tickerText = "Downloading...";
            time = System.currentTimeMillis();
            notification = new Notification(icon, tickerText, time);
            context = getApplicationContext();
            contentTitle = "Your download is in progress";
            contentText = "0% complete";
            Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
            notificationIntent.setType("audio/*");
            contentIntent = PendingIntent.getActivity(context, 0,
                    notificationIntent, 0);
            notification.setLatestEventInfo(context, contentTitle,
                    contentText, contentIntent);
            notificationManager.notify(HELLO_ID, notification);

        }

        @Override
        protected String doInBackground(String... urls) {

            try {

                Log.d("trys:", "try");
                URL url = new URL(
                        "http://www.zapiture.com/resources/IMG_6812.JPG");
                connection = url.openConnection();
                connection.connect();
                int fileLength = connection.getContentLength();
                InputStream input = new BufferedInputStream(url
                        .openStream());
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory()
                        + "/img23.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                int previousProgress = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    if ((int) (total * 100 / fileLength) > previousProgress) {
                        previousProgress = (int) (total * 100 / fileLength);
                        publishProgress(""
                                + (int) (total * 100 / fileLength));
                        output.write(data, 0, count);
                    }
                }

                output.flush();
                output.close();
                input.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            downloadNotification();

            super.onPreExecute();
            ;
        }

        @Override
        public void onProgressUpdate(String... progress) {

            contentText = Integer.parseInt(progress[0]) + "% complete";
            notification.setLatestEventInfo(context, contentTitle,
                    contentText, contentIntent);
            notificationManager.notify(HELLO_ID, notification);
            super.onProgressUpdate(progress);
        }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.d("sf", "On Start");
        Toast.makeText(this, "on start", Toast.LENGTH_SHORT).show();
        DownloadWebPageTask task = new DownloadWebPageTask();

        task.execute();
    }

    @Override
    public void onDestroy() {
        stopSelf();
        super.onDestroy();
        Log.d("df", "From on Destroy");
        Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
    }
}

4 个答案:

答案 0 :(得分:1)

你真的不应该在服务中使用AsyncTask,而是在活动中使用它。如果您需要自动启动工作线程的服务,请使用IntentService。完成后它也会自动停止。发送进度更新可能需要更多工作,但它比AsyncTask更清晰。

答案 1 :(得分:0)

当您使用AsyncTask下载时,可以尝试通过cancel(boolean)取消AsyncTask本身,

task.cancel(true);

答案 2 :(得分:0)

永远记住,即使你调用stopService,AsyncTask也不会在某些处理过程中停止。除非你在服务的onDestroy实现中调用task的cancel方法,它只会在完成后结束

因此,请在代码中进行以下修改。

你基本上需要添加它。

@Override
public void onDestroy() {
    task.canel();
    super.onDestroy();
}

此外,您在开始时正在创建DownloadWebPageTask task = new DownloadWebPageTask();,因此您无法在onDestroy中调用task.cancel.Rather定义DownloadWebPageTask task; 外部task.cancel onDestroy可以使用{{1}}。

答案 3 :(得分:0)

我建议你最初制作一个Boolean标志变量true,然后在onDestroy()中将其更改为false

现在在doInBackground检查变量状态是否为true然后继续你的任务,如果为false然后停止它,只需调用return;

AsyncTask在他们单独的process中运行时,即使活动/服务被破坏,他们也会继续执行。