android 炫酷倒计时连接数据库,并使用广播接收器的完整代码
时间: 2023-12-28 16:06:21 浏览: 62
以下是一个简单的 Android 炫酷倒计时应用的完整代码,其中包括了连接数据库和使用广播接收器的相关代码。
首先,我们需要创建一个数据库帮助类 `CountdownDBHelper`,用于创建和管理数据库:
```java
public class CountdownDBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "countdown.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_COUNTDOWNS = "countdowns";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_DATE = "date";
private static final String CREATE_TABLE_COUNTDOWNS =
"CREATE TABLE " + TABLE_COUNTDOWNS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_TITLE + " TEXT, " +
COLUMN_DATE + " TEXT);";
public CountdownDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_COUNTDOWNS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COUNTDOWNS);
onCreate(db);
}
}
```
接下来,我们需要创建一个 `Countdown` 类,用于表示一个倒计时对象,并实现相关的数据库操作:
```java
public class Countdown {
private long id;
private String title;
private Date date;
public Countdown(long id, String title, Date date) {
this.id = id;
this.title = title;
this.date = date;
}
public long getId() {
return id;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public static List<Countdown> getAllCountdowns(Context context) {
List<Countdown> countdowns = new ArrayList<>();
CountdownDBHelper dbHelper = new CountdownDBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(CountdownDBHelper.TABLE_COUNTDOWNS,
new String[]{CountdownDBHelper.COLUMN_ID, CountdownDBHelper.COLUMN_TITLE, CountdownDBHelper.COLUMN_DATE},
null, null, null, null, null);
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex(CountdownDBHelper.COLUMN_ID));
String title = cursor.getString(cursor.getColumnIndex(CountdownDBHelper.COLUMN_TITLE));
String dateString = cursor.getString(cursor.getColumnIndex(CountdownDBHelper.COLUMN_DATE));
Date date = new Date(Long.parseLong(dateString));
countdowns.add(new Countdown(id, title, date));
}
cursor.close();
db.close();
dbHelper.close();
return countdowns;
}
public static long addCountdown(Context context, String title, Date date) {
CountdownDBHelper dbHelper = new CountdownDBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CountdownDBHelper.COLUMN_TITLE, title);
values.put(CountdownDBHelper.COLUMN_DATE, String.valueOf(date.getTime()));
long id = db.insert(CountdownDBHelper.TABLE_COUNTDOWNS, null, values);
db.close();
dbHelper.close();
return id;
}
public static void deleteCountdown(Context context, long id) {
CountdownDBHelper dbHelper = new CountdownDBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(CountdownDBHelper.TABLE_COUNTDOWNS,
CountdownDBHelper.COLUMN_ID + " = ?",
new String[]{String.valueOf(id)});
db.close();
dbHelper.close();
}
}
```
接下来,我们需要创建一个 `CountdownAdapter` 类,用于将倒计时对象列表展示在 `RecyclerView` 中:
```java
public class CountdownAdapter extends RecyclerView.Adapter<CountdownAdapter.ViewHolder> {
private List<Countdown> countdowns;
private Context context;
public CountdownAdapter(Context context, List<Countdown> countdowns) {
this.context = context;
this.countdowns = countdowns;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public TextView countdownTextView;
public ViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.titleTextView);
countdownTextView = itemView.findViewById(R.id.countdownTextView);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_countdown, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Countdown countdown = countdowns.get(position);
holder.titleTextView.setText(countdown.getTitle());
holder.countdownTextView.setText(getCountdownString(countdown.getDate()));
}
@Override
public int getItemCount() {
return countdowns.size();
}
private String getCountdownString(Date date) {
long diff = date.getTime() - new Date().getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
diff -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(diff);
diff -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
diff -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
return String.format("%02dd %02dh %02dm %02ds", days, hours, minutes, seconds);
}
}
```
接下来,我们需要创建一个 `CountdownActivity` 类,用于处理倒计时的各种操作:
```java
public class CountdownActivity extends AppCompatActivity {
private RecyclerView countdownRecyclerView;
private CountdownAdapter countdownAdapter;
private BroadcastReceiver countdownReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
countdownAdapter.notifyDataSetChanged();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
countdownRecyclerView = findViewById(R.id.countdownRecyclerView);
countdownRecyclerView.setLayoutManager(new LinearLayoutManager(this));
List<Countdown> countdowns = Countdown.getAllCountdowns(this);
countdownAdapter = new CountdownAdapter(this, countdowns);
countdownRecyclerView.setAdapter(countdownAdapter);
LocalBroadcastManager.getInstance(this).registerReceiver(countdownReceiver,
new IntentFilter("countdown-updated"));
FloatingActionButton addCountdownButton = findViewById(R.id.addCountdownButton);
addCountdownButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showAddCountdownDialog();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(countdownReceiver);
}
private void showAddCountdownDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Countdown");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_add_countdown, null);
final EditText titleEditText = view.findViewById(R.id.titleEditText);
final DatePicker datePicker = view.findViewById(R.id.datePicker);
final TimePicker timePicker = view.findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
builder.setView(view);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String title = titleEditText.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
timePicker.getCurrentHour(), timePicker.getCurrentMinute());
long id = Countdown.addCountdown(CountdownActivity.this, title, calendar.getTime());
countdownAdapter.notifyDataSetChanged();
Intent intent = new Intent("countdown-updated");
LocalBroadcastManager.getInstance(CountdownActivity.this).sendBroadcast(intent);
}
});
builder.setNegativeButton("Cancel", null);
builder.show();
}
}
```
最后,我们需要创建一个 `BroadcastReceiver` 类,用于在倒计时结束时发送通知:
```java
public class CountdownReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1;
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(intent.getStringExtra("title"))
.setContentText("Countdown has ended!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default", "Countdown", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
```
以上就是一个简单的 Android 炫酷倒计时应用的完整代码,其中包括了连接数据库和使用广播接收器的相关代码。
阅读全文