线程执行错误第二次android

时间:2015-03-29 17:35:32

标签: java android multithreading android-intent

下午好,请原谅我的英语不是很好;我有一个包含各种活动的应用程序,但基本上可以定义如下:

主要活动>新警报>主要活动>报警和GT;新警报>线程执行错误

基本上是主要活动,我有一个带有个人适配器的ExpandableListView,它协调选项菜单;只需单击菜单报警,然后菜单子新报警,重定向到活动新报警,卷信息进入数据库并运行服务(Hilo),负责比较系统时间与介绍。

Code MainActivity:

public class MainActivity extends Activity {
    SparseArray<GrupoDeItems> grupos = new SparseArray<GrupoDeItems>();
    Hilos hilo,hilo2;
    Switch estado_drunk_blocker;
    Switch estado_alarma;
    GrupoDeItems grupo0 = new GrupoDeItems("Drunk Blocker");
    GrupoDeItems grupo1 = new GrupoDeItems("Alarma");
    adaptador adapter;
    Intent salto = new Intent();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        crearDatos();
        hilo2 = new Hilos("bd");
        hilo2.execute();


        estado_drunk_blocker = (Switch) findViewById(R.id.switch1);
        estado_alarma = (Switch) findViewById(R.id.switch2);
        ExpandableListView listView = (ExpandableListView) findViewById(R.id.listViewexp);
        adaptador adapter = new adaptador(this, grupos);
        listView.setAdapter(adapter);

    }

    public void crearDatos() {
        grupo0.children.add("Preferencias");
        grupo0.children.add("Configuración");
        grupos.append(0, grupo0);

        grupo1.children.add(0,"Nueva Alarma");
        grupos.append(1, grupo1);
    }

    public void AgregarAlarma_ConPos(String valor,int posicion){
        grupo1.children.add(posicion,valor);
        grupos.append(1,grupo1);
    }

    public void AgregarAlarma(String valor){
        grupo1.children.add(valor);
        grupos.append(1,grupo1);
    }

    public void LanzarDrunkBlocker(View view) throws InterruptedException {
        boolean on = estado_drunk_blocker.isChecked();
        if (on) {
            hilo = new Hilos("drunk blocker");
            hilo.execute();
        }
    }

    public void GenerarSaltos(Activity origen, Class destino){
        salto.setClass(origen,destino);
        startActivity(salto);
    }

   /* public void GenerarSaltos_ConservandoValores(Activity origen, Class destino, int codigo){

        Intent salto = new Intent(origen,destino);
        origen.startActivityForResult(salto,codigo);
    }
 */

    public void HacerUnaPausa(){
        try {
            Thread.sleep(1000);
        } catch(InterruptedException e) {}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    public class Hilos extends AsyncTask<Void, Void, Boolean> {
        String valor;
        Cursor cursor;
        DataBaseManager manager;

       public Hilos(String parametro){
           valor = parametro;
       }

        @Override
        protected Boolean doInBackground(Void... params) {
        boolean pasar = true;

            if(valor.equals("drunk blocker")) {
                for (int i = 0; i < 10; i++) {

                    HacerUnaPausa();
                    if (!estado_drunk_blocker.isChecked()) {
                       Toast.makeText(MainActivity.this,"Entre en la cancelacion",Toast.LENGTH_SHORT).show();
                        cancel(true);
                        pasar = false;
                        break;
                    }

                }

                if (pasar) {
                    startActivity(new Intent(MainActivity.this,Drunk_Blocker.class));
                    cancel(true);
                }
            }


            if (valor.equals("bd")){
                Actualizar_Alarmas();
                Verificar_Hilo_Alarma();
            }

            return true;
        }

        @Override
        protected void onPreExecute() {

            if(valor.equals("drunk blocker")) {
                Toast.makeText(MainActivity.this,"Cuenta con 10 segundos antes del bloqueo",Toast.LENGTH_SHORT).show();
            }


        }

        public void Actualizar_Alarmas(){
            manager = new DataBaseManager(MainActivity.this);
            cursor = manager.Cargar_Cursor_Alarmas();

            int posicion = 1;
            if (cursor.moveToFirst()){
                do {
                    String id = cursor.getString(0);
                    String horas = cursor.getString(1);
                    String minutos = cursor.getString(2);
                    String horario = cursor.getString(3);
                    String etiqueta = cursor.getString(4);
                    String estado_alarma = cursor.getString(5);

                    AgregarAlarma_ConPos(horas + ":" + minutos + " " + horario + "       " + etiqueta + " ---" + estado_alarma, posicion);
                    posicion++;
                }while(cursor.moveToNext());

                cursor.close();

            }
        }

        public void Verificar_Hilo_Alarma(){
            manager = new DataBaseManager(MainActivity.this);
            cursor = manager.Cargar_Cursor_Alarmas();

            if (cursor.moveToFirst()){
                do {
                    String id = cursor.getString(0);
                    String horas = cursor.getString(1);
                    String minutos = cursor.getString(2);
                    String horario = cursor.getString(3);
                    String etiqueta = cursor.getString(4);
                    String estado_alarma = cursor.getString(5);
                    if (estado_alarma.equals("activa")){
                       // Toast.makeText(MainActivity.this,"Si hay una alarma activa!!",Toast.LENGTH_LONG).show();
                      //  manager.Insertar_Tabla_Estado_Hilo(0);
                       // int probando=Buscar_Datos_Hilo(manager);
                        //Toast.makeText(MainActivity.this,"probando : "+probando+"",Toast.LENGTH_LONG).show();

                        //if (probando==1){
                   //       Toast.makeText(MainActivity.this,"Si veo TABLAAAAAAAA!!",Toast.LENGTH_LONG).show();
                        //  cursor.moveToLast();
                          //manager.Modificar_Campo_Tabla_Hilo("1",1);
                          startService(new Intent(MainActivity.this,MyService.class));
                          cancel(true);
                          onCancelled();
                          break;

                       //}
                    }
                    }while(cursor.moveToNext());

                cursor.close();
            }
        }

    }
}

