_Android 课设之个人音乐播放器

2023-11-23 21:51:34 浏览数 (1)

第一章 绪论

1.1选题背景

由于时代快速发展,各种各样的音乐播放器层出不穷,此时需要一个可以根据个人爱好来播放的音乐播放器就尤为重要,因此我特意制作了一个根据自己喜好的音乐播放器,只需要把音乐文件放进制定的目录下即可。

1.2开发技术

该App利用了SQlite数据库对于用户的管理,还有MediaPlayer媒体播放器的使用,和各种布局加以一些控件得以使界面看着舒服,还有利用了广播信息对于用户的操作进行提示。并且对于音乐文件得存储也使用了sdcard文件存储的技术,还有组件间的通信和广播信息等技术。主要使用Android,java开发。

第二章 需求及可行性分析

2.1需求分析

Android应用软件包含人机界面(控件、菜单、工具栏、对话框等)、组件通信、后台服务、数据存储、媒体播放、手机特色等功能。

2.2 可行性分析

  1. 首先要对用户进行注册和登录修改删除等功能:可以使用sqlite数据库
  2. 要扫描文件夹的mp3文件:使用Java文件流的读写操作和Android的存取权限控制
  3. 要实现音乐的播放:使用MediaPlayer类来对音乐进行操作
  4. 布局使用安卓自带的LinearLayout标签
  5. 菜单使用安卓自带的Menu类
  6. 按钮使用安卓自带的Button类
  7. 还有对权限进行控制:使用Mainfest.permission等属性赋予权限
  8. 对于组件间的通信使用Intent类
  9. 对于部分广播信息使用Toast类
  10. 确定使用的技术,进行实际开发。

第三章 系统分析

MainActivity类

Protect void onCreate(Budle): 构建主界面

对于主页面一些组件的管理和对于一些事件的监听

Record类

对于一些常用的变量要做静态存储处理,比如说用户名,密码,数据库链接,还有登录时间,当前播放的音乐文件等

MusicActivity类

该类主要用于音乐播放的初始化处理和对音乐进行播放,暂停,重置播放等功能,以下是该类应该具备的功能。

Protect void onCreate(Bundle): 构建播放音乐界面

Public boolean onCreateOptionsMenu(Menu): 添加菜单(返回,注销,更新信息)这个功能应当用于登录之后的每一个页面

Public void onOptionsItemSelected(MenuItem):对于子菜单进行监听处理,这个功能也应当用于登录之后的每一个页面

Public void onRequestPermissionsResult(int String[] int[]): 对于音乐播放的权限处理

Protect void onDestroy(): 用于关闭释放MediaPlayer播放器

Private void initMediaPlayer(): 对于MusicPlayer进行初始化和准备工作。

Time类

该类主要用于获取当前时间(原本还写了一个日志类,但是由于时间紧凑,该类的功能没能得到补充)

Public static String getCurrentTime() 用于获取当前时间

DBAdapter类

该类主要对于数据库的一些增删查改操作进行封装,此处方法过多就不进行一一解释了。只介绍一些重要的方法和内部类。

Private static Class DBOpenHelper extends SQLiteOpenHelper静态Helper类,用于建立更新和打开数据库

Public long insert(User): 用于插入用户,实现注册功能

Public User queryOneData(String String): 用于查找指定某一个用户,实现用户登录功能。

Public long deleteOneData(String): 用于删除某个指定用户,实现用户注销功能。

Public long updateOneData(String User):根据指定条件更新某个用户的信息,实现更新用户信息功能。

User 类

对于数据库的用户表而建的用户类。

UserMsgActivity类

该类用于展示用户登录之后的页面,比如说展示一些提示信息,登陆时间和用户喜爱的音乐,还有菜单的对用户的信息进行管理。有以下主要方法

Protect void onCreate(Bundle): 创建用户登录之后的页面

Public void find(File, String): 查找某一个指定文件,也就是实现播放某一个指定音乐功能。

Public ArrayList<File> getAllMusic(): 获取目录下的所有音乐文件。

