Android音乐播放器简单示例
16lz
2022-05-31
放置我们的媒体文件(jack.mp3)
编写我们的媒体Service类
package org.snailteam;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MediaPlayerService extends Service {private static final String TAG = "音乐播放器服务";MediaPlayer player;public IBinder onBind(Intent intent) {return null;} public void onCreate() {//服务初始化, Toast.makeText(this, "MediaPlayerService created", Toast.LENGTH_LONG).show(); Log.i(TAG, "onCreate"); player = MediaPlayer.create(this,R.raw.jack);//此处引用到我们的mp3文件,raw文件夹的。 player.setLooping(false); } public void onStart(Intent intent, int startId) { Toast.makeText(this, " MediaPlayerService Start", Toast.LENGTH_LONG).show(); Log.i(TAG, "onStart"); player.start();} public void onDestroy() { Toast.makeText(this, " MediaPlayerService Stoped", Toast.LENGTH_LONG).show(); Log.i(TAG, "onDestroy"); player.stop();}}
输入代码R.raw.jack音乐文件没有提示时,需要修复一下
注册我们的Service组件到程序中
配置文件会多一行,注意.MediaPlayerService前面的.
<service android:name=".MediaPlayerService"></service>
我们的界面图设计如下,主要是两个按钮
主程序添加代码
package org.snailteam;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class application extends Activity implements OnClickListener{//我的主程序类是applicationprivate static final String TAG = "主程序";Button buttonStart, buttonStop; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); buttonStart = (Button)findViewById(R.id.buttonStart); buttonStop = (Button)findViewById(R.id.buttonStop); buttonStart.setOnClickListener(this); buttonStop.setOnClickListener(this); } public void onClick(View view) { switch (view.getId()) {//判断哪个按钮 case R.id.buttonStart: Log.i(TAG, "onClick: starting service"); startService(new Intent(this, MediaPlayerService.class));//引用我们自己写的媒体服务组件 break; case R.id.buttonStop: Log.i(TAG, "onClick: stopping service"); stopService(new Intent(this, MediaPlayerService.class)); break;}}}
之后大家可以运行试试效果。
更多相关文章
- Android(安卓)查询远程服务器的工具QueryUtils
- android定时获取数据更新
- android HttpClient网络通信工具类基于XML
- android 服务
- android 9.0 在rk3326平台上hidl的使用
- 学习笔记 Android(安卓)使用AIDL实现进程间通信
- Android(安卓)adb命令启动系统组件
- Android开发指南整理
- 使用NanoHTTPD在android实现web迷你服务器
随机推荐
- 让Cocos2d-x实现全屏等比缩放适配Android
- Android 平台上拍照/录像,图片/视频选择,编
- Android WebView中的JavaScript代码使用
- Android:No permission to write APN sett
- android控件详解----TextView
- Android 系统中 Location Service 的实现
- Android(安卓)Permission权限通知
- Android app:如何让 App 拿到Power key 值
- Android中使用代码控制Wifi及数据连接网
- Binary XML file line #11: You must sup