第一次成功运行到达并且两次都相等时被重定向到报警活动,该报警活动完成了应该的操作并重定向到主活动,在尝试创建或修改新的arlama以输入数据时出现问题按Pin接受线程执行错误生成,表示线程已经运行且无法再次运行。

我结束每条线都满足了我感兴趣的条件,而不是第二次运行或者如果活动重定向没有成功停止并且一些puntoo重新运行服务,也许可能是主要活动未在适配器中完成甚至虽然您控制活动并作为参数工作适配器和

public adapter (Activity act ....) {

activity = act;
    }

代码适配器(个人适配器)

public class adaptador extends BaseExpandableListAdapter {
    private final SparseArray<GrupoDeItems> grupos;
    public LayoutInflater inflater;
    public Activity activity;
    MainActivity obj = new MainActivity();

    // Constructor
    public adaptador(Activity act, SparseArray<GrupoDeItems> grupos) {
        activity = act;
        this.grupos = grupos;
        inflater = act.getLayoutInflater();
    }

    // Nos devuelve los datos asociados a un subitem en base
    // a la posición

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return grupos.get(groupPosition).children.get(childPosition);
    }

    // Devuelve el id de un item o subitem en base a la
    // posición de item y subitem

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return 0;
    }

    // En base a la posición del item y de subitem nos devuelve
    // el objeto view correspondiente y el layout para los subitems

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final String children = (String) getChild(groupPosition, childPosition);
        TextView textvw = null;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.subitems_layout, null);
        }
        textvw = (TextView) convertView.findViewById(R.id.textView1);
        textvw.setText(children);
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        Intent ine = new Intent();
                //Esto emite una pequeña ventana de alerta con el mensaje seleccionado
                //Toast.makeText(activity, children, Toast.LENGTH_SHORT).show();
                switch (groupPosition){
                    case 0:
                        ine.setClass(activity,Drunk_Blocker.class);
                        switch (childPosition){
                          case 0:
                                activity.startActivity(ine);
                                //obj.GenerarSaltos(activity,Drunk_Blocker.class);
                                break;

                          case 1:
                                activity.startActivity(ine);
                                //obj.GenerarSaltos(activity,Drunk_Blocker.class);
                                break;
                        }
                        break;
                    case 1:

                        DataBaseManager manager = new DataBaseManager(activity);
                        Cursor cursor = manager.Cargar_Cursor_Alarmas();
                        cursor.moveToFirst();
                        switch (childPosition){
                            case 0:
                                ine.setClass(activity,Nueva_Alarma.class);
                                if(cursor.getCount()<3) {
                                    activity.finish();
                                    activity.startActivity(ine);
                                }
                                else
                                   Toast.makeText(activity,"Solo puede tener 1 alarma",Toast.LENGTH_SHORT).show();
                                //obj.GenerarSaltos(activity,Alarma.class);
                                break;
                            case 1:
                                activity.finish();
                                ine.setClass(activity,Modificar_Alarma.class);
                                ine.putExtra("identificador",cursor.getString(0));
                                activity.startActivity(ine);
                                break;

                            case 2:
                                cursor.moveToPosition(1);
                                ine.setClass(activity,Modificar_Alarma.class);
                                ine.putExtra("identificador",cursor.getString(0));
                                activity.startActivity(ine);
                                break;

                            case 3:
                          /*      cursor.moveToPosition(2);
                                ine.setClass(activity,Modificar_Alarma.class);
                                ine.putExtra("identificador",cursor.getString(0));
                                activity.startActivity(ine);
                                break;

                            case 4:
                                cursor.moveToPosition(3);
                                ine.setClass(activity,Modificar_Alarma.class);
                                ine.putExtra("identificador",cursor.getString(0));
                                activity.startActivity(ine);
                                break;

                            case 5:
                                cursor.moveToPosition(4);
                                ine.setClass(activity,Modificar_Alarma.class);
                                ine.putExtra("identificador",cursor.getString(0));
                                activity.startActivity(ine);
                                break;*/
                            //asigna una imagen a un teim o subitem
                            //textvw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.pescadofrito, 0, 0, 0);

                        }
                        cursor.close();
                       // 
                        break;
                }
            }
        });

        textvw.setText(children);

        return convertView;
    }

    // Nos devuelve la cantidad de subitems que tiene un ítem
    @Override
    public int getChildrenCount(int groupPosition) {
        return grupos.get(groupPosition).children.size();
    }


    //Los datos de un ítem especificado por groupPosition
    @Override
    public Object getGroup(int groupPosition) {
        return grupos.get(groupPosition);
    }

    //La cantidad de ítem que tenemos definidos
    @Override
    public int getGroupCount() {
        return grupos.size();
    }

    //Método que se invoca al contraer un ítem
    @Override
    public void onGroupCollapsed(int groupPosition) {
        super.onGroupCollapsed(groupPosition);
    }

    //Método que se invoca al expandir un ítem
    @Override
    public void onGroupExpanded(int groupPosition) {
        super.onGroupExpanded(groupPosition);
    }

    //Devuelve el id de un ítem
    @Override
    public long getGroupId(int groupPosition) {
        return 0;
    }

    //Obtenemos el layout para los ítems
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.items_layout, null);
        }
        GrupoDeItems grupo = (GrupoDeItems) getGroup(groupPosition);
        ((CheckedTextView) convertView).setText(grupo.string);
        ((CheckedTextView) convertView).setChecked(isExpanded);
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    //Nos informa si es seleccionable o no un ítem o subitem
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}