Public boolean onCreateOptionsMenu(Menu): 添加菜单(返回,注销,更新信息)这个功能应当用于登录之后的每一个页面

Public void onOptionsItemSelected(MenuItem):对于子菜单进行监听处理,这个功能也应当用于登录之后的每一个页面

UpdateUser 类

该类用于展示用户更新信息的页面,实现用户更新密码,更换用户名等功能。

Protect void onCreate(Bundle) : 用于创建用户更新信息的页面。

Public boolean onCreateOptionsMenu(Menu): 添加菜单(返回,注销,更新信息)这个功能应当用于登录之后的每一个页面

Public void onOptionsItemSelected(MenuItem):对于子菜单进行监听处理,这个功能也应当用于登录之后的每一个页面

还有一些事件监听方法过多就不进行一一列举了。

第四章 系统设计及实现

4.1系统设计:

首先应当分为四个包分别装有对应功能的类,如下图:

activity包下存放的是更新用户信息类(UpdateUser)和展示用户信息类(UserMsgActivity)

DB包下存放的是数据库操作类(DBAdapter)和实体用户类(User)

log包下存放的是日志类(Logger)和时间类(Time)// 注:日志类暂无实现该功能

lyl包下存放的是主类(MainActivity)和记录类(Record)

musicplayer包下存放的是音乐操作类(MusicActivity)

4.2实现

com.example.activity.UpdateUser
代码语言:javascript复制
package com.example.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.DB.User;
import com.example.lyl.R;
import com.example.lyl.Record;

public class UpdateUser extends Activity {

    private EditText agoPassword;
    private EditText newPassword;
    private EditText againPassword;
    private EditText agoUsername;
    private EditText newUsername;
    private Button updatePassword;
    private Button updateUsername;
    private Button resetUsername;
    private Button resetPassword;

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

        agoPassword = findViewById(R.id.editAgoPassword);
        newPassword = findViewById(R.id.editNewPassword);
        againPassword = findViewById(R.id.editAgainPassword);
        updatePassword = findViewById(R.id.updatePassword);
        agoUsername = findViewById(R.id.editAgoUsername);
        newUsername = findViewById(R.id.editNewUsername);
        resetPassword = findViewById(R.id.resetPassword);
        updateUsername = findViewById(R.id.updateBtnUsername);
        resetUsername = findViewById(R.id.resetUsername);

        agoUsername.setText(Record.username);

