android开发步步为营之36:四大组件之Service(中)通过bindService启动

接着上一篇的理论,我们继续学习使用另外一种方法来启动我们的Service,通过bindService让activity绑定到一个service来启动。这里使用bindService(intent, sc, Context.BIND_AUTO_CREATE);来启动服务的,我们需要定义ServiceConnectionnn,并实现里面的方法,当服务绑定成功后会调用ServiceConnectionnn中的回调函数:
public void onServiceConnected(ComponentName name, IBinder service),
回调函数里面使用musicService = ((MusicBindService.MyBinder)(service)).getService();来获取MusicBindService服务对象。
     开始我们的范例:
第一步、设计播放器页面(同上一篇)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android=" http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
    <Button android:layout_width="wrap_content" android:id="@+id/btnclose" android:text="@string/close" android:layout_height="wrap_content" android:layout_below="@+id/btnstop" android:layout_alignParentLeft="true" android:layout_marginTop="17dp" android:layout_alignParentRight="true"></Button>
    <Button android:layout_width="wrap_content" android:id="@+id/btnpause" android:text="@string/pause" android:layout_height="wrap_content" android:layout_below="@+id/btnplay" android:layout_alignParentLeft="true" android:layout_marginTop="14dp" android:layout_alignParentRight="true"></Button>
    <TextView android:layout_width="wrap_content" android:text="@string/musicplayer" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></TextView>
    <Button android:layout_width="wrap_content" android:id="@+id/btnstop" android:text="@string/stop" android:layout_height="wrap_content" android:layout_below="@+id/btnpause" android:layout_alignParentLeft="true" android:layout_marginTop="16dp" android:layout_alignParentRight="true"></Button>
    <Button android:layout_width="wrap_content" android:id="@+id/btnplay" android:text="@string/play" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_alignParentLeft="true" android:layout_marginTop="15dp" android:layout_alignParentRight="true"></Button>
</RelativeLayout>
 
第二步、设计MusicBindService.java
 
/**
 *
 */
package Test.HelloWorld;
 
import java.io.IOException;
 
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
 
/**
 * @author zhuzhifei
 *
 */
public class MusicBindService extends Service {
 
         private static final String TAG = "MusicBindService";//日志tag
 
    private MediaPlayer mediaPlayer;//播放器
    //自定义binder
    private final IBinder binder = new MyBinder();
  
    public class MyBinder extends Binder {
             MusicBindService getService() {
            return MusicBindService.this;
        }
    }
 
         //返回绑定的服务
         @Override
         public IBinder onBind(Intent arg0) {
                  // TODO Auto-generated method stub
                    Log.d(TAG, "onBind");
                            play();
                            return binder;
 
         }
         //创建服务
         @Override
         public void onCreate() {
                   super.onCreate();
                 
                   Log.d(TAG, "onCreate");
                   Toast.makeText(this, "show media player", Toast.LENGTH_SHORT).show();
                 
                 
         }
   //销毁服务
         @Override
         public void onDestroy() {
                   super.onDestroy();
                 
                   Log.d(TAG, "onDestroy");
                   Toast.makeText(this, "stop media player", Toast.LENGTH_SHORT);
                   if(mediaPlayer != null){
                            mediaPlayer.stop();
                            mediaPlayer.release();
                   }
         }
 
         //播放
         public void play() {
                   if (mediaPlayer == null) {
                            mediaPlayer = MediaPlayer.create(this, R.raw.ohprettywoman);
                            mediaPlayer.setLooping(false);
                   }
                   if (!mediaPlayer.isPlaying()) {
                            mediaPlayer.start();
                            mediaPlayer.setVolume(1.0f,1.0f);//音量大小0.1~1.0,不设默认最大
                   }
         }
    //暂停
         public void pause() {
                   if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                            mediaPlayer.pause();
                   }
         }
    //停止
         public void stop() {
                   if (mediaPlayer != null) {
                            mediaPlayer.stop();
                            try {
                                     // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
                                     mediaPlayer.prepare();
                            } catch (IOException ex) {
                                     ex.printStackTrace();
                            }
                   }
         }
}
 
第三步、设计Activity  BindMusicServiceActivity.java
package Test.HelloWorld;
 
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
 * @author zhuzhifei
 *
 */
public class BindMusicServiceActivity extends Activity implements
       OnClickListener {
    private static final String TAG = "PlayMusic";
    private Button btnplay;
    private Button btnpause;
    private Button btnstop;
    private Button btnclose;
    private MusicBindService musicService;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       // TODO Auto-generated method stub
       super.onCreate(savedInstanceState);
       setContentView(R.layout.musicview);
       btnplay = (Button) findViewById(R.id.btnplay);
       btnpause = (Button) findViewById(R.id.btnpause);
       btnstop = (Button) findViewById(R.id.btnstop);
       btnclose = (Button) findViewById(R.id.btnclose);
       btnplay.setOnClickListener(this);
       btnpause.setOnClickListener(this);
       btnstop.setOnClickListener(this);
       btnclose.setOnClickListener(this);
       // 第二种方法bindService来启动service
       connection();
    }
    //给按钮添加事件
    @Override
    public void onClick(View v) {
       int op = -1;
       // 用广播
       // Intent intent = new Intent("org.allin.android.musicReceiver");
 
       switch (v.getId()) {
       case R.id.btnplay:
           Log.d(TAG, "onClick: playing muic");
           // 开始播放
           musicService.play();
           break;
       case R.id.btnpause:
           Log.d(TAG, "onClick: pausing music");
           // 暂停播放
           musicService.pause();
           break;
       case R.id.btnstop:
           Log.d(TAG, "onClick: stoping music");
           // 停止播放
           musicService.stop();
           break;
       case R.id.btnclose:
           Log.d(TAG, "onClick: close");
           // 关闭播放器
           unbindService(sc);//解绑服务
           this.finish();
           break;
       }
 
    }
 
    private void connection() {
       Log.d(TAG, "connecting.....");
       Intent intent = new Intent("Test.HelloWorld.MusicBindService");
       bindService(intent, sc, Context.BIND_AUTO_CREATE);//绑定服务
    }
    //服务连接
    private ServiceConnection sc = new ServiceConnection() {
       @Override
       public void onServiceDisconnected(ComponentName name) {
           musicService = null;
           Log.d(TAG, "in onServiceDisconnected");
       }
 
       @Override
       public void onServiceConnected(ComponentName name, IBinder service) {
           musicService = ((MusicBindService.MyBinder) (service)).getService();
           if (musicService != null) {
              musicService.play();
           }
           Log.d(TAG, "in onServiceConnected");
       }
    };
 
}
 
第四步、AndroidManifest.xml注册我们的Activity和Service
      <service android:enabled="true" android:name=".MusicBindService">
           <intent-filter>
              <action android:name="Test.HelloWorld.MusicBindService" />
           </intent-filter>
     </service>
 
      <activity android:name=".BindMusicServiceActivity">
           <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
 
第五步、运行效果
主界面
 
查看正在运行的服务

发现在服务不在正在运行之中,可能是因为和activity绑定的原因
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、下4载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、下4载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值