我正在尝试制作一些设定数量每天都会减少的东西,即使该应用已关闭且未激活。例如,如果您没有打开应用程序5天,当您打开它时,该数字将低5个数字。我一直在尝试使用AlarmManager,但我只能让它来制作Toast并且不在主活动中运行一个函数。这是我的代码......
主要活动
private TextView mTest;
private Button mButton;
private int number = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scheduleAlarm();
}
});
}
public void scheduleAlarm(){
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 100000, 100000, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT ));
Toast.makeText(MainActivity.this, "This is starting!", Toast.LENGTH_SHORT).show();
}
public void subtract(){
mTest = (TextView) findViewById(R.id.textView);
number -= 1;
String numberString = Integer.toString(number);
mTest.setText(numberString);
}
这是广播
private MainActivity mMainActivity = new MainActivity();
@Override
public void onReceive(Context context, Intent intent) {
mMainActivity.subtract();
Toast.makeText(context, "This is bogus", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:0)
您可以使用计时器(https://developer.android.com/reference/java/util/Timer.html)
轻松完成此操作请遵循以下示例:
long MINUTE_TO_MSEC = 60000;
long DAY_TO_MSEC = MINUTE_TO_MSEC * 60 * 24;
Timer timer = new Timer();
TimerTask countdownTask = new TimerTask() {
public void run() {
/* your function goes here */
}
}
timer.scheduleAtFixedRate(task,0,DAY_TO_MSEC);
这将每24小时运行一次代码。