        updatePassword.setOnClickListener(onUpdatePwClickListener);
        updateUsername.setOnClickListener(onUpdateUnClickListener);
        resetPassword.setOnClickListener(onResetPwClickListener);
        resetUsername.setOnClickListener(onResetUnClickListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getTitle().equals("返回")){
            setResult(RESULT_CANCELED,null);
            finish();
        }
        else if(item.getTitle().equals("注销")){
            Record.dbAdapter.deleteOneData(Record.username);
            Toast.makeText(UpdateUser.this,"注销成功",Toast.LENGTH_LONG).show();
            setResult(RESULT_CANCELED,null);
            finish();
            Intent intent = new Intent(UpdateUser.this,com.example.lyl.MainActivity.class);
            startActivity(intent);
        }
        else if(item.getTitle().equals("更新信息")){
            Intent intent = new Intent(UpdateUser.this,UpdateUser.class);
            startActivity(intent);
        }
        return true;
    }

    View.OnClickListener onUpdatePwClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String agoPw = agoPassword.getText().toString();
            String newPw = newPassword.getText().toString();
            String againPw = againPassword.getText().toString();

            User user = new User();

            if(agoPw.equals(Record.password)){
                if(newPw.equals(againPw)){
                    user.setUsername(Record.username);
                    user.setPassword(newPw);
                    Record.dbAdapter.updateOneData(user.getUsername(),user);
                    Record.password = againPw;
                    Toast.makeText(UpdateUser.this,"更新密码成功",Toast.LENGTH_LONG).show();
                }
                else{
                    Toast.makeText(UpdateUser.this,"两次密码不一样",Toast.LENGTH_LONG).show();
                }
            }
            else {
                Toast.makeText(UpdateUser.this,"旧密码不正确",Toast.LENGTH_LONG).show();
            }
        }
    };

    View.OnClickListener onUpdateUnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String ago_Username = agoUsername.getText().toString();
            String new_Username = newUsername.getText().toString();
            User user = new User();
            if(Record.username.equals(ago_Username)){
                if(!new_Username.equals("")){
                    user.setUsername(new_Username);
                    user.setPassword(Record.password);
                    Record.dbAdapter.updateOneData(ago_Username,user);
                    Record.username = new_Username;
                    Toast.makeText(UpdateUser.this,"用户名更改成功",Toast.LENGTH_LONG).show();
                }
                else{
                    Toast.makeText(UpdateUser.this,"用户名不能为空",Toast.LENGTH_LONG).show();
                }
            }
            else{
                Toast.makeText(UpdateUser.this,"旧用户名不正确",Toast.LENGTH_LONG).show();
            }
        }
    };

    View.OnClickListener onResetPwClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            agoPassword.setText("");
            againPassword.setText("");
            newPassword.setText("");
        }
    };

    View.OnClickListener onResetUnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            agoUsername.setText("");
            newUsername.setText("");
        }
    };
}
com.example.activity.UserMsgActivity
代码语言:javascript复制
package com.example.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.DB.DBAdapter;
import com.example.log.Time;
import com.example.lyl.R;
import com.example.lyl.Record;
import com.example.musicplayer.MusicActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class UserMsgActivity extends Activity {

    private static Manifest.permission permission;
    public ArrayList<File> listMusic = new ArrayList<>();

    private DBAdapter dbAdapter;
    private TextView times;
    private TextView userText;
    private ListView listView;

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

        times = findViewById(R.id.times);
        userText = findViewById(R.id.userText);
        Record.Times = Time.getCurrentTime();
        times.setText("登录时间为:" Record.Times);
        userText.setText("欢迎你: " Record.username "用户");

        dbAdapter = new DBAdapter(this);
        dbAdapter.open();

        getAllMusic();
//        for(int i=0;i<listMusic.size();i  ){
//            System.out.print("第" (i 1) "首:");
//            System.out.println(listMusic.get(i).getName());
//        }
        List<String> list = new ArrayList<>();
        listView = findViewById(R.id.ListViewMusic);
        for(int i=0;i<listMusic.size();i  ){
            String musicName = listMusic.get(i).getName();
            System.out.print("第" (i 1) "首:");
            System.out.println(musicName);
            int rex = musicName.indexOf("伦");
            String newMusicName = musicName.substring(0,rex 1)   ".mp3";
            System.out.println(newMusicName);
            list.add(newMusicName);
        }
        Record.list = list;
        Record.lastViewFlag = true;
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
        listView.setAdapter(adapter);
        Record.listView = listView;

        listView.setOnItemClickListener(listViewListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getTitle().equals("返回")){
            listView.clearDisappearingChildren();
            setResult(RESULT_CANCELED,null);
            finish();
        }
        else if(item.getTitle().equals("注销")){
            dbAdapter.deleteOneData(Record.username);
            Toast.makeText(UserMsgActivity.this,"注销成功",Toast.LENGTH_LONG).show();
            setResult(RESULT_CANCELED,null);
            finish();
            Intent intent = new Intent(UserMsgActivity.this,com.example.lyl.MainActivity.class);
            startActivity(intent);
        }
        else if(item.getTitle().equals("更新信息")){
            Intent intent = new Intent(UserMsgActivity.this,UpdateUser.class);
            startActivity(intent);
        }
        return true;
    }

    public ArrayList<File> getAllMusic(){

        File dir = new File("/sdcard/music/");
        boolean exitFlag = dir.exists();
        boolean canWrite = dir.canWrite();
        System.out.println("存在吗:" exitFlag "n可读吗:" canWrite);
        if (ContextCompat.checkSelfPermission(UserMsgActivity.this, UserMsgActivity.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(UserMsgActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Context.MODE_ENABLE_WRITE_AHEAD_LOGGING);
        }
        String str = ".mp3";
        String exegc = "^. "   str   "$";  //匹配以str为后缀名的文件;
        File file = dir;
        if (!file.exists()) {
            System.out.println("您要查找的路径不存在,请重新输入:");
            getAllMusic();
        } else if (!file.isDirectory()) {
            System.out.println("您输入的不是文件夹,请重新输入:");
            getAllMusic();
        } else {
            find(file, exegc);   //调用方法;
//                if (count == 0) {
//                    System.out.println("没有您要找的"   str   "为后缀名的文件");
//                } else {
//                    System.out.println(path   "文件夹下共有以"   count   "个以"   str   "为后缀名的文件");
        }
        return listMusic;
    }

    private void find(File file1, String exegc) {

        File[] lists = file1.listFiles();  //将当前文件夹下的文件和文件夹放入数组中
        for (int i = 0; i < lists.length; i  ) {
            if (lists[i].isDirectory()) {
                find(lists[i], exegc);
            } else {
                if (lists[i].getName().matches(exegc)) {
                    System.out.println(lists[i].getAbsolutePath());
                    listMusic.add(lists[i]);
//                        count  ;
                }
            }
        }
    }

    AdapterView.OnItemClickListener listViewListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            File file = listMusic.get((int) id);
            Record.file = file;
            String musicName = file.getName();
            int rex = musicName.indexOf("伦");
            String newMusicName = musicName.substring(0,rex 1)   "    正在播放";
            Record.musicText = newMusicName;
            Intent intent = new Intent(UserMsgActivity.this, MusicActivity.class);
            startActivity(intent);
        }
    };
}
com.example.DB.DBAdapter
代码语言:javascript复制
package com.example.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DBAdapter {

    private static final String DB_NAME = "people.db";
    private static final String DB_TABLE = "personinfo";
    private static final int DB_VERSION = 1;

    public static final String KEY_ID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_PASSWORD = "password";

    private SQLiteDatabase db;
    private final Context context;
    private DBOpenHelper dbOpenHelper;

    public DBAdapter(Context _context) {
        context = _context;
    }

    /** Close the database */
    public void close() {
        if (db != null){
            db.close();
            db = null;
        }
    }

    /** Open the database */
    public void open() throws SQLiteException {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase();
        }
        catch (SQLiteException ex) {
            db = dbOpenHelper.getReadableDatabase();
        }
    }


    public long insert(User people) {
        ContentValues newValues = new ContentValues();

        newValues.put(KEY_NAME, people.getUsername());
        newValues.put(KEY_PASSWORD, people.getPassword());

        System.out.println(people);
        return db.insert(DB_TABLE, null, newValues);
    }


    public User[] queryAllData() {
        Cursor results =  db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_PASSWORD },
                null, null, null, null, null);
        return ConvertToPeople(results);
    }

    public User[] queryOneData(String name,String password) {
        Cursor results =  db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_PASSWORD },
                KEY_NAME   "= ? AND "   KEY_PASSWORD   "= ? " , new String[]{name,password},null,null,null );
        return ConvertToPeople(results);
    }

    private User[] ConvertToPeople(Cursor cursor){
        int resultCounts = cursor.getCount();
        if (resultCounts == 0 || !cursor.moveToFirst()){
            return null;
        }
        User[] peoples = new User[resultCounts];
        for (int i = 0 ; i<resultCounts; i  ){
            peoples[i] = new User();
            peoples[i].ID = cursor.getInt(0);
            peoples[i].Username= cursor.getString(cursor.getColumnIndex(KEY_NAME));
            peoples[i].password = cursor.getString(cursor.getColumnIndex(KEY_PASSWORD));

            cursor.moveToNext();
        }
        return peoples;
    }

    public long deleteAllData() {
        return db.delete(DB_TABLE, null, null);
    }

    public long deleteOneData(String name) {
        System.out.println(name);
        return db.delete(DB_TABLE,  KEY_NAME   "='"   name   "'", null);
    }

    public long updateOneData(String name , User people){
        ContentValues updateValues = new ContentValues();
        updateValues.put(KEY_NAME, people.Username);
        updateValues.put(KEY_PASSWORD, people.password);

        return db.update(DB_TABLE, updateValues,  KEY_NAME   "='"   name   "'", null);
    }

    /** 静态Helper类,用于建立、更新和打开数据库*/
    private static class DBOpenHelper extends SQLiteOpenHelper {

        public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        private static final String DB_CREATE = "create table "  
                DB_TABLE   " ("   KEY_ID   " integer primary key autoincrement, "  
                KEY_NAME  " text not null, "   KEY_PASSWORD  " text );";

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
            _db.execSQL("DROP TABLE IF EXISTS "   DB_TABLE);
            onCreate(_db);
        }
    }
}
com.example.DB.User
代码语言:javascript复制
package com.example.DB;

