[移动端]Android开发笔记(下)

716 阅读4分钟

Android笔记(2021.9.12-2021.11.26)

五.数据存储

1.数据存储是什么?

image.png

sp:配置文件

SQLite,room:数据库

2.SP

1.特点

image.png

2.使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

  <Button
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="保存数据"
      android:onClick="saveData"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="读取数据"
        android:onClick="getData"/>

</LinearLayout>

// Java文件
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 参数1  String name:SP名字
     * 参数2 int mode:模式 (追加Context.MODE_APPEND ;常规 Context.MODE_PRIVATE)
     *  public SharedPreferences getSharedPreferences(String name, int mode) {
     *         throw new RuntimeException("Stub!");
     *     }
     * @param view
     */

    //保存数据SP
    public void saveData(View view) {
        SharedPreferences sp = getSharedPreferences("SPName", Context.MODE_PRIVATE);

        //apply,后数据才会写到xml文件中去
        sp.edit().putString("phone","RedaMi K40 por +").apply();
    }

    //读取SP数据
    public void getData(View view) {
        SharedPreferences sp = getSharedPreferences("SPName", Context.MODE_PRIVATE);
        String phone = sp.getString("phone", "没找到,这是默认值");
        Toast.makeText(MainActivity.this,"电话号码是:" + phone.toString(),Toast.LENGTH_SHORT).show();
    }
}

3.SQLite

1.介绍

image.png

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/createDB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="建库"
        android:gravity="center"/>

    <Button
        android:id="@+id/query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"
        android:gravity="center"/>

    <Button
        android:id="@+id/insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="插入"
        android:gravity="center"/>


    <Button
        android:id="@+id/alter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改"
        android:gravity="center"/>

    <Button
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除"
        android:gravity="center"/>

    <Button
        android:id="@+id/exit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="退出"
        android:gravity="center"/>

</LinearLayout>

//Java文件
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "SQLite";
    private DBHelper helper = DBHelper.getInstance(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        Button create = findViewById(R.id.createDB);
        Button insert = findViewById(R.id.insert);
        Button delete = findViewById(R.id.delete);
        Button query = findViewById(R.id.query);
        Button alter = findViewById(R.id.alter);
        Button exit = findViewById(R.id.exit);

        create.setOnClickListener(this);
        insert.setOnClickListener(this);
        delete.setOnClickListener(this);
        query.setOnClickListener(this);
        alter.setOnClickListener(this);
        exit.setOnClickListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.createDB:
                helper.getReadableDatabase();
                break;

            case R.id.query:
                SQLiteDatabase db1 = helper.getReadableDatabase();
                if (db1.isOpen()) {
                    Cursor cursor = db1.rawQuery("select * from persons", null);
                    while (cursor.moveToNext()) {
                        //偷懒做法
//                        id = cursor.getInt(0)
//                        name = cursor.getString(1);

                        //正确做法
                        @SuppressLint("Range")
                        int id = cursor.getInt(cursor.getColumnIndex("_id"));
                        @SuppressLint("Range")
                        String name = cursor.getString(cursor.getColumnIndex("name"));

                        Log.d(TAG, "query  _id:" + id + "  name:" + name);

                    }

                    //关闭资源
                    cursor.close();
                }
                db1.close();
                break;

            case R.id.insert:
                SQLiteDatabase db2 = helper.getWritableDatabase();
                if (db2.isOpen()) {
                    String sql = "insert into persons(name) values('划水')";
                    db2.execSQL(sql);
                }
                db2.close();
                break;

            case R.id.alter:
                SQLiteDatabase db3 = helper.getWritableDatabase();
                if (db3.isOpen()) {
                    String sql = "update persons set name = ? where _id=?";
                    db3.execSQL(sql,new Object[]{"摸鱼",4});
                }
                db3.close();
                break;

            case R.id.delete:
                SQLiteDatabase db4 = helper.getWritableDatabase();
                if (db4.isOpen()) {
                    String sql = "delete from persons where _id=?";
                    db4.execSQL(sql,new Object[]{5});
                }
                db4.close();
                break;

            case R.id.exit:
                finish();
                break;
            default:
                break;
        }

    }
}
-----------------------------------------------------
 DBHelper.java
/**
 * @author : HengZhang
 * @date : 2021/10/19 20:01
 * <p>
 * 相当于工具类
 */

public class DBHelper extends SQLiteOpenHelper {

    private static DBHelper dbHelper;

    //单例模式
    public static synchronized DBHelper getInstance(Context context) {
        if (dbHelper == null) {
            dbHelper = new DBHelper(context, "sqlite.db", null, 1);
        }
        return dbHelper;
    }

    private DBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    //创建数据库的时候执行,每次建库,只执行一次
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //创建数据库
        String sql = "create table persons(_id integer primary key autoincrement,name text)";
        sqLiteDatabase.execSQL(sql);

    }

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

    }
}

4.Room(对SQLite的封装)

1.三角色

image.png

2.创建

//一张表,entity
@Entity
public class Student {

    //主键唯一,自动增长
    @PrimaryKey(autoGenerate = true)
    private Integer id;

    private String name;

    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
---------------------------------------------------
@Dao   // Dao == database access object
public interface StudentDao {

    //增
    @Insert
    void insertStudents(Student... students);

    //改
    @Update
    void updateStudents(Student... students);

    //查
    @Query("select * from Student order by id")
    List<Student> queryAllStudents();

    //删,
    @Delete
    void deleteStudent(Student... students);

    //所有需要写query+sql语句
    @Query("delete from Student")
    void deleteAllStudents();
}
------------------------------------------------

@Database(entities = {Student.class}, version = 1, exportSchema = false)
public abstract class StudentDB extends RoomDatabase {

