实验报告

课程名称

基于Android平台移动互联网开发

实验日期

2016年5月2日

实验项目名称

BindService模拟通信

实验地点

S3010

实验类型

□验证型    √设计型    □综合型

学  时

2

一、实验目的及要求(本实验所涉及并要求掌握的知识点)

  1. 实现启动端和BindService之间的双向通信;
  2. 实现从启动端传递一个数据至BindService端;
  3. 实现使用BindService服务播放项目源文件中的音乐;
  4. 实现在启动端通过“增加”和“降低”两个按钮控制音频音量大小;
  5. 实现在启动端通过“暂停”按钮控制音频暂停播放。

 

二、实验环境(本实验所使用的硬件设备和相关软件)

(1)PC机

(2)操作系统:Windows XP

(3)软件: Eclipse, JDK1.6,Android SDK,ADT

三、实验内容及步骤

  1. 新建工程;
  2. 新建并完善BackmusicService和SettingActivity类;
  3. 新建music.xml界面。

 

四、实验结果(本实验源程序清单及运行结果或实验结论、实验设计图)

代码:

MainActivity:

package com.example.mediaplayer;

import java.io.File;
import java.io.IOException;

import com.example.mediaplayer.R;
import com.example.mediaplayer.BackmusicService.Mbinder;
import com.example.mediaplayer.BackmusicService;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends Activity {
     Button   source,local,network,stop,video,exit;
     private MediaPlayer mediaplayer=new MediaPlayer();
     private File file;
     private TextView tv;
     private String uri="http://y.qq.com/#type=song&mid=003e0OzZ0wFBRX&tpl=yqq_song_detail";
     private VideoView videoView;
     MediaController mc;
     Mbinder mb;
     BackmusicService bs;
     
     ServiceConnection conn=new ServiceConnection() {
            
            @Override
            public void onServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub
                
            }
            
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub
                mb=(Mbinder) service;
                bs=mb.getBackmusicService();
            }
        };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent it = new Intent();
        it.setAction("android.intent.action.BM");
        tv=(TextView)findViewById(R.id.textView1);
        source=(Button)findViewById(R.id.button1);
        local=(Button)findViewById(R.id.button2);
        network=(Button)findViewById(R.id.button3);
        stop=(Button)findViewById(R.id.button4);
        video=(Button)findViewById(R.id.button5);
        videoView=(VideoView)findViewById(R.id.videoView1);
        File file=new File("/sdcard/bluevird.mp4");
        mc=new MediaController(MainActivity.this);
        it.addCategory("android.intent.category.BMUSIC");
        bindService(it, conn,Context.BIND_AUTO_CREATE);
    
        source.setOnClickListener(new OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method   stub
                mediaplayer=MediaPlayer.create(MainActivity.this,   R.raw.what);
                mediaplayer.start();
                Toast.makeText(MainActivity.this,"playing the music",Toast.LENGTH_SHORT).show();
            }

         });

         stop.setOnClickListener(new OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method   stub
                if(mediaplayer.isPlaying()){
                mediaplayer.stop();
                Toast.makeText(MainActivity.this,"stop",Toast.LENGTH_SHORT).show();
                }
            }
         });
         local.setOnClickListener(new OnClickListener() {
             
             @SuppressLint("SdCardPath")   @Override
             public void onClick(View arg0) {
                 // TODO Auto-generated method   stub
                 try {
                    mediaplayer.reset();
                    mediaplayer.setDataSource("/sdcard/Louis Armstrong - What A Wonderful World.mp3");
                    mediaplayer.prepare();
                    mediaplayer.start();
                    Toast.makeText(MainActivity.this,"playing the sdcard music",Toast.LENGTH_SHORT).show();
                 } catch (IllegalStateException   e) {
                    // TODO Auto-generated catch   block
                    e.printStackTrace();
                 } catch (IOException e) {
                    // TODO Auto-generated catch   block
                    e.printStackTrace();
                 }     
          }
          });
          network.setOnClickListener(new OnClickListener(){
   
          @Override
          public void onClick(View arg0) {
             // TODO Auto-generated method stub
             mediaplayer.reset();
             try{
                 mediaplayer.setDataSource(uri);
             }catch(IllegalStateException e) {
                 // TODO Auto-generated catch   block
                 e.printStackTrace();
             } catch (IOException e) {
                 // TODO Auto-generated catch   block
                 e.printStackTrace();
             }
             Toast.makeText(MainActivity.this,"network music",Toast.LENGTH_SHORT).show();
             Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(uri));
             startActivity(intent);
          }
             
          });
          video.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                File file=new File("/sdcard/bluebird.mp4");
                videoView.setVideoPath(file.getAbsolutePath());
                videoView.setMediaController(mc);
                try{
                    videoView.start();
                } catch (Exception e){
                    e.printStackTrace();
                }
                Toast.makeText(MainActivity.this,"playing the video",Toast.LENGTH_SHORT).show();
            }
        });
         
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent it =new Intent();
        switch (item.getItemId()) {
        case R.id.music: {
        it.setAction("android.intent.action.MUSIC");
        Bundle bd = new Bundle();
        bd.putBinder("service", mb);
        it.putExtras(bd);
        startActivity(it);
        break;
    }
    default:{
        break;
    }
    }
    return super.onOptionsItemSelected(item);
    }
    
}

BackmusicService:

package com.example.mediaplayer;

import java.io.File;
import java.io.IOException;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;

public class BackmusicService extends Service{
MediaPlayer mp=new MediaPlayer();
Mbinder binder=new Mbinder();
AudioManager  audioManager;

boolean isSilent=false;

    public void setsilent(boolean isSilent){
        if(isSilent){
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,0,0);    
            }else{
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,1000,1000);
            }

    }
    public void setvolum(int setting){
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,setting,100);

    }
    public void onCreate() {
        // TODO Auto-generated method stub
        File file=new File(Environment.getExternalStorageDirectory().getPath()+"/what.mp3");
        mp=MediaPlayer.create(this, R.raw.what);
        audioManager=(AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mp.start();

        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        mp.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if(mp.isPlaying()){
            mp.stop();
            mp.release();
            
        }
    }


    public class Mbinder extends Binder{
        public BackmusicService getBackmusicService(){
            return BackmusicService.this;
            
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return binder;
    }

}

SettingActivity:

package com.example.mediaplayer;

import com.example.mediaplayer.BackmusicService.Mbinder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class SettingActivity extends Activity{
CheckBox cb;
SeekBar sb;
BackmusicService bs;

         @SuppressLint("NewApi") public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.music);
            Bundle bd=getIntent().getExtras();
            bs=((Mbinder) bd.getBinder("service")).getBackmusicService();
            sb=(SeekBar) findViewById(R.id.seek1);
            cb=(CheckBox) findViewById(R.id.checkquit);
            cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // TODO Auto-generated method stub
                    bs.setsilent(isChecked);
                }
            });
            sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress,
                        boolean fromUser) {
                    // TODO Auto-generated method stub
                    bs.setvolum(progress);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub
                    
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // TODO Auto-generated method stub
                    
                }
            });
        }
    
}

Music.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <SeekBar
        android:id="@+id/seek1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <CheckBox
        android:id="@+id/checkquit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="quite" />

</LinearLayout>

运行结果:(截图)

 

五、实验总结(对本实验结果进行分析,实验心得体会及改进意见)

本次实验较难,涉及到了大量的新知识,并且运用了许多抽象的概念,要多加研究才能将其掌握。