2016-10-04 8 views
-3

実際、私は、非同期タスクを実行するサービスを持っていますが、これを達成するにはPHPのwebserviceでid GETをチェックしてください。 mysqlは変更時に通知しません im newです。私は適切なリスナーを作成する方法がわかりません。Androidでmysqlデータベースの変更を聴く方法

私のコード:

import android.app.IntentService; 
    import android.app.Notification; 
    import android.app.NotificationManager; 
    import android.app.Service; 
    import android.content.Intent; 
    import android.graphics.Bitmap; 
    import android.graphics.BitmapFactory; 
    import android.media.RingtoneManager; 
    import android.os.AsyncTask; 
    import android.os.Handler; 
    import android.os.IBinder; 
    import android.os.Looper; 
    import android.support.v4.app.NotificationCompat; 
    import android.util.Log; 
    import android.view.Menu; 



    import com.android.volley.DefaultRetryPolicy; 
    import com.android.volley.Request; 
    import com.android.volley.RequestQueue; 
    import com.android.volley.Response; 
    import com.android.volley.VolleyError; 
    import com.android.volley.toolbox.JsonObjectRequest; 
    import com.android.volley.toolbox.StringRequest; 
    import com.android.volley.toolbox.Volley; 
    import com.fda.agil_eat.ActividadPrincipal; 
    import com.fda.agil_eat.Adaptadores.Adaptador_Pedido_Hecho; 
    import com.fda.agil_eat.Fragmento_Menu; 
    import com.fda.agil_eat.MyApplication; 
    import com.fda.agil_eat.R; 
    import com.fda.agil_eat.SharedPref; 
    import com.fda.agil_eat.modelo.PedidoHecho; 
    import com.fda.agil_eat.tools.Constantes; 

    import org.json.JSONArray; 
    import org.json.JSONException; 
    import org.json.JSONObject; 

    import java.text.SimpleDateFormat; 
    import java.util.ArrayList; 
    import java.util.Arrays; 
    import java.util.Date; 
    import java.util.HashMap; 
    import java.util.List; 
    import java.util.Map; 
    import java.util.Random; 
    import java.util.Timer; 
    import java.util.TimerTask; 

    public class RSSPullService extends Service { 
     // constant 
     public static final long NOTIFY_INTERVAL = 5 * 1000; // 10 seconds 
     public RequestQueue mQueue; 
     private Timer mtimer; 


// run on another Thread to avoid crash 
     private Handler mHandler = new Handler(); 
     private Handler segundoHandler = new Handler(); 
     private Timer mTimer = null; 
     public TimeDisplayTimerTask tsk = new TimeDisplayTimerTask(); 

public static String nombredelivery; 
public static String itemspedido; 
public static String aclaracionespedido; 
public static String direccionpedido; 
public static String telefonopedido; 
public static String montopedido; 
public static String iddelivery; 
public static int cantPedidos = 0; 
public static boolean enviapedido=false; 
public static ArrayList<String> listapedidos = new ArrayList<String>(); 
public static ArrayList<String> listapedidosaborrar = new ArrayList<String>(); 
public static ArrayList<PedidoHecho> listadoPedidos = new ArrayList<PedidoHecho>(); 
public static Adaptador_Pedido_Hecho adaptador_pedido_hecho=new Adaptador_Pedido_Hecho(listadoPedidos); 

public Runnable myRunnable = new Runnable() { 
    @Override 
    public void run() { 
     //Do Something 
     task(); 

    } 
}; 
public Runnable myRunnable2 = new Runnable() { 
    @Override 
    public void run() { 
     //Do Something 

     task2(); 
    } 
}; 
class TimeDisplayTimerTask extends TimerTask { 

    @Override 
    public void run() { 
     // run on another thread 
     mHandler.post(myRunnable); 
     segundoHandler.post(myRunnable2); 

    } 

} 


public static String tiempo; 
public void task() { 
    if (enviapedido) { 
     new AscyncPedido().execute(); 
     enviapedido=false; 
    } 

} 
    public List<String> colaAsync = new ArrayList<>(); 
public void task2(){ 
    ArrayList<String> listapedidos2=listapedidos; 
    if (listapedidos2.size()>0) { 
     for (String ped : listapedidos2) { 
      final String idpedido = ped; 
      int e = listapedidos2.indexOf(ped); 
      String estado = ""; 
      for (PedidoHecho p:listadoPedidos) { 
       if (p.id.equals(idpedido)){ 
        estado=p.estado; 
       } 

      } 
      if (estado.toLowerCase().equals("enviado")) { 
       if (colaAsync.indexOf(ped)==(-1)){ 
        new AscyncAprobacion().execute(idpedido); 
        colaAsync.add(ped); 
       } 

      } 
     } 
     boolean todos_tienen_respuesta=true; 
     for (PedidoHecho unpedido:listadoPedidos) { 
      if(unpedido.estado.toLowerCase().equals("enviado")){ 
       todos_tienen_respuesta=false; 
      } 
     } 
     if (todos_tienen_respuesta) { 
      if (listapedidosaborrar.size() > 0) { 
       for (String i : listapedidosaborrar) { 
        try { 
         listapedidos.remove(i); 
        } catch (Exception e) { 
         // //e.printStackTrace(); 
        } 
       } 
      } 
     } 
    } 

} 



public class AscyncAprobacion extends AsyncTask<String, Integer, Void> { 
     //  boolean HayPedido = false; 
    //  int contador=0; 
    //  boolean notificada=false; 
      @Override 
    protected void onPreExecute() { 

    } 

    @Override 
    protected Void doInBackground(final String... params) { 
     Thread 
       splashTread = new Thread() { 

      @Override 
      public void run() { 




        try { 

         getapr(params[0]); 



           sleep(3000); 


        }catch (InterruptedException e) { 

        } finally { 

        } 
       } 


     }; 
     splashTread.start(); 
     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values){ 

    } 

    @Override 
    protected void onPostExecute(Void result) { 

     // FragmentoInicio.this.adaptador.notifyDataSetChanged(); 
    } 
} 

    public void getapr(final String idped) { 
boolean continuar = false; 
final String idpedido = idped; 
for (PedidoHecho pedi : listadoPedidos) { 
    if (pedi.id.equals(idpedido)) { 
     if (pedi.estado.toLowerCase().equals("enviado")) { 
      continuar = true; 
     } else { 
      return; 
     } 
    } 

} 
if (continuar) { 

    try { 
     if (mQueue != null) { 
      mQueue.cancelAll(this.getClass().getName()); 
     } 
    } catch (Exception exx) { 
     Log.e("Cancel queue", exx.toString()); 
    } 

    try { 


     String url = Constantes.Aprobado + "?id=" + idpedido; 
     Log.e("apr", url); 
     StringRequest stringRequest1 = new StringRequest(url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 


        try { 
         JSONObject obj = new JSONObject(response); 
         // String aprobado; 
         String respuesta = obj.getString("aprobada"); 
         switch (respuesta.toUpperCase()) { 
          case "SI": 

           Handler mHandler1 = new Handler(Looper.getMainLooper()); 
           mHandler1.post(new Runnable() { 
            @Override 
            public void run() { 
             try { 
              if (mQueue != null) { 
               mQueue.cancelAll(this.getClass().getName()); 
              } 
             } catch (Exception e) { 
              Log.e("Cancel queue", e.toString()); 
             } 
             try { 
              String url = Constantes.Tiempo + "?id=" + idpedido; 
              Log.e("time", url); 

              StringRequest stringRequest2 = new StringRequest(url, new Response.Listener<String>() { 
               @Override 
               public void onResponse(String response) { 
                boolean existe = false; 
                try { 
                 JSONObject obj = new JSONObject(response); 
                 String respuesta = obj.getString("tiempo"); 
                 Log.e("tiempo", respuesta); 
                 tiempo = respuesta; 
                 int i = listapedidos.indexOf(idpedido); 

                 for (String it : listapedidosaborrar) { 
                  if (it.equals(idpedido)) { 
                   existe = true; 
                  } 

                 } 
                 if (!existe) { 
                  try { 
                   String est = ""; 
                   listapedidosaborrar.add(idpedido); 
                   for (PedidoHecho pp : listadoPedidos) { 
                    if (pp.id.equals(idpedido)) { 
                     est = pp.estado; 
                     pp.estado = "Aprobado"; 
                     pp.detalleestado = tiempo; 
                     pp.horapedido = getCurrentTimeStamp(); 
                    } 

                   } 


                   adaptador_pedido_hecho.notifyDataSetChanged(); 

                   if (est.toLowerCase().equals("enviado")) { 
                    Bitmap aBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); 

                    NotificationCompat.Builder builder = new NotificationCompat.Builder(RSSPullService.this.getApplicationContext()) 
                      .setSmallIcon(R.drawable.minilogo).setLargeIcon(aBitmap) 
                      .setTicker("Noticias de tu Pedido!!") 
                      .setContentTitle("Noticias de tu Pedido!!") 
                      .setContentText("Tu pedido fue aprobado!!\n" + "Llegada aproximada en : " + tiempo) 
                      .setAutoCancel(true) 
                      .setTicker("Tu pedido fue aprobado!!\n" + "Llegada aproximada en : " + tiempo) 
                      .setStyle(new NotificationCompat.BigTextStyle().bigText("Noticias de tu Pedido!!")) 
                      .setStyle(new NotificationCompat.BigTextStyle().bigText("Tu pedido fue aprobado!!\n" + "Llegada aproximada en : " + tiempo)) 
                      .setPriority(Notification.PRIORITY_MAX) 
                      .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) 
                      .setVibrate(new long[]{1, 1, 1}) 
                      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
                      .setDefaults(Notification.DEFAULT_SOUND) 
                      .setDefaults(Notification.DEFAULT_ALL); 
                    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
                    Notification notify = new Notification(); 
                    notify.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_ONLY_ALERT_ONCE; 
                    Random random = new Random(); 
                    notificationmanager.notify(random.nextInt(), builder.build()); 
                    new NotificarInforme().execute(idpedido); 
                   } 
                  } catch (Exception e) { 
                   // //e.printStackTrace(); 
                  } 

                 } 
                } catch (JSONException e) { 
                 // //e.printStackTrace(); 
                } 
               } 
              }, 
                new Response.ErrorListener() { 
                 @Override 
                 public void onErrorResponse(VolleyError error) { 
                  //Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show(); 
                 } 
                }); 

              stringRequest2.setRetryPolicy(new DefaultRetryPolicy(15000, 6, 6)); 
              if (mQueue == null) { 
               mQueue = MyApplication.getInstance() 
                 .getRequestQueue(); 
               mQueue.add(stringRequest2); 
              } else { 
               mQueue.add(stringRequest2); 
              } 
             } catch (Exception e) { 
              Log.e("EX", e.toString()); 

             } 
            } 

           }); 


           break; 
          case "NO": 

           Handler mHandler2 = new Handler(Looper.getMainLooper()); 
           mHandler2.post(new Runnable() { 
            @Override 
            public void run() { 
             try { 
              if (mQueue != null) { 
               mQueue.cancelAll(this.getClass().getName()); 
              } 
             } catch (Exception e) { 
              Log.e("Cancel queue", e.toString()); 
             } 
             try { 
              String url = Constantes.Tiempo + "?id=" + idpedido; 
              Log.e("time", url); 

              StringRequest stringRequest2 = new StringRequest(url, new Response.Listener<String>() { 
               @Override 
               public void onResponse(String response) { 
                boolean existe = false; 
                try { 
                 JSONObject obj = new JSONObject(response); 
                 String respuesta = obj.getString("tiempo"); 
                 Log.e("tiempo", respuesta); 
                 tiempo = respuesta; 
                 int i = listapedidos.indexOf(idpedido); 

                 for (String it : listapedidosaborrar) { 
                  if (it.equals(idpedido)) { 
                   existe = true; 
                  } 

                 } 
                 if (!existe) { 
                  try { 
                   String est = ""; 
                   listapedidosaborrar.add(idpedido); 
                   for (PedidoHecho pp : listadoPedidos) { 
                    if (pp.id.equals(idpedido)) { 
                     est = pp.estado; 
                     pp.estado = "Rechazado"; 
                     pp.horapedido = getCurrentTimeStamp(); 
                     if (tiempo.equals(" ")) { 
                      pp.detalleestado = "El Lugar lo Rechazo..."; 
                     } else { 
                      pp.detalleestado = tiempo; 
                     } 

                    } 

                   } 


                   adaptador_pedido_hecho.notifyDataSetChanged(); 

                   if (est.toLowerCase().equals("enviado")) { 
                    Bitmap aBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); 

                    NotificationCompat.Builder builder = new NotificationCompat.Builder(RSSPullService.this.getApplicationContext()) 
                      .setSmallIcon(R.drawable.minilogo).setLargeIcon(aBitmap) 
                      .setTicker("Noticias de tu Pedido!!") 
                      .setContentTitle("Noticias de tu Pedido!!") 
                      .setContentText("Tu pedido fue Rechazado...\n" + "El Local/Establecimiento rechazo tu pedido") 
                      .setAutoCancel(true) 
                      .setTicker("Tu pedido fue Rechazado...\n" + "El Local/Establecimiento rechazo tu pedido") 
                      .setStyle(new NotificationCompat.BigTextStyle().bigText("Noticias de tu Pedido!!")) 
                      .setStyle(new NotificationCompat.BigTextStyle().bigText("Tu pedido fue Rechazado...\n" + "El Local/Establecimiento rechazo tu pedido")) 
                      .setPriority(Notification.PRIORITY_MAX) 
                      .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) 
                      .setVibrate(new long[]{1, 1, 1}) 
                      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
                      .setDefaults(Notification.DEFAULT_SOUND) 
                      .setDefaults(Notification.DEFAULT_ALL); 
                    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
                    Notification notify = new Notification(); 
                    notify.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_ONLY_ALERT_ONCE; 
                    Random random = new Random(); 
                    notificationmanager.notify(random.nextInt(), builder.build()); 
                    new NotificarInforme().execute(idpedido); 
                   } 
                  } catch (Exception e) { 


                   //   //e.printStackTrace(); 
                  } 

                 } 
                } catch (JSONException e) { 
                 //  //e.printStackTrace(); 
                } 
               } 
              }, 
                new Response.ErrorListener() { 
                 @Override 
                 public void onErrorResponse(VolleyError error) { 
                  //Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show(); 
                 } 
                }); 

              stringRequest2.setRetryPolicy(new DefaultRetryPolicy(15000, 6, 6)); 
              if (mQueue == null) { 
               mQueue = MyApplication.getInstance() 
                 .getRequestQueue(); 
               mQueue.add(stringRequest2); 
              } else { 
               mQueue.add(stringRequest2); 
              } 
             } catch (Exception e) { 
              Log.e("EX", e.toString()); 

             } 
            } 

           }); 


           break; 
          default: 
           Handler mHandler3 = new Handler(Looper.getMainLooper()); 
           mHandler3.post(new Runnable() { 
            @Override 
            public void run() { 

              getapr(idped); 


            } 
           }); 
           break; 
         } 

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

      } 
     }, 
       new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         getapr(idped); //Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show(); 
        } 
       }); 

     stringRequest1.setRetryPolicy(new DefaultRetryPolicy(15000, 6, 6)); 
     if (mQueue == null) { 
      mQueue = MyApplication.getInstance() 
        .getRequestQueue(); 
      mQueue.add(stringRequest1); 
     } else { 
      mQueue.add(stringRequest1); 
     } 

    } catch (Exception ex) { 
     Log.e("EX", ex.toString()); 

    } 
} 
    } 

感謝!

+0

申し訳ありません私の虚偽の英語{} –

+0

あなたは正しいですMYSQLは誰にも変更を通知しません。あなたがそれが起こることを望むなら、あなたのためにそれを行う何かを書かなければならないでしょう – RiggsFolly

答えて

0

MySQLデータベースでは、GCMや他のサービスを介してアンドロイドにデータを受信するようリクエストしています。あなたにとって信頼できるものです。

+0

これを説明する例またはリンクを与えることができますか?かなり新しい –

+0

携帯電話にGCM通知を統合し、データベースが変更されたときにサーバー側から通知をプッシュするように呼び出すとき。アンドロイド側でnotificationIDを受信し、それに基づいて更新するAPI呼び出しを行います。このリンクを確認してくださいhttp://www.androidhive.info/2016/02/android-push-notifications-using-gcm-php-mysql-realtime-chat-app-part-1/ –

関連する問題