放置我们的媒体文件(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;}}}

之后大家可以运行试试效果。

更多相关文章

  1. Android(安卓)查询远程服务器的工具QueryUtils
  2. android定时获取数据更新
  3. android HttpClient网络通信工具类基于XML
  4. android 服务
  5. android 9.0 在rk3326平台上hidl的使用
  6. 学习笔记 Android(安卓)使用AIDL实现进程间通信
  7. Android(安卓)adb命令启动系统组件
  8. Android开发指南整理
  9. 使用NanoHTTPD在android实现web迷你服务器

随机推荐

  1. 让Cocos2d-x实现全屏等比缩放适配Android
  2. Android 平台上拍照/录像,图片/视频选择,编
  3. Android WebView中的JavaScript代码使用
  4. Android:No permission to write APN sett
  5. android控件详解----TextView
  6. Android 系统中 Location Service 的实现
  7. Android(安卓)Permission权限通知
  8. Android app:如何让 App 拿到Power key 值
  9. Android中使用代码控制Wifi及数据连接网
  10. Binary XML file line #11: You must sup