android - 停止安卓服务

标签 android android-asynctask android-service

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

主要 Activity :

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();
    }
}

最佳答案

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

关于android - 停止安卓服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11077294/

相关文章:

java - 如何使用 iText 在 (x,y) 位置的文档中将 PdfPTable 添加到 HTML 字符串?

android - Drupal Android 应用程序登录持久性

java - 防止屏幕方向更改后服务过度窗口旋转

android - 无法从服务中获取 Binder 对象

android - 当我们在android应用程序中从服务器加载数据到页面时如何避免 "white screen in phonegap application"?

安卓 Gradle Jacoco : offline instrumentation for integration tests

Java:尝试 block 在结束之前停止,没有任何异常

android - ListView 在滚动时显示错误位置的图像

android - 如何测试异步 HTTP 请求和响应 Android

android - 如何像前台服务一样启动socket.io来保持连接和监听消息