在我的第一个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 :(得分:0)
handler.postDelayed(runnable,1000)
,因为永远不会调用run()
。尝试将handler.postDelayed(runnable,1000)
添加到您的' onCreate()'让球滚动。
答案 1 :(得分: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);
}