码迷,mamicode.com
首页 > 其他好文 > 详细

实验7 BindService模拟通信

时间:2016-05-02 21:12:26      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

课程名称

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

实验日期

2016年4月22日

实验项目名称

 BindService模拟通信

实验地点

S3010

实验类型

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

学  时

2

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

【目的】

实现启动端和BindService之间的双向通信

【要求】

1) 实现使用BindService服务播放项目源文件中的音乐;

2) 实现在启动端通过SeekBar控件控制音频音量大小;

3) 实现在启动端通过CheckBox控制音频静音。

 

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

(1)PC机 

(2)操作系统:Windows XP 

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

三、实验内容及步骤

1)在原有的Sudoku项目中的layout中添加一个musicsetting.xml文件

2)新建MusicSetting.java类

3)修改AndroidManifest.xml文件

4)新建MusicBindService类,使用Service服务播放项目源文件中的音乐,实现后台继续能播放音频。

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

代码:

MainActivity.java代码:

package com.example.shudu07;

import com.example.shudu07.MusicvoiceService.Mbinder;
import com.example.sukodu.R;

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.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
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.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    Button exitbtn, btphone, btmsn, btbackdeskt, bturl, btabout,btnewgame;
    Bundle bd;
    String account;
    String pwd;
    Intent intent;
    TextView tv; 
    LinearLayout llayoutbg;
    Mbinder mb;
    MusicvoiceService 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();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent it = new Intent();
        it.setAction("android.intent.action.BM");
        bd = getIntent().getExtras();
        account = bd.getString("account");
        pwd = bd.getString("pwd");
        tv = (TextView) findViewById(R.id.mainTitle);
        llayoutbg=(LinearLayout) findViewById(R.layout.activity_main);
        exitbtn = (Button) findViewById(R.id.exit_btn);
        btphone = (Button) findViewById(R.id.act_phone);
        btmsn = (Button) findViewById(R.id.act_msn);
        btnewgame=(Button) findViewById(R.id.new_btn);
        it.addCategory("android.intent.category.BMUSIC");
        bindService(it, conn,Context.BIND_AUTO_CREATE);
//        Toast.makeText(this, "current volum:"+String.valueOf(bs.getvolum()), Toast.LENGTH_LONG).show();
        btnewgame.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent it = new Intent();
                it.setClass(MainActivity.this, GamesActivity.class);
                startActivity(it);
            }
        });
        btabout = (Button) findViewById(R.id.about_btn);
        btmsn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                Intent it = new Intent();
                it.setAction(Intent.ACTION_SENDTO);
                it.putExtra("sms_body", "jian");
                it.setData(Uri.parse("smsto:61602"));
                startActivity(it);
            }
        });
        btbackdeskt = (Button) findViewById(R.id.act_backdeskt);
        btbackdeskt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                Intent it = new Intent();
                it.setAction(Intent.ACTION_MAIN);
                it.addCategory(Intent.CATEGORY_HOME);
                startActivity(it);
                finish();
            }
        });
        bturl = (Button) findViewById(R.id.act_url);
        bturl.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                Intent it = new Intent();
                it.setAction(Intent.ACTION_VIEW);
                it.setData(Uri.parse("http://www.baidu.com"));
                startActivity(it);
            }
        });
        btphone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                Intent it = new Intent();
                it.setAction(Intent.ACTION_CALL);
                it.setData(Uri.parse("tel:61602"));
                startActivity(it);
            }
        });
        exitbtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                intent = getIntent();
                setResult(0x1716, intent);
                finish();
            }
        });
        btabout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent it = new Intent();
                it.setAction("android.intent.action.ABOUT");
                it.addCategory("android.intent.category.CABOUT");
                startActivity(it);
            }
        });

    }

    @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);
        getMenuInflater().inflate(R.menu.actionbar, menu);
        return true;
    }

    @SuppressLint("NewApi") @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        Color co = new Color();
        Intent it =new Intent();
        switch (item.getItemId()) {
        case R.id.red: {
            tv.setTextColor(co.RED);
            break;
        }
        case R.id.blue:{
            tv.setTextColor(co.BLUE);
            break;
        }
        case R.id.green:{
            tv.setTextColor(co.GREEN);
            break;
        }
        case R.id.cancel:{
            it.setClass(MainActivity.this, LoginActivity.class);
            startActivity(it);
            finish();
            break;
        }
        case R.id.bgred:{
            llayoutbg.setBackgroundColor(co.RED);
            break;
        }
        case R.id.bggreen:{
            llayoutbg.setBackgroundColor(co.GREEN);
            break;
        }
        case R.id.help:{
            it.setClass(this, BangzActivity.class);
            startActivity(it);
            break;
        }
        case R.id.about:{
            it.setClass(this, SecondActivity.class);
            startActivity(it);
            break;
        }
        case R.id.newgame:{
            it.setClass(this, GamesActivity.class);
            startActivity(it);
            break;
        }
        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);
    }

}

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="@string/quit" />

</LinearLayout>

 

   ShezhiActivity.java代码:

package com.example.shudu07;

import com.example.shudu07.MusicvoiceService.Mbinder;
import com.example.sukodu.R;

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 ShezhiActivity extends Activity{
CheckBox cb;
SeekBar sb;
MusicvoiceService 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
                    
                }
            });
        }
    
}

 

MusicvoiceService.java代码:

package com.example.shudu07;

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 MusicvoiceService 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()+"/nanshannan.mp3");
        if(file.exists()){
            try {
                mp.setDataSource(file.getAbsolutePath());
                mp.prepare();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             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 MusicvoiceService getBackmusicService(){
            return MusicvoiceService.this;
            
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return binder;
    }

}

 

 

 

运行结果:(截图)

技术分享技术分享技术分享

 

 

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

这次实验对我来说很难,从查找资料到询问同学,我试着从多个方向解决问题,这次实验最特别的一点是用到了真实的手机设备测试,所以需要用到6.0的安卓版本的虚拟机才能运行出效果。总的来说做的还是可以的,不过还有点小问题,有待解决。

实验评语

 

实验成绩

 

指导教师签名:              年   月   日

实验7 BindService模拟通信

标签:

原文地址:http://www.cnblogs.com/xkb07/p/5453022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!