2015-02-10 2 views
0

Я хочу получать уведомления с сервера с фиксированным интервалом, поэтому я установил этот ответ сервера в службу. Таким образом, в основном я использую Службы для запуска фона и создания уведомлений. Моя проблема в том, что у меня есть уведомления не с фиксированным интервалом. Итак, как получить уведомления с фиксированным интервалом. Я также хочу продолжить мой сервис (получать уведомления), даже если я перезагружу свой телефон. Я немного смутил, что если телефон будет выключен, мне придется перезапустить службу или нет. Если мне нужно перезапустить его, то как я могу справиться с этим. Ваша помощь будет оценена по достоинству. Заранее спасибо.Уведомления с сервисами в android

Alert_notifications.java 
public class Alert_notifications extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_alert_notifications); 
     Button buttonStartService = (Button)findViewById(R.id.startservice); 
     Button buttonStopService = (Button)findViewById(R.id.stopservice); 

     buttonStartService.setOnClickListener(new Button.OnClickListener(){ 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       Intent intent = new Intent(Alert_notifications.this, com.example.gpstracking.NotifyService.class); 
       Alert_notifications.this.startService(intent); 
      }}); 

     buttonStopService.setOnClickListener(new Button.OnClickListener(){ 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       Intent intent = new Intent(); 
       intent.setAction(NotifyService.ACTION); 
       intent.putExtra("RQS", NotifyService.STOP_SERVICE); 
       sendBroadcast(intent); 
      }}); 

    } 
} 



NotifyService.java 


public class NotifyService extends Service { 

    final static String ACTION = "NotifyServiceAction"; 
    final static String STOP_SERVICE = ""; 
    final static int RQS_STOP_SERVICE = 1; 
    private static final String url_Weather_details1="http://198.168.1.2/Weatherforecast1/"; 
    private static final String TAG_SUCCESS = "success"; 


    NotifyServiceReceiver notifyServiceReceiver; 

    private static final int MY_NOTIFICATION_ID = 1; 
    private NotificationManager notificationManager; 
    private Notification myNotification; 
    private final String myBlog = "http://android-er.blogspot.com/"; 

    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     notifyServiceReceiver = new NotifyServiceReceiver(); 
     super.onCreate(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
     JSONParser jsonParser = new JSONParser(); 
     params.add(new BasicNameValuePair("LAT", "LAT")); 
     params.add(new BasicNameValuePair("LONGITUDE", "LONG")); 
     Log.d("params", params.toString()); 
     // getting weather details by making HTTP request 
     // Note that weather details url will use GET request 
     JSONObject json = jsonParser.makeHttpRequest(url_Weather_details1, 
       "GET", params); 
     // check your log for json response 
     Log.d("Weather Details", json.toString()); 

     // json success tag 
     int success = 0; 
     try { 
      success = json.getInt(TAG_SUCCESS); 
      System.out.println("success"+success); 
     } 
     catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     if (success == 2) { 
      // successfully received weather details 

     // TODO Auto-generated method stub 

     IntentFilter intentFilter = new IntentFilter(); 
     intentFilter.addAction(ACTION); 
     registerReceiver(notifyServiceReceiver, intentFilter); 

     // Send Notification 
     notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     myNotification = new Notification(R.drawable.ic_launcher,"Notification!", System.currentTimeMillis()); 

     Context context = getApplicationContext(); 
     String notificationTitle = "Heavy Rain!"; 
     String notificationText = ""; 
     Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog)); 
     PendingIntent pendingIntent = PendingIntent.getActivity(
       getBaseContext(), 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK); 
     myNotification.defaults |= Notification.DEFAULT_SOUND; 
     myNotification.flags |= Notification.FLAG_AUTO_CANCEL; 
     myNotification.setLatestEventInfo(context, notificationTitle, 
       notificationText, pendingIntent); 
     notificationManager.notify(MY_NOTIFICATION_ID, myNotification); 

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

    } 


    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 
     this.unregisterReceiver(notifyServiceReceiver); 
     super.onDestroy(); 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    public class NotifyServiceReceiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      // TODO Auto-generated method stub 
      int rqs = arg1.getIntExtra("RQS", 0); 
      if (rqs == RQS_STOP_SERVICE) { 
       stopSelf(); 
      } 
     } 
    } 

} 
+0

Если вы отправляете уведомление с сервера, вы можете установить cronjob для него и установить/запланировать интервал. Пожалуйста, дайте мне знать, поможет ли эта идея или вам нужно больше разъяснений. – sUndeep

ответ

0

Я бы рекомендовал использовать GCM доставить «PUSH» -notifications для Android клиентов или клиентов в качестве альтернативы может сделать сетевой вызов и проверить, есть ли новые уведомления. Для того, чтобы устройство не спало во время работы Сервиса, вы также должны посмотреть на WakefulBroadcastReceiver или приобрести WakeLock. Если вы хотите перезагрузить свой сервис после загрузки, отметьте также answer, чтобы получить системное событие ACTION_BOOT_COMPLETED на вашем BroadcastReceiver, в котором вы можете перезапустить службу.

Смежные вопросы