我想增加一个数字,并在一天的特定时间使用AlarmManager在TextView中显示它,但它不起作用。 应用正在调试并显示0,但没有增加int数。 请帮助,这是代码。
public class MainActivity extends AppCompatActivity {
TextView tv;
int a = 3;
Calendar calendar = Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
MyAlarm alarm = new MyAlarm();
setAlarm(calendar.getTimeInMillis());
int g = alarm.i;
tv.setText(String.format("%d", g));
}
private void setAlarm(long time) {
calendar.setTimeInMillis(System.currentTimeMillis());
//getting the alarm manager
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//creating a new intent specifying the broadcast receiver
Intent i = new Intent(this, MyAlarm.class);
//creating a pending intent using the intent
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 55);
calendar.set(Calendar.SECOND, 0);
//setting the repeating alarm that will be fired every day
am.setRepeating(AlarmManager.RTC, time, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
}
广泛的演员在这里
public class MyAlarm extends BroadcastReceiver {
int i;
@Override
public void onReceive(Context context, Intent intent) {
i++;
}
}
答案 0 :(得分:0)
要添加默认构造函数,请在MyAlarm类中尝试以下操作:
MyAlarm(){
}
也添加此方法:
public int setI(){
i = i+1;
return i;
}
现在应该是这样:
public class MyAlarm extends BroadcastReceiver{
int i;
MyAlarm(){
i=0;
}
public int setI(){
i = i+1;
return i;
}
@Override
public void onReceive(Context context,Intent intent) {
i++;
}
}
现在,在onCreate()中调用它,它将使i递增。 你可以说
int g = myAlarm.setI();
您的setAlarm()函数中的或您想增加它的任何位置。 g现在将增加。我希望这会有所帮助!