大家好今天我将为大家分享基于Service与ContentProvider的音乐播放实例,对于接触Android有一些时日的人来说,Android的核心也就是Activity,Service,ContentProvider,BroadCastReceiver,以及串联它们的Intent五大模块,Activity我就不用多说了,而我将就这个例子来说一下Service,以及ContentProvider.
Service:
Android中的服务,它与Activity不同,它是不能与用户交互的,运行在后台的程序,如果我们退出应用时,没有结束进程,它仍然在后台运行,那我们什么时候会用到Service呢?比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用 Service,我们就听不到歌了,所以这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以用Service在后台定时更新,而不用每打开应用的时候在去获取。
CotentProvider:
Android中的内容提供者,它让我们可以通过一个URL跨应用获取数据(通常是SQLite数据库),我觉得Android这个还是机制还是非常不错的,特别是我们想获取Sdcard里一些数据时,比如我们想获取所有Sdcard里的音频,视频,图片等,我们只要通过一个URL就可以轻松搞定,其实我们在开机或者插入Sdcard时,Android会做一些事情,就是它自动建库,将我们卡里所有音频,视频,图片等信息存在相应的表中,我们可以用 DDMS打开看一下如下图(data/data目录下),红线是我手机当前卡建立的数据库(不同卡会建立不同的数据库)
然后我们可以将这个数据库导出,用可以打开.db的工具打开浏览数据库的相关信息如下图所示(我这里打开了音频的数据表,可以看到我手机里所有音频文件,当然还有数据表字段):
本来这个应用是我用来写播放音乐Widget的代码,但是布局有点多,我就简单化了,做了一个比较 简单的Demo,老规矩Step by Step.
第一步:新建一个Android工程命名为MusicDemo.
第二步:候改main.xml布局文件(我这里增加了四个按钮,上一首,播放,下一首,暂停)代码如下:
view plaincopy to clipboardprint?
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:orientation="vertical"
4. android:layout_width="fill_parent"
5. android:layout_height="fill_parent"
6. >
7. <TextView
8. android:layout_width="fill_parent"
9. android:layout_height="wrap_content"
10. android:text="Welcome to Mr Wei's blog."
11. />
12. <LinearLayout
13. android:orientation="horizontal"
14. android:layout_width="fill_parent"
15. android:layout_height="wrap_content"
16. >
17. <Button
18. android:id="@+id/previous"
19. android:layout_height="fill_parent"
20. android:layout_width="wrap_content"
21. android:layout_weight="1"
22. android:text="上一首"
23. />
24. <Button
25. android:id="@+id/play"
26. android:layout_height="fill_parent"
27. android:layout_width="wrap_content"
28. android:layout_weight="1"
29. android:text="播放"
30. />
31. <Button
32. android:id="@+id/next"
33. android:layout_height="fill_parent"
34. android:layout_width="wrap_content"
35. android:layout_weight="1"
36. android:text="下一首"
37. />
38. <Button
39. android:id="@+id/pause"
40. android:layout_height="fill_parent"
41. android:layout_width="wrap_content"
42. android:layout_weight="1"
43. android:text="暂停"
44. />
45. </LinearLayout>
46. </LinearLayout>
第三步:新建一个MusicService.java类,播放音乐都是在这个类里进行的哦,代码如下:
view plaincopy to clipboardprint?
1. package com.tutor.music;
2. import java.io.IOException;
3. import android.app.Service;
4. import android.content.Intent;
5. import android.database.Cursor;
6. import android.media.MediaPlayer;
7. import android.net.Uri;
8. import android.os.IBinder;
9. import android.provider.MediaStore;
10. import android.widget.Toast;
11. public class MusicService extends Service {
12.
13. String[] mCursorCols = new String[] {
14. "audio._id AS _id", // index must match IDCOLIDX below
15. MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
16. MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
17. MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
18. MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION
19. };
20. private MediaPlayer mMediaPlayer;
21. private Cursor mCursor;
22. private int mPlayPosition = 0;
23.
24. public static final String PLAY_ACTION = "com.tutor.music.PLAY_ACTION";
25. public static final String PAUSE_ACTION = "com.tutor.music.PAUSE_ACTION";
26. public static final String NEXT_ACTION = "com.tutor.music.NEXT_ACTION";
27. public static final String PREVIOUS_ACTION = "com.tutor.music.PREVIOUS_ACTION";
28. @Override
29. public IBinder onBind(Intent arg0) {
30. // TODO Auto-generated method stub
31. return null;
32. }
33. @Override
34. public void onCreate() {
35. super.onCreate();
36. mMediaPlayer = new MediaPlayer();
37. //通过一个URI可以获取所有音频文件
38. Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
39. //这里我过滤了一下,因为我机里有些音频文件是游戏音频,很短
40. //播放不到一秒钟,我这里作了处理,默认大于10秒的可以看作是歌
41. mCursor = getContentResolver().query(MUSIC_URL, mCursorCols, "duration > 10000", null, null);
42. }
43.
44. @Override
45. public void onStart(Intent intent, int startId) {
46. super.onStart(intent, startId);
47.
48. String action = intent.getAction();
49. if(action.equals(PLAY_ACTION)){
50. play();
51. }else if(action.equals(PAUSE_ACTION)){
52. pause();
53. }else if(action.equals(NEXT_ACTION)){
54. next();
55. }else if(action.equals(PREVIOUS_ACTION)){
56. previous();
57. }
58. }
59.
60. //play the music
61. public void play() {
62. inite();
63. }
64.
65. //暂停时,结束服务
66. public void pause() {
67. stopSelf();
68. }
69. //上一首
70. public void previous() {
71. if (mPlayPosition == 0) {
72. mPlayPosition = mCursor.getCount() - 1;
73. } else {
74. mPlayPosition--;
75. }
76. inite();
77. }
78. public void next() {
79. if (mPlayPosition == mCursor.getCount() - 1) {
80. mPlayPosition = 0;
81. } else {
82. mPlayPosition++;
83. }
84. inite();
85. }
86. public void inite() {
87. mMediaPlayer.reset();
88. String dataSource = getDateByPosition(mCursor, mPlayPosition);
89. String info = getInfoByPosition(mCursor, mPlayPosition);
90. //用Toast显示歌曲信息
91. Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
92. try {
93. mMediaPlayer.setDataSource(dataSource);
94. mMediaPlayer.prepare();
95. mMediaPlayer.start();
96. } catch (IllegalArgumentException e1) {
97. e1.printStackTrace();
98. } catch (IllegalStateException e1) {
99. e1.printStackTrace();
100. } catch (IOException e1) {
101. e1.printStackTrace();
102. }
103. }
104. //根据位置来获取歌曲位置
105. public String getDateByPosition(Cursor c,int position){
106. c.moveToPosition(position);
107. int dataColumn = c.getColumnIndex(MediaStore.Audio.Media.DATA);
108. String data = c.getString(dataColumn);
109. return data;
110. }
111. //获取当前播放歌曲演唱者及歌名
112. public String getInfoByPosition(Cursor c,int position){
113. c.moveToPosition(position);
114. int titleColumn = c.getColumnIndex(MediaStore.Audio.Media.TITLE);
115. int artistColumn = c.getColumnIndex(MediaStore.Audio.Media.ARTIST);
116. String info = c.getString(artistColumn)+" " + c.getString(titleColumn);
117. return info;
118.
119. }
120. //服务结束时要释放MediaPlayer
121. public void onDestroy() {
122. super.onDestroy();
123. mMediaPlayer.release();
124. }
125. }
第四步:修改Musicdemo.java代码如下(代码比较简洁易懂):
view plaincopy to clipboardprint?
1. package com.tutor.music;
2. import android.app.Activity;
3. import android.content.ComponentName;
4. import android.content.Intent;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. public class MusicDemo extends Activity implements OnClickListener {
10.
11. private Button mPrevious,mPlay,mNext,mPause;
12. private ComponentName component;
13. public void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.main);
16. //oncreate里代码一如既往的少
17. setupViews();
18. }
19. //初始化一些工作
20. public void setupViews(){
21. component = new ComponentName(this,
22. MusicService.class);
23.
24. mPrevious = (Button)findViewById(R.id.previous);
25. mPlay = (Button)findViewById(R.id.play);
26. mNext = (Button)findViewById(R.id.next);
27. mPause = (Button)findViewById(R.id.pause);
28.
29. mPrevious.setOnClickListener(this);
30. mPlay.setOnClickListener(this);
31. mNext.setOnClickListener(this);
32. mPause.setOnClickListener(this);
33. }
34. //按钮点击事件响应
35. public void onClick(View v) {
36. if(v == mPrevious){
37. Intent mIntent = new Intent(MusicService.PREVIOUS_ACTION);
38. mIntent.setComponent(component);
39. startService(mIntent);
40. }else if(v == mPlay){
41. Intent mIntent = new Intent(MusicService.PLAY_ACTION);
42. mIntent.setComponent(component);
43. startService(mIntent);
44. }else if(v == mNext){
45. Intent mIntent = new Intent(MusicService.NEXT_ACTION);
46. mIntent.setComponent(component);
47. startService(mIntent);
48. }else{
49. Intent mIntent = new Intent(MusicService.PAUSE_ACTION);
50. mIntent.setComponent(component);
51. startService(mIntent);
52. }
53.
54. }
55. }
第五步:修改AndroidManifest.xml,这里只是把我们的MusicService申明进去,不然会报错(第14行代码),代码如下:
view plaincopy to clipboardprint?
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="com.tutor.music"
4. android:versionCode="1"
5. android:versionName="1.0">
6. <application android:icon="@drawable/icon" android:label="@string/app_name">
7. <activity android:name=".MusicDemo"
8. android:label="@string/app_name">
9. <intent-filter>
10. <action android:name="android.intent.action.MAIN" />
11. <category android:name="android.intent.category.LAUNCHER" />
12. </intent-filter>
13. </activity>
14. <service android:name=".MusicService" android:exported="true" />
15. </application>
16. <uses-sdk android:minSdkVersion="7" />
17. </manifest>
第六步:运行上述Android工程,效果如下图所示:
效果1:首界面:
效果2:点击播发按钮开始播放音乐:
效果3:我们可以在设置(Settings)->应用(Applications)->正在运行的服务(Running Services)查看我们启动了一个新的Service:
转自:http://ssd910.blog.163.com/blog/static/23876797201072513543705/
相关推荐
通过上述步骤,我们可以构建出一个基本的基于`Service`的Android音乐播放器。当然,实际开发中还需考虑性能优化、错误处理以及用户体验等方面的细节,以打造出功能完善、用户体验良好的音乐播放应用。
其次,Android多媒体框架是播放音乐的关键。源码中会涉及到MediaPlayer类,这是Android系统提供的一个用于播放音频和视频的类。开发者需要学会如何实例化MediaPlayer对象,加载音乐文件,控制播放状态,并处理各种回...
6. **使用ContentResolver**:在其他组件(如Activity或Service)中,通过`ContentResolver`接口与ContentProvider进行交互。`ContentResolver`提供了与`ContentProvider`相同的CRUD方法,但它们更易用,因为它们不...
这样,其他应用在访问这个ContentProvider时,系统会根据URI找到对应的ContentProvider实例,并根据权限判断是否允许访问。 例如,假设我们有一个名为"com.example.sharedprovider"的应用,其中包含一个...
本项目"MusicBox_service.zip"就是一个基于Service组件构建的音乐播放器实例,旨在提供一个简洁、易于理解的代码参考,帮助开发者深入理解如何在后台持续运行音乐播放任务。下面我们将详细探讨Service在音乐播放器中...
4. **服务(Service)**:为了在后台持续播放音乐,我们需要创建一个Background Service。在Service中,我们可以启动MediaPlayer实例并处理播放控制。同时,Service还需要正确处理生命周期方法,确保资源的合理使用...
Service则负责在后台持续播放音乐,即使用户离开应用也能保持播放状态;BroadcastReceiver监听系统事件,如耳机插拔,以调整播放状态;MediaPlayer是Android提供的核心音频播放组件,用于处理音乐播放的具体细节。 ...
以下将详细阐述"Android编程典型实例与项目开发工程实例"中可能涵盖的知识点。 1. **Android SDK和环境配置**:首先,所有Android应用的开发都基于Android SDK,这包括Java编译器、Android模拟器、Android开发工具...
7. **服务**:为了在后台持续播放音乐,我们可能需要创建一个`Service`。这样即使用户离开应用,音乐仍能继续播放。同时,通过`Notification`可以让用户在通知栏中控制播放。 8. **权限管理**:不要忘记在`...
Android应用的核心组件包括Activity、Service、BroadcastReceiver和ContentProvider。在`src/main/java`目录下,可以看到对应的包结构,通常以包名命名,如`com.example.myapp`。在这里,你可以编写Activity、...
功能流程图展示了用户从打开应用到播放音乐、控制音乐和查看歌词的整个过程,包括用户交互、数据处理和反馈结果等步骤。 3. 详细设计与实现 3.1 Android程序设计基础 Android应用由多个组件(Activity、Service、...
5. 背景服务:为了在后台持续播放音乐,可以创建一个Service,将MediaPlayer实例绑定到Service中,即使应用被关闭,音乐也能继续播放。 四、源码分析 深入源码,我们可以发现Android 4.3音乐播放器是如何处理线程...
这个压缩包包含了三个部分,"Android编程典型实例与项目开发案例 part 1.rar"、"part 2.rar"和"part 3.rar",提供了丰富的源代码,旨在帮助开发者深入理解Android应用的构建过程。以下是基于这些资源可能涉及的一些...
开发者需要理解如何在Manifest中正确配置活动(Activity)、服务(Service)、广播接收器(BroadcastReceiver)和内容提供者(ContentProvider)。 其次,Android应用程序通常由多个Activity组成,每个Activity对应...
4. **服务(Service)**:在后台运行的组件,即使用户离开应用程序,服务也能继续执行任务,例如播放音乐。音乐APP通常会使用Foreground Service,确保即使在低内存情况下也不被系统杀死。 5. **通知(Notification)**...
2. **服务(Service)**:Apollo作为一个音乐播放应用,核心功能运行在后台服务中,确保即使用户离开应用,音乐也能继续播放。Service是Android系统中一种特殊的组件,它可以在后台长时间运行,不依赖于用户界面。 ...
GL音乐播放器是一款基于Android平台的高级音乐播放应用,其源码提供了丰富的学习素材,涵盖了Android多媒体处理、UI设计、播放控制、数据管理等多个关键领域。下面将对这款应用的主要功能和技术实现进行详细解析。 ...
这个名为“Mp3Player01”的项目,显然是一个基于Eclipse IDE的Android音乐播放器应用实例。下面,我们将详细探讨这个项目中可能涉及的技术点,以及如何利用Eclipse进行Android应用开发。 1. **Android SDK**:...
这款高仿多米音乐播放器就是基于Android SDK开发的,它涉及到Activity管理、UI布局、服务(Service)、广播接收器(BroadcastReceiver)、内容提供者(ContentProvider)等Android核心组件的应用。 2. **音乐播放器架构**...
2.4.3 Service:在后台运行,执行长时间的任务,不与用户界面直接交互。 2.4.4 BroadcastReceiver:接收并响应系统或自定义广播事件。 2.4.5 ContentProvider:管理应用的数据,允许其他应用访问和共享数据。 ...