基于 Android Studio 的事件安排,设置闹钟提醒且带有打卡功能的代码
时间: 2024-01-25 17:05:32 浏览: 67
基于Android studio的2048游戏设计源代码(高分期末大作业)
以下是基于 Android Studio 的事件安排,设置闹钟提醒且带有打卡功能的代码:
1. 创建一个新的 Android Studio 项目。
2. 在项目的布局文件中添加一个 TextView,一个 Button 和一个 TimePicker。
3. 在 MainActivity.java 文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private Button mButton;
private TimePicker mTimePicker;
private AlarmManager mAlarmManager;
private PendingIntent mPendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
mButton = findViewById(R.id.button);
mTimePicker = findViewById(R.id.time_picker);
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour = mTimePicker.getHour();
int minute = mTimePicker.getMinute();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), mPendingIntent);
Toast.makeText(MainActivity.this, "Alarm set for " + hour + ":" + minute, Toast.LENGTH_SHORT).show();
}
});
}
}
```
4. 创建一个 AlarmReceiver 类,用于接收闹钟提醒广播,并添加以下代码:
```java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm received", Toast.LENGTH_SHORT).show();
//TODO: Add punch function here
}
}
```
5. 在 AlarmReceiver 类中添加打卡功能的代码,例如:
```java
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("punched", true);
editor.apply();
```
6. 在 MainActivity.java 中添加读取打卡状态的代码,例如:
```java
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean punched = sharedPreferences.getBoolean("punched", false);
if (punched) {
mTextView.setText("You have punched");
} else {
mTextView.setText("You have not punched");
}
```
7. 运行应用程序,并设置闹钟提醒。当闹钟响起时,应用程序将显示“Alarm received”,并且打卡状态将更新为“已打卡”。
阅读全文