2016-08-29 5 views
0

Работа над моим первым приложением для Android, поэтому я полный noob, поэтому я, вероятно, совершу глупую ошибку, но я не могу периодически получать текст уведомления. Он работает, если я нажму кнопку переключения, но я хочу, чтобы уведомление автоматически обновлялось, если номер недели изменился, и обновить уведомление тихо. Включен фрагмент моего кода, спасибо за помощь заранее.Обновление уведомлений от Android периодически не работает (проблема с обработчиком?)

import android.app.NotificationManager; 
import android.content.Context; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.app.NotificationCompat; 
import android.util.Log; 
import android.os.Handler; 
import android.widget.CompoundButton; 
import android.widget.ToggleButton; 

import java.util.Calendar; 

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "MyActivity"; 


    public void createNotification() { 

     final Calendar now = Calendar.getInstance(); 
     now.get(Calendar.WEEK_OF_YEAR); 

     int weekId = 1; 
     final NotificationCompat.Builder nBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
       .setContentTitle("Week") 
       .setContentText(""+now.get(Calendar.WEEK_OF_YEAR)) 
       .setSmallIcon(R.drawable.ic_stat_name); 
     final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     NM.notify(weekId, nBuilder.build()); 

    } 

    // Init 
    private Handler handler = new Handler(); 
    private Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      createNotification(); 
      Log.i(TAG, "updated"); 
      handler.postDelayed(runnable,1000); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton); 
     toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked) { 
        // The toggle is enabled 
        createNotification(); 
       } else { 
        // The toggle is disabled 
        NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
        NM.cancelAll(); 
       } 
      } 
     }); 
    } 


} 

ответ

0

handler.postDelayed(runnable,1000) никогда не называют, потому что run() никогда не вызывается. Попробуйте добавить handler.postDelayed(runnable,1000) в свой 'onCreate()', чтобы получить мяч.

+0

Спасибо за помощь! Теперь работает. Интересно, как в соответствии с Logcat обработчик в режиме onCreate запускается один раз, тогда похоже, что он ссылается на исходный обработчик и продолжает зацикливать его, когда «убивает» «onCreate». – UberNoob

0

Это сработало:

if (isChecked) { 
    // The toggle is enabled 
    handler.postDelayed(runnable,1000); 
} else { 
    // The toggle is disabled 
    NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    NM.cancel(1); 
} 

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

  • Нет связанных вопросов^_^