android - 为什么在 Android 中调用 stopService 后服务中的线程仍未停止?

标签 android android-service

我正在使用服务将图片上传到服务器,那里有一个取消按钮可以取消上传,但问题是当我点击取消按钮时,我调用了 stopService() ,然后onDestroy 方法执行。但上传仍在继续......我想知道这是怎么发生的?我是初学者,我知道调用stopService后服务会被销毁,请问这是怎么回事?谁能帮帮我?

我的服务.java

public class MyService extends Service {
    int id=1;
    private ProgressDialog pd;
    Bitmap image=null;
    private static final int MY_NOTIFICATION_ID=1;
    NotificationManager notificationManager;
    private NotificationManager mNotifyManager;
    Notification myNotification;
    private android.support.v7.app.NotificationCompat.Builder mBuilder;
    RemoteViews contentView;
    Thread t;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // Let it continue running until it is stopped.
        String path;
        int i=0;

        path = intent.getExtras().getString("key");
        Toast.makeText(this, "Service Started"+path, Toast.LENGTH_LONG).show();
        Log.e("Service started=" + path, "service");
        image= decodeFile(path);
        startNotification();
    /*    pd = new ProgressDialog(MyService.this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("Uploading Picture...");
        pd.setCanceledOnTouchOutside(true);

        pd.setCancelable(true);
        pd.show();
        pd.setProgress(0);*/

        uploadPhoto(image);
        //  boolean status= isMyServiceRunning();
      /*  if(!status)//if false
        {
            myNotification = new NotificationCompat.Builder(getApplicationContext())
                    .setContentTitle("Cookbook Upload")
                    .setContentText("Upload Completed")
                    .setTicker("Cookbook Upload")
                    .setWhen(System.currentTimeMillis())
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setAutoCancel(true)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .build();

            notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
        }*/

        return START_STICKY;
    }
    private void startNotification() {


        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        CharSequence notiText = "Your notification from the service";
        long meow = System.currentTimeMillis();

        Notification notification = new Notification(icon, notiText, meow);

        Context context = getApplicationContext();
        CharSequence contentTitle = "Cookbook Upload";
        CharSequence contentText = "Upload in Progress";

        //PENDING INTENT
        Intent notificationIntent = new Intent(this, ImageViewActivity.class);
        notificationIntent.putExtra("FROM_NOTIFICATION", true);
       // notificationIntent.putExtra("first_state", 2);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,  PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        int SERVER_DATA_RECEIVED = 1;
        notificationManager.notify(SERVER_DATA_RECEIVED, notification);


        }
    private void EndNotification() {


        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        CharSequence notiText = "Your notification from the service";
        long meow = System.currentTimeMillis();

        Notification notification = new Notification(icon, notiText, meow);

        Context context = getApplicationContext();
        CharSequence contentTitle = "Cookbook Upload";
        CharSequence contentText = "Upload Completed";

        //PENDING INTENT
        Intent notificationIntent = new Intent(this, ImageViewActivity.class);
        notificationIntent.putExtra("Complete_message", 1);
        // notificationIntent.putExtra("first_state", 2);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,  PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        int SERVER_DATA_RECEIVED = 1;
        notificationManager.notify(SERVER_DATA_RECEIVED, notification);


    }
    private void uploadPhoto(Bitmap   bitmap) {
        //in this method you upload the photo to the server: omitted for brevity
        final Bitmap bit=bitmap;
         //
    /*    int[] progress = new int[0];
        pd.setProgress((int) (progress[0]));*/


        //
       t = new Thread("MyService") {
            @Override
            public void run() {
                try {
                    Log.e("Service started", "service");
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpContext localContext = new BasicHttpContext();
                    HttpPost httpPost = new HttpPost(Config.FILE_UPLOAD_URL);

                    MultipartEntity entity = new   MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);





                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                 bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    byte[] data = bos.toByteArray();


                    entity.addPart("uploaded_file", new ByteArrayBody(data,
                            "myImage.jpg"));

                    httpPost.setEntity(entity);
                    HttpResponse response = httpClient.execute(httpPost,
                            localContext);
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(
                                    response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    String aux = "";

                    while ((aux = reader.readLine()) != null) {
                        builder.append(aux);
                    }

                    String sResponse = builder.toString();



                } catch (Exception e) {


                    Log.e(e.getClass().getName(), e.getMessage(), e);

                }
                stopSelf();
            }
        };
        t.start();



       }
    public Bitmap decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);
        final int REQUIRED_SIZE = 1024;
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        o.inJustDecodeBounds = false;

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        image= BitmapFactory.decodeFile(filePath, o2);
        return image;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        t.interrupt();
        EndNotification();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

在这里我停止我的服务

最佳答案

使用这段代码

t = new Thread(new Runnable() {

    @Override
    public void run() {
        while (true) {
            try { 
                if(flag){//here add a flag
                  return;
                }
                t.sleep(5000);
                // Toast.makeText(getApplicationContext(), "Horas",
                // Toast.LENGTH_LONG).show();
                handler.sendEmptyMessage(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
});
t.start();

public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
//t.interrupt();
handler.removeCallbacks(t);
super.onDestroy();
flag = false;//here set flag to false
}

关于android - 为什么在 Android 中调用 stopService 后服务中的线程仍未停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560415/

相关文章:

java - Android 条件字符串的验证

java - Gradle:如何在 Android 构建中包含来自依赖 Java 项目的本地 jar?

android - 后台服务发布的事件没有订阅者

android - 服务、线程和进程

android - 如何设置 Android 闹钟在特定日期之前触发

android - 警报管理器意外停止

android - 无法在android中获取json数组

android - 使用 Roboguice 进行延迟注入(inject)

android - 无法在 Android 的 ndk-gdb 中达到断点

android - 我得到 Caused by : java. lang.InstantiationException 以下