当另一个片段被调用时,线程仍在运行

时间:2016-02-09 22:22:45

标签: android android-fragments onpause

嗨我有一个在片段A上运行的线程,当我调用第二个片段时,据说片段A必须调用方法onPause(),我停止线程,但是线程仍在运行,因为我有一个第一个片段上的吐司显示一条消息,如果我在片段A上的列表是空的,它在片段B上显示,让我粘贴你的代码:

片段A:

   public class FragmentoPrincipalChofer extends ListFragment {
        private List<ParseObject> mPedido;
        private List<ParseObject> mViaje;
        private List<ParseUser> mUrlUsuario;
        private ListView mLista;
        private Runnable r;
        final Handler handler = new Handler();
        private String  mChoferActual;
        private String mPassChofer;
        private   AdaptadorDatosListviewChofer adaptador;





        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {


            View x = inflater.inflate(R.layout.fragmento_principal_chofer, container, false);
            mLista = (ListView)x.findViewById(android.R.id.list);




            SharedPreferences pref = getContext().getSharedPreferences("login", 0);
            mChoferActual= pref.getString("usuario","");
            mPassChofer= pref.getString("pass","");

            ParseUser.logInInBackground(mChoferActual, mPassChofer, new LogInCallback() {
                public void done(ParseUser user, ParseException e) {
                    if (user != null) {
                        // Hooray! The user is logged in.
                    } else {
                        // Signup failed. Look at the ParseException to see what happened.
                    }
                }
            });




            return x;

        }

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

            // logica de recibir pedidos

            final ProgressDialog dialogoProgreso = new ProgressDialog(getContext());
            dialogoProgreso.setTitle("Cargando");
            dialogoProgreso.setMessage("Buscando Pedidos");
            dialogoProgreso.setCancelable(false);
            dialogoProgreso.show();

                r = new Runnable() {
                    public void run() {

                        handler.postDelayed(r, 10000);









                        //obtener pedido de taxi


                        ParseQuery<ParseObject> query = ParseQuery.getQuery("Pedido");
                        query.whereEqualTo("chofer", mChoferActual);
                        query.addDescendingOrder("createdAt");
                        query.findInBackground(new FindCallback<ParseObject>() {
                            public void done(List<ParseObject> pedido, com.parse.ParseException e) {
                                if (e == null) {

                                    if(pedido.size()==0){
                                        dialogoProgreso.cancel();


  Toast.makeText(getContext(), "prueba", Toast.LENGTH_LONG).show();


                                    }else{

                                        dialogoProgreso.cancel();
                                        mPedido = pedido;
                                        String[] nombreUsuarios = new String[mPedido.size()];
                                        int i = 0;
                                        for (ParseObject pedidos : mPedido) {

                                            nombreUsuarios[i] = pedidos.getString("cliente");
                                            i++;

                                        }



                                        adaptador = new AdaptadorDatosListviewChofer(getListView().getContext(), mPedido);
                                        setListAdapter(adaptador);


                                    }


                                } else {

                                }
                            }
                        });

                    }
                };
                r.run();


            ClickPedido();


        }


        // manejo de click sobre el pedido de taxi
        public void ClickPedido() {

            mLista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                              @Override
                                              public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                                                  final String clienteSeleccionado = mPedido.get(position).get("cliente").toString();
                                                  AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

                                                  builder.setTitle("Confirmacion de pedido")
                                                          .setMessage("Esta seguro que desea tomar el pedido de " + clienteSeleccionado)
                                                          .setPositiveButton("OK",
                                                                  new DialogInterface.OnClickListener() {
                                                                      @Override
                                                                      public void onClick(DialogInterface dialog, int which) {

                                                                          adaptador.remove(mPedido.get(position));
                                                                          adaptador.notifyDataSetChanged();


                                                                          ParseQuery<ParseObject> query2 = ParseQuery.getQuery("Pedido");
                                                                          query2.whereEqualTo("cliente", clienteSeleccionado);
                                                                          query2.getFirstInBackground(new GetCallback<ParseObject>() {
                                                                              public void done(ParseObject chofer, ParseException e) {
                                                                                  if (chofer == null) {
                                                                                      Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                                                                                  } else {

                                                                                      try {

                                                                                          ParseObject viaje = new ParseObject("Viaje");
                                                                                          viaje.put("chofer", mChoferActual);
                                                                                          viaje.put("cliente", chofer.get("cliente").toString());
                                                                                          viaje.saveInBackground();


                                                                                          chofer.delete();
                                                                                          chofer.saveInBackground();


                                                                                          Fragment fragment2 = new MapaChofer();
                                                                                          FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
                                                                                          transaction.replace(R.id.prueba2, fragment2).addToBackStack(null);
                                                                                          transaction.commit();

                                                                                      } catch (ParseException e1) {
                                                                                          e1.printStackTrace();
                                                                                      }


                                                                                  }
                                                                              }
                                                                          });


                                                                      }

                                                                  }

                                                          )
                                                          .setNegativeButton("CANCELAR",
                                                                  new DialogInterface.OnClickListener() {
                                                                      @Override
                                                                      public void onClick(DialogInterface dialog,
                                                                                          int which) {

                                                                      }
                                                                  }

                                                          );
                                                  builder.show();


                                              }
                                          }

            );


                                    }



        @Override
        public void onPause() {
            super.onPause();
            handler.removeCallbacks(r);
                    }

       }

