广播和数据库

广播接收器


动态注册广播接收器


创建一个类继承BroadcastReceiver
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        receiver = new NetworkChangeReceiver();
        registerReceiver(receiver,intentFilter);
  动态注册的必须在OnDestroy方法中注销广播接收器
静态注册
直接AndroidStudio创建
在Manifest文件中添加IntentFilter


发送标准广播
Intent intent = new Intent("......");
sendBroadcast(intent);


发送有序广播
sendOrderedBroadcast(intent,null); 第2个参数是权限相关的
在onreceive方法中调用abortBroadcast将截断广播


使用本地广播
LocalBroadcastManager = LocalBroadcastManager.getInstance(this);
发送和注册广播都通过LocalBroadcastManager来进行管理


本地广播不能用静态注册




将数据存储到文件中
Context类提供了一个openFileOutput()方法获得一个输出流
  private void save(String data){
        FileOutputStream outputStream=null;
        BufferedWriter writer = null;
        try{
            outputStream = openFileOutput("data",MODE_APPEND);
            writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(data);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(writer!=null){
                    writer.close();
                }
                if(outputStream!=null){
                    outputStream.close();
                }
                
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        
    }
从文件中读取数据
private String load(){
        FileInputStream inputStream = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try{
            inputStream = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line=reader.readLine())!=null){
                content.append(line);
            }




        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(reader!=null){
                    reader.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }


            }catch (Exception e){
                e.printStackTrace();
            }


        }
        return content.toString();
    }


将数据存储在sharedpreference中
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("name","张三");
        editor.putBoolean("married",false);
        editor.apply();
从sharedpreference中读取数据
 String name = preferences.getString("name","");
        boolean married = preferences.getBoolean("married",false);


SQLite数据库创建
创建一个类继承SQLiteOpenHelper
public class MyDatabase extends SQLiteOpenHelper {




    private Context mContext;
    public static final String CREATE_BOOK = "create table Book ( " +
            "id integer primary key autoincrement, " +
            "author text, " +
            "price real, " +
            "pages integer," +
            " name text)";
    public MyDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {


        sqLiteDatabase.execSQL(CREATE_BOOK);
        Toast.makeText(mContext,"创建成功!",Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {


    }
}
final MyDatabase database = new MyDatabase(MainActivity.this,"BookStore.db",null,1);
         create.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 database.getWritableDatabase();
             }
         });


   adb shell                generic_x86_64:/ # cd /data/data/com.example.broadcasttest/databases/
generic_x86_64:/data/data/com.example.broadcasttest/databases # ls
BookStore.db BookStore.db-journal
generic_x86_64:/data/data/com.example.broadcasttest/databases # sqlite3 BookStore.db
SQLite version 3.9.2 2015-11-02 18:31:45
Enter ".help" for usage hints.
sqlite> .table
Book              android_metadata
sqlite> .schema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE Book ( id integer primary key autoincrement, author text, price real, pages integer, name text);
sqlite>


更新数据库 创建新的表
 public static final String CREATE_CATEGORY ="create table Category ( " +
            "id integer primary key autoincrement," +
            "category_name text," +
            " category_code integer)";
    public MyDatabase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }


    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {


        sqLiteDatabase.execSQL(CREATE_BOOK);
        sqLiteDatabase.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext,"创建成功!",Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {


        sqLiteDatabase.execSQL("drop table if exists Book");
        sqLiteDatabase.execSQL("drop table if exists Category");
        onCreate(sqLiteDatabase);
    }
}




final MyDatabase database = new MyDatabase(MainActivity.this,"BookStore.db",null,2);


插入数据
insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = database.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("name","红楼梦");
                values.put("price",22.5);
                values.put("pages",40);
                values.put("author","曹雪芹");
                db.insert("Book",null,values);
                values.clear();
                values.put("name","西游记");
                values.put("price",21.5);
                values.put("pages",43);
                values.put("author","吴承恩");
                db.insert("Book",null,values);




            }
        });
更新数据
 update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = database.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("author","张三");
                db.update("Book",values,"name = ?",new String[]{"西游记"});


            }
        });
查询数据
query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = database.getReadableDatabase();
                Cursor cursor = db.query("Book",null,null,null,null,null,null);
                while (cursor.moveToNext()){
                    String name = cursor.getString(cursor.getColumnIndex("name"));
                    String author = cursor.getString(cursor.getColumnIndex("author"));
                    int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                    double price = cursor.getDouble(cursor.getColumnIndex("price"));
                    Log.d("Main",name);
                    Log.d("Main",author);
                    Log.d("Main",pages+"");
                    Log.d("Main",price+"");


                }
                cursor.close();
            }
        });
删除数据
delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SQLiteDatabase db = database.getWritableDatabase();
                db.delete("Book","name = ?",new String[]{"西游记"});
            }
        });


使用LitePal
compile 'org.litepal.android:core:1.6.0'
main目录下创建assets文件夹
创建litepal.xml文件
<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="BookStore"></dbname>
    <version value="1"></version>
    <list>
       <mapping class = "com.example.litepaltest.Book"></mapping>
    </list>


</litepal>




public class MyApplication extends Application {
   private Context context;
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        LitePal.initialize(context);
        
    }
    
}


继承DataSupport
public class Book extends DataSupport {
    private String name;
    private String author;
    private int pages;
    private double price;


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public String getAuthor() {
        return author;
    }


    public void setAuthor(String author) {
        this.author = author;
    }


    public int getPages() {
        return pages;
    }


    public void setPages(int pages) {
        this.pages = pages;
    }


    public double getPrice() {
        return price;
    }


    public void setPrice(double price) {
        this.price = price;
    }
}


创建数据库
create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LitePal.getDatabase();
            }
        });
插入数据
insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Book book = new Book();
                book.setName("西游记");
                book.setAuthor("吴承恩");
                book.setPages(10);
                book.setPrice(20.1);
                book.save();


            }
        });
查询数据
query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<Book> books= DataSupport.findAll(Book.class);
                for(Book book :books){


                    Log.d("Main", book.getName());
                    Log.d("Main", book.getAuthor());
                    Log.d("Main",book.getPages()+"");
                    Log.d("Main",book.getPrice()+"");




                }
            }
        });
更新数据
update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Book book = new Book();
                book.setAuthor("张三");
                book.updateAll("name = ?","西游记");
                book.setToDefault("pages");
                book.updateAll();


            }
        });
删除数据
delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataSupport.deleteAll(Book.class,"name = ?","西游记");


            }
        });
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 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 炫酷倒计时应用的完整代码,其中包括了连接数据库和使用广播接收器的相关代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值