Working on my first android app so I am a complete noob so I'm probably making a silly mistake but I cannot get the notification text to update periodically. It works if I reclick the toggle button but I want the notification to update automatically if the week number has changed and to refresh the notification silently. Included a snippet of my code, thanks for the help in advance.
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();
}
}
});
}
}
handler.postDelayed(runnable,1000)
is never being called because run()
is never being called. Try adding a handler.postDelayed(runnable,1000)
to your 'onCreate()' to get the ball rolling.