主要抽屉管理碎片:

public class DrawerPrincipal extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {


    private ParseFile mPrueba;
    private Uri url;
    private ImageView imagen;
    private DrawerLayout mDrawerLayout;
    private String mUsuarioActual;
    public static final int CHOOSE_PIC_REQUEST_CODE = 1;
    private Uri mMediaUri;
    private ImageView mImagenPrevia;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drawer_principal);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        SharedPreferences pref = getApplicationContext().getSharedPreferences("login", 0);
        mUsuarioActual= pref.getString("usuario","");









        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View hView =  navigationView.inflateHeaderView(R.layout.nav_header_drawer_principal);
        final ImageView imgvw = (ImageView)hView.findViewById(R.id.imagenPerfil);
        final TextView tv = (TextView)hView.findViewById(R.id.nombreUsuarioV);
        //Picasso.with(getBaseContext()).load(url.toString()).into(imgvw);
        tv.setText("new text");

        ParseQuery<ParseUser> query3 = ParseUser.getQuery();
        query3.whereEqualTo("username",mUsuarioActual);
        query3.findInBackground(new FindCallback<ParseUser>() {
            public void done(List<ParseUser> usuario, ParseException e) {
                if (e == null) {

                    mPrueba = usuario.get(0).getParseFile("foto");
                    tv.setText(usuario.get(0).getUsername().toString());
                    url = Uri.parse(mPrueba.getUrl());
                    Picasso.with(getBaseContext()).load(url.toString()).transform(new RoundedTransformation(300, 4)).into(imgvw);

                    if (usuario.get(0).get("tipoUsuario").toString().equals("pasajero")) {
                        Fragment fragmento;
                        fragmento = new FragmentoPrincipalUsuario();
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.content_main, fragmento)
                                .commit();


                    }else {

                        Fragment fragmento;
                        fragmento = new FragmentoPrincipalChofer();
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.content_main, fragmento)
                                .commit();

                    }


                } else {
                    // Something went wrong.
                }
            }
        });




    }



    @Override
    public void onBackPressed() {

        DrawerLayout layout = (DrawerLayout)findViewById(R.id.drawer_layout);
    if (layout.isDrawerOpen(GravityCompat.START)) {
        layout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
        /*
        if(getSupportFragmentManager().getBackStackEntryCount()!=0) {
            getSupportFragmentManager().popBackStack();
        }else{

            super.onBackPressed();
        }*/
    }









    /*
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.pantalla_principal_usuario, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    */
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.cuenta) {

            Fragment fragmento;
            fragmento = new OpcionDrawerUsuario();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .addToBackStack(null)
                    .commit();

        } else if (id == R.id.historial_viajes) {
            Fragment fragmento;
            fragmento = new FragmentoViajesAcumulados();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragmento)
                    .addToBackStack(null)
                    .commit();


        } else if (id == R.id.contacto) {
            String emailAdress[] = {"gastondelacruz@gmail.com"};
            Intent email= new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL,emailAdress);
            email.putExtra(Intent.EXTRA_SUBJECT,"Pon aqui el motivo de tu mail");
            email.setType("text/plain");
            email.putExtra(Intent.EXTRA_TEXT,"Su mensaje");
            startActivity(email);


        } else if (id == R.id.compartir) {
            String texto="https://www.google.com.ar/?gfe_rd=cr&ei=9JuBVvmcGanX8gejsK_4CA&gws_rd=ssl";
            Intent intento= new Intent();
            intento.setAction(Intent.ACTION_SEND);
            intento.putExtra(Intent.EXTRA_TEXT, texto);
            intento.setType("text/plain");
            startActivity(intento);

        } else if (id == R.id.version) {
            String prueba="aceptar";
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("prueba") //
                    .setMessage("Esta es una prueba todavia no poseo el numero de version del producto") //
                    .setPositiveButton(prueba, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // TODO
                            dialog.dismiss();
                        }
                    }); //

            builder.show();

        } else if (id == R.id.salir) {
            AlertDialog.Builder builder = new AlertDialog.Builder(DrawerPrincipal.this);
            builder.setTitle("Cerrar Sesion")
                    .setMessage("Esta seguro que desea cerrar sesion actual?")
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ParseUser.logOut();
                                    Intent intento = new Intent(getApplicationContext(), ActividadLogin.class);
                                    intento.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intento.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intento);
                                    finish();


                                }

                            }

                    )
                    .setNegativeButton("CANCELAR",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {

                                }
                            }

                    );
            builder.show();



        }

       DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);mDrawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }







}

1 个答案:

答案 0 :(得分:0)

你实际上没有在片段A中运行一个线程。你创建了一个Runnable并调用了它的run方法,这使它在当前线程中立即执行。然后它使用Handler重新安排自己。您的处理程序也在针对主线程安排工作,在这种情况下这是默认的。

很难说你在这里尝试做什么,代码格式不好,但我很确定你不想调用r.run()来立即调用Runnable。