public class User {
    public int ID = -1;
    public String Username;
    public String password;

    public String getUsername() {
        return Username;
    }

    public void setUsername(String username) {
        Username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString(){
        String result = "";
        result  = "ID:"   this.ID   ",";
        result  = "用户名:"   this.Username   ",";
        result  = "密码:"   this.password;
        return result;
    }
}
com.example.log.Logger
代码语言:javascript复制
package com.example.log;

import android.os.BugreportManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Logger {
    private static File file = null;
    private static String path = "C:\Users\Dell is very good\Documents\AndroidStudio\Log\log.txt";
    private static FileOutputStream fos = null;
    private static BufferedOutputStream bfos = null;

    public static void initFile(){
        file = new File(path);
        try{
            fos = new FileOutputStream(file,true);
            bfos = new BufferedOutputStream(fos);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void writeLog(String text){
        Logger.initFile();
        if(file!=null){
            try{
                text  = "n";
                String time = com.example.log.Time.getCurrentTime() 'n';
                byte[] buff = text.getBytes();
                byte[] buffTime = time.getBytes();
                bfos.write(buffTime);
                bfos.write(buff);
                bfos.flush();
                fos.flush();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(bfos!=null){
                    try {
                        bfos.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if(fos!=null){
                    try{
                        fos.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                else{
                    System.out.println("fos是null");
                }
            }
        }
        else{
            System.out.println("file是null");
        }
    }
}
com.example.log.Time
代码语言:javascript复制
package com.example.log;


import java.text.SimpleDateFormat;
import java.util.Date;

public class Time {
    public static String getCurrentTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date();
        String timeString = sdf.format(d);
        System.out.println("当前时间为: " timeString);
        return timeString;
    }
}
com.example.lyl.MainActivity
代码语言:javascript复制
package com.example.lyl;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.DB.DBAdapter;
import com.example.DB.User;
import com.example.activity.UserMsgActivity;


public class MainActivity extends Activity {

    private DBAdapter dbAdepter ;

    private EditText editUsername;
    private EditText editPassword;
    private TextView labelView;
    private Button btnRegister;
    private Button btnLogin;

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

        editUsername = findViewById(R.id.editUsername);
        editPassword = findViewById(R.id.editPassword);
        labelView = findViewById(R.id.show);
        btnLogin = findViewById(R.id.login);
        btnRegister = findViewById(R.id.register);

        btnRegister.setOnClickListener(btnRegisterListener);
        btnLogin.setOnClickListener(btnLoginButtonListener);

        dbAdepter = new DBAdapter(this);
        dbAdepter.open();
        Record.dbAdapter = dbAdepter;
    }

    View.OnClickListener btnRegisterListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ContentValues values = new ContentValues();
            User user = new User();
            String name = editUsername.getText().toString();
            String password = editPassword.getText().toString();
            if (!name.equals("") && !password.equals("")) {
                user.Username = name;
                user.password = password;
                try {
                    long colunm = dbAdepter.insert(user);
                    if (colunm == -1) {
                        labelView.setText("添加过程错误!");
                    } else {
                        Toast.makeText(MainActivity.this,"注册成功",Toast.LENGTH_LONG).show();
                        labelView.setText("成功添加数据,ID:"   String.valueOf(colunm));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    labelView.setText("添加过程错误!");
                }
            } else {
                labelView.setText("你的输入有误!");
            }
        }
    };

    View.OnClickListener btnLoginButtonListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String name = null;
            String password;
            User[] peoples =null;
            if(!editUsername.getText().toString().equals("")) {
                try {
                    name = editUsername.getText().toString();
                    password = editPassword.getText().toString();
                    peoples = dbAdepter.queryOneData(name,password);
                    Record.username = name;
                    Record.password = password;
                    labelView.setText("没问题");
                    if(peoples!=null) {
                        Intent intent = new Intent(MainActivity.this, com.example.activity.UserMsgActivity.class);
                        startActivity(intent);
                        Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    labelView.setText("数据库中没有Name为" name "的数据或者密码错误");
                }
            }
            else{
                labelView.setText("请输入用户名");
            }
            if (peoples == null && name!=null){
                labelView.setText("数据库中没有Name为" name "的数据或者密码错误");
                return;
            }
        }
    };
}
com.example.lyl.Record
package com.example.lyl;


import android.widget.ListView;

import com.example.DB.DBAdapter;

import java.io.File;
import java.util.List;

public class Record {
    public static DBAdapter dbAdapter;
    public static String username;
    public static String Times;
    public static String password;
    public static ListView listView;
    public static File file;
    public static List list = null;
    public static boolean lastViewFlag = false;
    public static String musicText;
}
com.example.musicplayer.MusicActivity
代码语言:javascript复制
package com.example.musicplayer;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.activity.UpdateUser;
import com.example.lyl.R;
import com.example.lyl.Record;
import java.io.IOException;

public class MusicActivity extends Activity {
    private Button play;
    private Button pause;
    private Button replay;
    private TextView musicText;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play = findViewById(R.id.play);
        pause = findViewById(R.id.pause);
        replay = findViewById(R.id.replay);
        musicText = findViewById(R.id.music);
        musicText.setText(Record.musicText);
        if (ContextCompat.checkSelfPermission(MusicActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MusicActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else {
            try { //权限申请
                initMediaPlayer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mediaPlayer.isPlaying()){
                    mediaPlayer.start();
                }
            }
        });
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                }
            }
        });
        replay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.reset();
                    try {
                        initMediaPlayer();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getTitle().equals("返回")){
            Record.listView.clearDisappearingChildren();
            setResult(RESULT_CANCELED,null);
            finish();
        }
        else if(item.getTitle().equals("注销")){
            Record.dbAdapter.deleteOneData(Record.username);
            Toast.makeText(MusicActivity.this,"注销成功",Toast.LENGTH_LONG).show();
            setResult(RESULT_CANCELED,null);
            finish();
            Intent intent = new Intent(MusicActivity.this, com.example.lyl.MainActivity.class);
            startActivity(intent);
        }
        else if(item.getTitle().equals("更新信息")){
            Intent intent = new Intent(MusicActivity.this, UpdateUser.class);
            startActivity(intent);
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    try {
                        initMediaPlayer();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    Toast.makeText(MusicActivity.this,"权限被拒绝",Toast.LENGTH_LONG).show();
                }
                break;
            default:
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

    private void initMediaPlayer() throws IOException {
        mediaPlayer.setDataSource(Record.file.getPath());
        mediaPlayer.prepare();
    }
}

第五章 总结与展望

5.1总结

通过这次课程设计,把之前的一些布局和控件的属性以及如何调好他们之间的排版有了更深的理解,还有组件间的通信,和广播信息,还整合了SQLite数据库,MediaPalyer媒体音乐播放器都更加熟练使用这些类的一些常用方法和常用属性。

5.2展望

大家如果仔细看的话会发现我有两个类是多余的(Logger和Time),其实这两个类我是打算用来做输出日志文件的时候用的,但是由于回家了时间比较冲突就没来得及做剩余部分了。所以有一个日志类需要扩展出来,把这个播放器的使用进行监听并写入到日志文件中方便以后进行查看更新和纠错和记录用户的操作。以便以后与用户沟通的时候有依据可说。

我正在参与2023腾讯技术创作特训营第三期有奖征文,组队打卡瓜分大奖!

0 人点赞