Android服务运行多次

时间:2016-01-06 04:42:41

标签: android multithreading service notifications pull

我正在制作一个Android应用程序,它将数据作为来自服务器的通知,我已经使用过服务。此服务在后台运行,计时器为30秒。并且每隔30秒,该服务会检查并提取通知,但问题是移动设备的通知数量是实际通知数量的3倍。我不明白发生了什么。 这是我的服务类:

public class NotificationServices extends Service {
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
private final int updateIntercal = 30 * 1000;
private Timer timer = new Timer();
private static final int notificationEx = 0;
private NotificationCompat.Builder mBuilder;
private PendingIntent resultPendingIntent;
int mNotificationId = 001;
private NotificationManager mNotifyMgr;
private Intent resultIntent;
private String messageRecipientId;
private int recipientID = 0;
int counter = 0;
//private boolean lock = false;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Let it continue running until it is stopped.


    //Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    DatabaseHandler dh = new DatabaseHandler(NotificationServices.this);
    try {
        dh.Open();
        recipientID = dh.getRecipientId();
        dh.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    timer.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {
                                      // Check if there are updates here and notify if true
                                      Log.d("Service Counter", counter + "");
                                      counter++;
                                      RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                                      String url = getResources().getString(R.string.apiUrl) + "/registration/checkNotification/recipientID/" + recipientID;
                                      StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                                              new Response.Listener<String>() {
                                                  @Override
                                                  public void onResponse(String response) {


                                                      try {
                                                          Log.d("Response notification", response);
                                                          mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                                                          JSONObject jsonObject = new JSONObject(response);
                                                          JSONArray jsonArray = jsonObject.getJSONArray("data");
                                                          for (int i = 0; i < jsonArray.length(); i++) {
                                                              mBuilder = new NotificationCompat.Builder(NotificationServices.this);
                                                              mBuilder.setAutoCancel(true);//removes notification from status bar once clicked on it

                                                              //Vibration
                                                              mBuilder.setVibrate(new long[]{500, 500, 500, 500, 500});
                                                              mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                                                              mBuilder.setLights(Color.RED, 3000, 3000);

                                                              mBuilder.setSmallIcon(R.drawable.notification_icon)
                                                                      .setContentTitle(jsonArray.getJSONObject(i).getString("subject"))
                                                                      .setContentText(jsonArray.getJSONObject(i).getString("messageBody"));


                                                              //Passing the category to MainActivity Using Bundle
                                                              Bundle bundle = new Bundle();
                                                              bundle.putInt("message_recipientID", jsonArray.getJSONObject(i).getInt("message_recipientID"));
                                                              bundle.putString("Category", jsonArray.getJSONObject(i).getString("category"));
                                                              bundle.putInt("studentId", jsonArray.getJSONObject(i).getInt("studentID"));
                                                              bundle.putString("Subject", jsonArray.getJSONObject(i).getString("subject"));
                                                              bundle.putString("Message", jsonArray.getJSONObject(i).getString("messageBody"));
                                                              bundle.putString("Date", jsonArray.getJSONObject(i).getString("dateScheduled"));
                                                              bundle.putBoolean("FromNotification", true);


                                                              //For action of notification, use PendingIntent
                                                              resultIntent = new Intent(NotificationServices.this, MainActivity.class);
                                                              resultIntent.putExtras(bundle);//passing the bundle in the resultIntent
                                                              resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                                              Log.d("BundleValues", bundle.getInt("studentId") + " " + bundle.getString("Message"));


                                                              resultPendingIntent = PendingIntent.getActivity(NotificationServices.this, mNotificationId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                                                              mBuilder.setContentIntent(resultPendingIntent);
                                                              //Log.d("BundleValuesAfter", bundle.getInt("studentId")+" "+bundle.getString("Message"));

                                                              mNotifyMgr.notify(mNotificationId, mBuilder.build());//Sends the notification
                                                              mNotificationId++;
                                                              //messageRecipientId = jsonArray.getJSONObject(i).getString("message_recipientID");

                                                              //Getting the current date to send to the server
                                                              Calendar c = Calendar.getInstance();
                                                              SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                                              String formattedDate = df.format(c.getTime());
                                                              Log.d("seedate", formattedDate);

                                                              //save the message into SQLite Database
                                                              DatabaseHandler dh = new DatabaseHandler(getApplicationContext());
                                                              dh.Open();
                                                              dh.saveNotification(jsonArray.getJSONObject(i).getInt("message_recipientID"),
                                                                      jsonArray.getJSONObject(i).getInt("studentID"),
                                                                      jsonArray.getJSONObject(i).getString("dateScheduled"),
                                                                      jsonArray.getJSONObject(i).getString("messageBody"),
                                                                      jsonArray.getJSONObject(i).getString("subject"),
                                                                      jsonArray.getJSONObject(i).getString("category"));
                                                              dh.close();

                                                              /*//Setting message is recieved
                                                              RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
                                                              //String url = "http://hsm.edu.np/hsmapp/api/registration/notificationSeen/message_recipientID/"
                                                              String url = getResources().getString(R.string.apiUrl) + "/registration/notificationSeen/message_recipientID/"
                                                                      + messageRecipientId + "/date/" + formattedDate;
                                                              StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                                                                      new Response.Listener<String>() {
                                                                          @Override
                                                                          public void onResponse(String response) {
                                                                              Log.d("Response", response);

                                                                          }
                                                                      }, new Response.ErrorListener() {
                                                                  @Override
                                                                  public void onErrorResponse(VolleyError error) {
                                                                      Log.d("Response", error.toString());

                                                                  }
                                                              });
                                                              queue.add(stringRequest);*/
                                                          }

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

                                                      } catch (SQLException e) {
                                                          e.printStackTrace();

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

                                                      }

                                                  }

                                              }

                                              , new Response.ErrorListener()

                                      {
                                          @Override
                                          public void onErrorResponse(VolleyError error) {
                                              Log.d("Response", "error" + error);
                                          }
                                      }

                                      );
                                      queue.add(stringRequest);

                                  }

                              }

            , 0, updateIntercal);


    return START_STICKY;
}

private void stopService() {
    if (timer != null) timer.cancel();
    Log.d("Service Status:", "Stopped");
}


@Override
public void onDestroy() {
    super.onDestroy();
    if (timer != null) {
        timer.cancel();
    }
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}

}

我已经在启动活动中启动了这项服务,如下所示:

 startService(new Intent(SplashScreen.this, NotificationServices.class));

我最近正在学习这种方法,所以任何人都可以帮助我,我做错了什么?我不知道问题是什么?

0 个答案:

没有答案