(资源下载链接在文末)
实现功能:播放,暂停,下一曲,上一曲,注册,登录,更改背景图片。
首先在AndroidManifest.xml 声明server 和对SD卡中的文件进行操作的权限
<service
android:name=".service.MusicService"
android:enabled="true"
android:exported="true" />
<!-- 对SD卡中的文件进行操作的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
实现首页的所有功能(1、显示本地所有MP3 2、显示登录状态 3、自由更改背景图)
index_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:id="@+id/drawer_layout">
<FrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/design_default_color_secondary_variant"
app:titleTextColor="@color/white"
android:theme="@style/Theme.Design.Light.NoActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="55dp"
android:id="@+id/idnex_bg"/>
<LinearLayout
android:id="@+id/linearRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:layout_weight="1"
android:layout_marginBottom="60dp"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/mRecyclerView"
android:layout_width="match_parent"
android:layout_marginBottom="30dp"
android:layout_height="match_parent" />
</LinearLayout>
<include layout="@layout/controller_bottom" android:id="@+id/nowSong"/>
</FrameLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="@layout/nav_header"
android:id="@+id/nav_view"
app:menu="@menu/nav_menu"
android:background="@color/design_default_color_secondary_variant"
android:layout_gravity="start"/>
</androidx.drawerlayout.widget.DrawerLayout>
IndexActivity.java
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import com.liangyi.yueting.service.MusicService;
import org.litepal.LitePal;
import org.litepal.tablemanager.Connector;
import org.w3c.dom.Text;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class IndexActivity extends AppCompatActivity {
private List<Song> songList=new ArrayList<Song>();
private DrawerLayout drawerLayout;//滑动栏
private static final int LOAD_SONGLIST=1;
private static final int CHOOSE_PHOTO = 2;
private Message message=null;
private TextView info_buttom;
private ImageView album_bottom;
private LinearLayout nowSong;
private TextView songNumber=null;
private MusicReceiver mReceiver;
private NavigationView navigationView;
SQLiteDatabase db ;
LinearLayoutManager layoutManager;
Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case LOAD_SONGLIST:
break;
default:
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
break;
case R.id.search:
break;
case R.id.reload:
//扫描本地歌曲按钮
Toast.makeText(IndexActivity.this,"正在搜索本地音乐",Toast.LENGTH_SHORT).show();
loadSongList();
Toast.makeText(IndexActivity.this,"搜索到"+songList.size()+"首歌曲",Toast.LENGTH_SHORT).show();
case R.id.menu:
break;
case R.id.onlineMusic:
Intent intent=new Intent(IndexActivity.this,OnlineMusicActivity.class);
startActivity(intent);
break;
default:
break;
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.index_activity);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout=findViewById(R.id.drawer_layout);
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
}
mReceiver = new MusicReceiver(new Handler());
IntentFilter itFilter = new IntentFilter();
itFilter.addAction(MusicService.MAIN_UPDATE_UI);
registerReceiver(mReceiver, itFilter);
//初始化侧边栏,并设置点击事件
navigationView=(NavigationView)findViewById(R.id.nav_view);
initNavMenu();
//加载litepal数据库
/*=================litepal数据库=====================*/
LitePal.initialize(this);
db = LitePal.getDatabase();
//检查登录状态
checkUserLogin();
checkPermission();//检查文件读写权限并加载歌曲列表
}
// @Override
// protected void onResumeFragments() {
// super.onResumeFragments();
// loadSongList();
// }
private void checkUserLogin(){
//查询有无登录记录
List<User> findUser= LitePal.where("userStatus=?","1")
.find(User.class);
//有用户显示用户名,没用户显示登录
TextView username=(TextView)navigationView.getHeaderView(0).findViewById(R.id.name);
//如果无用户登陆过
if(findUser.size()==0){
username.setText("请登录");
//进入登陆页面
username.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(IndexActivity.this,LoginActivity.class);
startActivity(intent);
}
});
}
//当前有登录用户
if(findUser.size()>0){
User nowUser=findUser.get(0);
//显示用户名
username.setText(nowUser.getUserName());
//进入个人信息页面
username.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(IndexActivity.this,UserInfoActivity.class);
Bundle bundle=new Bundle();
bundle.putString("number",nowUser.getUserNumber());
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
//滑动菜单Nav_menu点击事件
private void initNavMenu(){
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.changeBg:
Toast.makeText(IndexActivity.this,"更改背景图",Toast.LENGTH_SHORT).show();
Intent intent=new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PHOTO);//打开相册
break;
default:
break;
}
return true;
}
});
}
//返回背景图片
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CHOOSE_PHOTO:
if(resultCode==RESULT_OK){
//判断手机版本号
if(Build.VERSION.SDK_INT>=19){
//api 19为安卓4.4以上用这个方法处理图片
handleImageOnKitKat(data);
}
}
default:
break;
}
}
private class MusicReceiver extends BroadcastReceiver {
private final Handler handler;
// Handler used to execute code on the UI thread
public MusicReceiver(Handler handler) {
this.handler = handler;
}
@Override
public void onReceive(final Context context, final Intent intent) {
// Post the UI updating code to our Handler
handler.post(new Runnable() {
@Override
public void run() {
//加载列表
loadSongList();
}
});
}
}
public void loadSongList(){
songList=ScanMusicUtils.getMusicData(IndexActivity.this);//初始化获取歌曲信息
SongAdapter songAdapter=new SongAdapter(songList);//歌曲适配器
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.mRecyclerView);
layoutManager=new LinearLayoutManager(IndexActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(songAdapter);//加载歌曲列表
//设置音乐点击事件
songAdapter.setOnSongItemClickListen(new SongAdapter.OnSongItemClickListen() {
@Override
public void onClick_Song(int position) {
// Toast.makeText(IndexActivity.this,"position is"+position,Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setClass(IndexActivity.this, PlayDetailActivity.class);
startActivity(intent);
}
});
if(MusicService.mPosition>0){
}
//加载底部控制栏布局
info_buttom=(TextView)findViewById(R.id.CurrentTitle);
album_bottom=(ImageView)findViewById(R.id.album_bottom);//底部专辑图
if(MusicService.mlastPlayer!=null){
// String nowSongInfo=songList.get(MusicService.mPosition).getName() +" - "+songList.get(MusicService.mPosition).getSinger();
String nowSongInfo= (songList.get(MusicService.mPosition).getName().contains(".") ? songList.get(MusicService.mPosition).getName().substring(0, songList.get(MusicService.mPosition).getName().indexOf(".")) : songList.get(MusicService.mPosition).getName())
+" - "+songList.get(MusicService.mPosition).getSinger();
info_buttom.setText(nowSongInfo);//更新歌手歌名
System.out.println("-----------------------------======================="+nowSongInfo);
loadingCover(songList.get(MusicService.mPosition).getPath());//获取专辑图
nowSong=findViewById(R.id.nowSong);
nowSong.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Bundle bundle = new Bundle();
int position = MusicService.mPosition;
bundle.putInt("position", position);
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setClass(IndexActivity.this, PlayDetailActivity.class);
startActivity(intent);
}
});
}else{
info_buttom.setText("🎧动次打次~");
}
}
//获取本地歌曲专辑图片
private void loadingCover(String mediaUri) {
Bitmap bitmap;
MediaMetadataRetriever mediaMetadataRetriever=new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(mediaUri);
Log.d("检查", "loadingCover: ");
byte[] picture = mediaMetadataRetriever.getEmbeddedPicture();
if(picture!=null) {//如果该歌曲有专辑图则显示
bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
album_bottom.setImageBitmap(bitmap);
}else{//没有专辑图则显示默认图片
album_bottom.setImageResource(R.drawable.playing);
}
}
//检查文件读写权限
@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){
loadSongList();
}else{
Toast.makeText(this,"拒绝权限将无法使用程序",Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
break;
}
}
//检查文件读写权限
private void checkPermission(){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
//没有权限则申请权限
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
},1);
}else{
loadSongList();
}
}
@TargetApi(19)
private void handleImageOnKitKat(Intent data) {
String imagePath=null;
Uri uri=data.getData();
if(DocumentsContract.isDocumentUri(this,uri)){
//如果是doucument类型的Uri,则通过document id处理
String docId=DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id=docId.split(":")[1];//解析出数字格式的id
String selection= MediaStore.Images.Media._ID+"="+id;
imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
}else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
Long.valueOf(docId));
imagePath=getImagePath(contentUri,null);
}
Log.d("uri类型:", "handleImageOnKitKat: content类型的Uri");
}else if("content".equalsIgnoreCase(uri.getScheme())){
//如果是content类型的Uri,则使用普通方式处理
imagePath=getImagePath(uri,null);
Log.d("uri类型:", "handleImageOnKitKat: content类型的Uri");
}else if("file".equalsIgnoreCase(uri.getScheme())){
//如果是file类型的Uri,直接获取图片路径即可
imagePath=uri.getPath();
Log.d("uri类型:", "handleImageOnKitKat: file类型的Uri");
}
disPlayImage(imagePath);
}
private String getImagePath(Uri uri, String selection) {
String path=null;
//通过Uri和selection来获取真实的图片路径
Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
if(cursor!=null){
if(cursor.moveToNext()){
path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void disPlayImage(String imagePath) {
if(imagePath!=null){
Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
ImageView index_bg=findViewById(R.id.idnex_bg);
index_bg.setImageBitmap(bitmap);
}else{
Toast.makeText(this,"设置背景图失败",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onResume() {
//返回该activity加载歌曲列表
super.onResume();
//返回activity时,定位到上一次点歌的位置
layoutManager.scrollToPositionWithOffset(MusicService.mPosition,0);
checkUserLogin();
}
播放功能实现(后台播放)
MusicService.java
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import com.liangyi.yueting.IndexActivity;
import com.liangyi.yueting.PlayDetailActivity;
import com.liangyi.yueting.R;
import com.liangyi.yueting.ScanMusicUtils;
import com.liangyi.yueting.Song;
import java.io.IOException;
import java.util.List;
//music服务,起到播放音乐的功能
//MusicService刚刚启动的时候就注册了一个广播,为的是让它在歌曲播完进行下一首播放
public class MusicService extends Service {
public static MediaPlayer mlastPlayer;//当前歌曲Media
public static int mPosition;//当前歌曲下标
private int position;
private String path=null;
private MediaPlayer player;
private Song song;
private List<Song> songlist;
private Context context;
private String TAG="MusicService";
private RemoteViews remoteView;
private Notification notification;//通知
private String notificationChannelId="playMusic";//通知渠道id
private int notifyId=1;
public static String ACTION="to_service";
public static String MAIN_UPDATE_UI="index_activity_ui";
public static String KEY_USR_ACTION = "key_usr_action";
public static final int ACTION_PRE = 0, ACTION_PLAY_PAUSE = 1, ACTION_NEXT = 2;
public static String KEY_MAIN_ACTIVITY_UI_BTN = "index_activity_ui_btn_key";
public static String KEY_MAIN_ACTIVITY_UI_TEXT = "index_activity_ui_text_key";
public static final int VAL_UPDATE_UI_PLAY = 1,VAL_UPDATE_UI_PAUSE =2;
NotificationCompat.Builder mBuilder;//notification建造者
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new musicBinder();
}
@Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
songlist= ScanMusicUtils.getMusicData(context);//获取音乐列表
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(ACTION);
registerReceiver(receiver,intentFilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
initNotificationBar();
Bundle bundle=intent.getExtras();
position=bundle.getInt("position");
if(mlastPlayer==null||mPosition!=position){
Log.d("播放页", "onStartCommand: "+"mPosition"+mPosition+" position"+position);
prepare();
}else{
player=mlastPlayer;
}
return super.onStartCommand(intent, flags, startId);
}
//初始化Notification通知
private void initNotificationBar(){
//检查当前Android版本,8.0以上需设置通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = "通知栏播放";
String description = "notification description";
int importance = NotificationManager.IMPORTANCE_MIN;
NotificationChannel mChannel = new NotificationChannel(notificationChannelId, name, importance);
mChannel.setDescription(description);
mChannel.setLightColor(Color.RED);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
}
mBuilder=new NotificationCompat.Builder(this,notificationChannelId);
//获取当前歌曲信息
Log.d("通知栏播放页init", "updateNotification: 更新状态栏歌曲新息");
String songName=songlist.get(MusicService.mPosition).getName();
String songSinger=songlist.get(MusicService.mPosition).getSinger();
//获取通知栏歌曲控制器
remoteView=new RemoteViews(getPackageName(),R.layout.notification);
remoteView.setTextViewText(R.id.notification_title,songName+" - "+songSinger);
loadingCover(songlist.get(MusicService.mPosition).getPath());
/控制按钮
//设置通知栏样式
mBuilder.setWhen(System.currentTimeMillis())
.setContentTitle("悦听~")
.setContent(remoteView)
.setSmallIcon(R.drawable.icon_music)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.icon_music));
notification=mBuilder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;//设置通知点击或滑动时不被清除
NotificationManager manager=(NotificationManager)getSystemService(Service.NOTIFICATION_SERVICE);
manager.notify(notifyId,notification);
updateNotification();
/---------------
}
private void updateNotification() {
Log.d("通知栏播放页updata", "updateNotification: 更新状态栏歌曲新息");
String title = songlist.get(MusicService.mPosition).getName()+" - "+songlist.get(MusicService.mPosition).getSinger();//更新歌曲标题
remoteView.setTextViewText(R.id.notification_title, title);
loadingCover(songlist.get(MusicService.mPosition).getPath());
//通知栏跳转到播放页面
Intent intent=new Intent();
intent.setClass(this, PlayDetailActivity.class);
Bundle bundle=new Bundle();
bundle.putInt("position",MusicService.mPosition);
Log.d("通知栏传给播放页", "initNotificationBar: 通知栏传Intent mPosition"+mPosition);
intent.putExtras(bundle);
PendingIntent pi=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
notification.contentView = remoteView;
notification=mBuilder.build();
NotificationManager manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
manager.notify(notifyId,notification);
}
//获取本地歌曲专辑图片
private void loadingCover(String mediaUri) {
Bitmap bitmap;
MediaMetadataRetriever mediaMetadataRetriever=new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(mediaUri);
Log.d("检查", "loadingCover: ");
byte[] picture = mediaMetadataRetriever.getEmbeddedPicture();
if(picture!=null) {//如果该歌曲有专辑图则显示
bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
remoteView.setImageViewBitmap(R.id.notification_album,bitmap);
// album_pic.setImageBitmap(bitmap);
}else{//没有专辑图则显示默认图片
// album_pic.setImageResource(R.drawable.playing);
remoteView.setImageViewResource(R.id.notification_album,R.drawable.playing);
}
}
void prepare(){
song = songlist.get(position);
path = song.getPath();
Log.d(TAG, "song path:"+path);
player = new MediaPlayer();//This is only done once, used to prepare the player.
if (mlastPlayer !=null){
mlastPlayer.stop();
mlastPlayer.release();
}
mlastPlayer = player;
mPosition = position;
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource(path); //Prepare resources
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
postState(getApplicationContext(), VAL_UPDATE_UI_PLAY,position);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
position+=1;
position=(position+songlist.size())%songlist.size();
song=songlist.get(position);
//
mPosition=position;
/
// Toast.makeText(context, "切换下一首:"+song.getName(), Toast.LENGTH_SHORT).show();
prepare();
}
});
}
private void postState(Context context, int state,int songid) {
Intent actionIntent = new Intent(MusicService.MAIN_UPDATE_UI);
actionIntent.putExtra(MusicService.KEY_MAIN_ACTIVITY_UI_BTN,state);
actionIntent.putExtra(MusicService.KEY_MAIN_ACTIVITY_UI_TEXT, songid);
updateNotification();
context.sendBroadcast(actionIntent);
}
//对音乐的操作
public class musicBinder extends Binder{
public boolean isPlaying(){
return player.isPlaying();//判断当前歌曲是否正在播放
}
public void play(){
if(player.isPlaying())
player.pause();
else{
player.start();
}
}
//播放下一首歌
public void next(int type){
mPosition+=type;
mPosition=(mPosition+songlist.size())%songlist.size();
song=songlist.get(mPosition);
prepare();
}
//Returns the length of the music in milliseconds
public int getDuration(){
return player.getDuration();
}
public int getPosition(){return mPosition;}
//Return the name of the music
public String getName(){
return song.getName();
}
public String getPath(){
return song.getPath();
}
public String getSinger(){
return song.getSinger();
}
//Returns the current progress of the music in milliseconds
public int getCurrenPostion(){
return player.getCurrentPosition();
}
public long getAlbumId(){
return song.getAlbumId();
}
//Set the progress of music playback in milliseconds
public void seekTo(int mesc){
player.seekTo(mesc);
}
}
//创建广播,发送和接受当前歌曲信息
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action)) {
int widget_action = intent.getIntExtra(KEY_USR_ACTION, -1);
switch (widget_action) {
case ACTION_PRE:
next(-1);
break;
case ACTION_PLAY_PAUSE:
play();
break;
case ACTION_NEXT:
next(1);
break;
default:
break;
}
}
}
};
public void play() {
if (player.isPlaying()) {
player.pause();
postState(getApplicationContext(), VAL_UPDATE_UI_PAUSE,position);
} else {
player.start();
postState(getApplicationContext(), VAL_UPDATE_UI_PLAY,position);
}
}
//Play the next music
public void next(int type){
position +=type;
position = (position + songlist.size())%songlist.size();
song = songlist.get(position);
prepare();
}
@Override
public void onDestroy() {
super.onDestroy();
}