2015-12-11 2 views
0

Я делаю приложение, которое требует push notfications. У меня есть push-уведомления, и я могу установить время для уведомлений. Единственное, что я должен в лик радиокнопок поэтому при выборе rabiobutton1 уведомление в 1 минуту, radiobutto2 10 минут и т.д. Ниже мой код для уведомлений:Уведомления о конкретном времени в java

public void onClick(View v) { 
    Intent i = new Intent(Settings.this, Start.class); 
    startActivity(i); 

    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       // 10 minutes * 60000 milliseconds(1 minute) 
       Thread.sleep(60000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 


      Intent intent = new Intent(); 
      PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent, 0); 
      Notification noti = new Notification.Builder(Settings.this) 
        .setTicker("TickerTitle") 
        .setContentTitle("Price-Watch") 
        .setContentText("Check Your Items Price") 
        .setSmallIcon(R.mipmap.pw) 
        .setContentIntent(pIntent).getNotification(); 
        noti.flags = Notification.FLAG_AUTO_CANCEL; 
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
        nm.notify(0, noti); 
       } 
      }).start(); 

Кто-нибудь знает, как я сделал бы это? Я огляделся и не мог найти ничего, что могло бы помочь мне. Im новичок в java и андроид-студиях, поэтому заблаговременно за любую помощь

ответ

0

Я не уверен, если меня поймут, но я надеюсь помочь вам.

Вы можете попробовать несколько подобных.

1) Получите свою радиогруппу и установите слушателя.

RadioGroup radioTimeGroup = (radioTimeGroup)findViewById(R.id.radioTimeGroup); 

final long selectedTime = 0l; 

radioTimeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
    public void onCheckedChanged(RadioGroup group, int checkedId) { 

     switch(checkedId) { 
      case R.id.rdbOpcion1: 
       selectedTime = 60000;//1 minute 
       break; 
      case R.id.rdbOpcion2: 
       selectedTime = 60000 * 10;//10 minute 
       break; 

      default: 
       //Your default action. 
       break; 
     } 
    } 
}); 

2) Установить выбранное время

new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       Thread.sleep(selectedTime); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 

      Intent intent = new Intent(); 
      PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent, 0); 
      Notification noti = new Notification.Builder(Settings.this) 
        .setTicker("TickerTitle") 
        .setContentTitle("Price-Watch") 
        .setContentText("Check Your Items Price") 
        .setSmallIcon(R.mipmap.pw) 
        .setContentIntent(pIntent).getNotification(); 
        noti.flags = Notification.FLAG_AUTO_CANCEL; 
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
        nm.notify(0, noti); 
       } 
      }).start(); 

В этом случае вы также можете использовать обработчик и конкретный него postDelay

new Handler().postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       Intent intent = new Intent(); 
       PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent, 0); 
       Notification noti = new Notification.Builder(Settings.this) 
         .setTicker("TickerTitle") 
         .setContentTitle("Price-Watch") 
         .setContentText("Check Your Items Price") 
         .setSmallIcon(R.mipmap.pw) 
         .setContentIntent(pIntent).getNotification(); 
       noti.flags = Notification.FLAG_AUTO_CANCEL; 
       NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
       nm.notify(0, noti); 
      } 
     }, selectedTime); 

С последним методом вашего кода выполняются после того, как "selectedTime".

PD: Извините за мой низкий уровень английского языка. Я надеюсь помочь вам.

+0

Осторожно о создании анонимного класса обработчика, поскольку это может быть утечка памяти. Попробуйте сделать его статическим классом. –

+0

Спасибо за ваш комментарий Кристи Уэлш. – Crash

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