刚开始接触android以及java,处于初级阶段,为此,拿音乐播放器 来进行开发,逐渐了解开发过程
第一次做音乐播放器,我的界面设计只用就用一个文本框和三个按钮,简单的进行一首哥的播放
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:text="play"
android:id="@+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="pause"
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="stop"
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
java文件
package com.example.mediaplayertext;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button bplay,bpause,bstop;
private MediaPlayer mp = new MediaPlayer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bplay = (Button)findViewById(R.id.play);
bpause = (Button)findViewById(R.id.pause);
bstop = (Button)findViewById(R.id.stop);
bplay.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
try {
mp.reset();
mp.setDataSource("/sdcard/music/多喜欢你.mp3");
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
});
bpause.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if(mp != null){
mp.pause();
}
}
});
bstop.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if(mp != null){
mp.stop();
}
}
});
}
@Override
protected void onDestroy() {
if(mp != null)
mp.release();
super.onDestroy();
}
}