    //单例模式
    private static StudentDB DB;

    //用户需要操作dao,所以暴露dao出去
    public abstract StudentDao getStudentDao();

    public static synchronized StudentDB getInstance(Context context) {
        if (DB == null) {

            //默认是异步线程
            DB = Room.databaseBuilder(context.getApplicationContext(),
                    StudentDB.class, "studentDB").build();
        }
        return DB;
    }
}

六.多媒体使用

1.录制音视频

image.png

image.png

public class MediaRecord extends AppCompatActivity implements View.OnClickListener {

    private Button record_btn;
    private TextureView textureView;
    private MediaRecorder mediaRecorder;
    private Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_record);

        textureView = findViewById(R.id.textureView);
        record_btn = findViewById(R.id.record_btn);

        record_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        CharSequence text = record_btn.getText();
        if (TextUtils.equals(text, "开始")) {
            record_btn.setText("结束");

            //设置录制时的镜头角度
            camera = Camera.open();
            camera.setDisplayOrientation(90);
            camera.unlock();

            mediaRecorder = new MediaRecorder();
            mediaRecorder.setCamera(camera);

            //设置音频源,麦克风
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            //设置视频源,相机
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            //设置音频格式mp4
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            //设置音频编码
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            //设置视频编码
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

            //设置文件保存位置
            mediaRecorder.setOutputFile(new File(getExternalFilesDir(""),
                    "a.mp4").getAbsolutePath());
            //设置文件尺寸
            mediaRecorder.setVideoSize(1920, 1080);
            //设置帧率,1s几张
            mediaRecorder.setVideoFrameRate(30);

            //比特率,8*1920*1080 巨清晰
            mediaRecorder.setVideoEncodingBitRate(8*1920*1080);
            //设置预览
            mediaRecorder.setPreviewDisplay(new Surface(textureView.getSurfaceTexture()));
            //视频结束后,播放的镜头角度
            mediaRecorder.setOrientationHint(90);

            try {
                //进入准备阶段
                mediaRecorder.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //开始运行
            mediaRecorder.start();

        } else {
            record_btn.setText("开始");

            //结束
            mediaRecorder.stop();
            mediaRecorder.release();

            camera.release();
        }
    }
}

2.视频播放

image.png

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".VideoViewActivity">

    <FrameLayout
        android:id="@+id/layout_top"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        tools:ignore="MissingConstraints">

        <VideoView
            android:id="@+id/videoView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:visibility="visible" />
    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

///Java文件
public class VideoViewActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);

        VideoView videoView = findViewById(R.id.videoView);

        //设置控制器
        MediaController mediaController = new MediaController(this);
        videoView.setMediaController(mediaController);

        //这是上一曲下一曲监听
        mediaController.setPrevNextListeners(this,this);

        //设置文件地址
        videoView.setVideoPath(new File(getExternalFilesDir(""),
                "video1.mp4").getAbsolutePath());
        videoView.start();
    }

    @Override
    public void onClick(View view) {
        Log.d("TAG", "onClick: ");
    }
}

3.音频播放

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SoundActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="音频播放" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

//Java文件
    public class SoundActivity extends AppCompatActivity implements MySoundAdapter.OnItemClickListener {

    private SoundPool soundPool;
    List<Sound> data;

    static class Sound {
        String name;
        int soundId;

        public String getName() {
            return name;
        }

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

        public int getSoundId() {
            return soundId;
        }

        public void setSoundId(int soundId) {
            this.soundId = soundId;
        }

        public Sound(String name, int soundId) {
            this.name = name;
            this.soundId = soundId;

        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sound);

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        //本节重点,第一步:创建SoundPool对象
        soundPool = new SoundPool.Builder().setMaxStreams(5).build();


        data = new ArrayList<>();

        //第二步:load方法,加载文件
        data.add(new Sound("music1", soundPool.load(this, R.raw.music1, 1)));
        data.add(new Sound("music2", soundPool.load(this, R.raw.music2, 1)));
        data.add(new Sound("music3", soundPool.load(this, R.raw.music3, 1)));
        data.add(new Sound("music4", soundPool.load(this, R.raw.music4, 1)));
        data.add(new Sound("music5", soundPool.load(this, R.raw.music5, 1)));
        MySoundAdapter adapter = new MySoundAdapter(data, recyclerView, this);
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);

    }

    @Override
    public void onItemClick(int position) {

        //第三步:播放
        Sound sound = data.get(position);
        soundPool.play(sound.getSoundId(),0.8f,0.8f,1,0,1.0f);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //第四步:资源释放
        for (Sound datum : data) {
            soundPool.unload(datum.getSoundId());
        }
        soundPool.release();
    }
}
-------------------------------------------------------

public class MySoundAdapter extends RecyclerView.Adapter<MySoundAdapter.MyViewHolder> implements View.OnClickListener {

    private final List<SoundActivity.Sound> data;
    private final Context context;
    private final RecyclerView recyclerView;
    private OnItemClickListener listener;

    public MySoundAdapter(List<SoundActivity.Sound> data, RecyclerView recyclerView, Context context) {
        this.data = data;
        this.recyclerView = recyclerView;
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        TextView textView = new TextView(context);
        LinearLayout.LayoutParams layoutParams =
                new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200);
        layoutParams.topMargin = 18;
        layoutParams.leftMargin = 30;

        textView.setLayoutParams(layoutParams);
        textView.setOnClickListener(this);

        return new MyViewHolder(textView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        ((TextView) holder.itemView).setText(data.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public void onClick(View view) {
        if (listener != null) {
            listener.onItemClick(recyclerView.getChildAdapterPosition(view));
        }

    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    //自定义一个点击事件
    interface OnItemClickListener {
        void onItemClick(int position);
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}