Code Myservice(线程警报)

public class MyService extends Service {
    Intent salto = new Intent();
    MyTask myTask;

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Alarma creada!", Toast.LENGTH_LONG).show();
        myTask = new MyTask();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Toast.makeText(this,"Antes de ejecutar------------------ "+myTask.getStatus().toString(),Toast.LENGTH_LONG).show();
        if (myTask.getStatus().toString().equals("FINISHED") || myTask.getStatus().toString().equals("PENDING")) {

            if (myTask.getStatus().toString().equals("RUNNING")){
                myTask.cancel(true);
            }

            myTask.execute();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
      //  Toast.makeText(getApplicationContext(), "Alarma cancelada!", Toast.LENGTH_SHORT).show();
        myTask.cancel(true);
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void GenerarSaltos(Activity origen, Class destino){
        salto.setClass(origen,destino);
        startActivity(salto);
    }

public class MyTask extends AsyncTask<String, String, String> {

    private DateFormat dateFormat;
    private String date;
    private boolean cent;
    DataBaseManager manager;
    Cursor cursor;
    ArrayList<String> vec2 = new ArrayList<String>();
  /*  public MyTask(Activity act){
        manager = new DataBaseManager(act);
        activity2 = act;
    }*/

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dateFormat = new SimpleDateFormat("HH:mm:ss");
        cent = true;
        manager = new DataBaseManager(getApplicationContext());
    }

    @Override
    protected String doInBackground(String... params) {
        String cadena;
        String[] vec;
        int horas_sys=0,minutos_sys=0,segundos_sys=0;
        while (cent){
            date = dateFormat.format(new Date());
            cursor = manager.Cargar_Cursor_Alarmas();
            cadena = date;
            vec = cadena.split(":");
            horas_sys =  Integer.parseInt(vec[0]);
            minutos_sys =  Integer.parseInt(vec[1]);
            segundos_sys =  Integer.parseInt(vec[2]);
            if (horas_sys>12){
                horas_sys = horas_sys - 12;
            }else{
                if (horas_sys==0){
                    horas_sys=12;
                }
            }

           // publishProgress(horas_sys+" "+minutos_sys+" "+segundos_sys);
            cursor.moveToFirst();
            if (cursor.moveToFirst()){
                do {
                    String id = cursor.getString(0);
                    String horas = cursor.getString(1);
                    String minutos = cursor.getString(2);
                    String horario = cursor.getString(3);
                    String etiqueta = cursor.getString(4);
                    String estado_alarma = cursor.getString(5);
                  //  publishProgress("horas sistema: "+horas_sys+" hora alarma: "+horas);
                    if (horas_sys==Integer.parseInt(horas)){
                       // publishProgress("Solo horas: "+horas);

                        if (minutos_sys==Integer.parseInt(minutos)){
                          //publishProgress("Horas: " + horas + " minutos " + minutos);
                            cursor = manager.Cargar_Cursor_Alarmas();
                            vec2 = manager.Recorrer_Cursor(cursor);
                            cadena = Recorrer_ArrayList(vec2);
                            manager.Modificar_Campo("1",cadena);


                            Intent hola = new Intent(getApplicationContext(),Alarma.class);
                                hola.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(hola);

                                cent = false;
                                cancel(true);
                                onCancelled();
                                break;

                            }
                        }
                     }while(cursor.moveToNext());
                    cursor.close();
                }

                if (cent==true){
                    try {
                        // Stop 5s
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                    }
                }


            }
            return null;
        }

        public String Recorrer_ArrayList(ArrayList<String> vec){
            String[] cadena = vec.get(0).split("/");
            String retorno = cadena[0];

            for (int i = 1; i <cadena.length -1 ; i++) {
                retorno = retorno + "/" + cadena[i];
            }

            retorno = retorno + "/" + "noactiva";
            return retorno;
        }

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

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            cent = false;
        }
    }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

AsyncTask只能使用一次。在onCreate()中,您可以创建AsyncTask。在onStartCommand()中,您使用AsyncTask。如果再次调用onStartCommand(),它会再次尝试使用AsyncTask。这是不允许的。

AsyncTask中创建onStartCommand()

答案 1 :(得分:0)

最后通过调用MyService类中的方法stopActivity()来解决问题,当我的条件满足它停止时,完成线程作为服务并正常工作。