Android 媒体键监听以及模拟媒体键盘的实现 demo

      有时我们需要程序模拟按钮或点击,而手机本身又没有,哪么可以采取其它方式 模拟实现,最后再去实际设备去测试(前期一般都拿不到设备);

如上一首,下一首,暂停等,手机上是没有的,但有些设备上是有的,所以我们只能模拟;

模拟按钮一种可以采用adb 命令;

别一种采用程序,这里主要讲采用程序的方法:

通过Runtime实现,模拟媒体上一首代码如下:

try
		{
			String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MEDIA_NEXT;
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec(keyCommand);
	 
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



模拟上一首

try
		{
			String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MEDIA_PREVIOUS;
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec(keyCommand);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



如果需要模拟其它按键只需将KeyEvent.KEYCODE_MEDIA_PREVIOUS替换成其它键值即可。


下面讲一下 媒体键监听:

首先我们定义一个广播类 MediaButtonReceive 它继承广播接收器类(BroadbcastReceiver),那么它就具备了BroadbcastReceiver类的使用方式,

        点击MEDIA_BUTTON发送的Intent Action 为:ACTION_MEDIA_BUTTON  ="android.intent.action.MEDIA_BUTTON"
        Intent 附加值为(Extra)点击MEDIA_BUTTON的按键码 :    

         //获得KeyEvent对象
        KeyEvent keyEvent = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        //获得Action
        String intentAction = intent.getAction() ;


     在取得音频焦点时,在AudioManager对象注册一个MediaoButtonRecevie,使它成为MEDIA_BUTTON的唯一接收器 也就是说只有它能收到,其他的都收不到这个广播了,否则的话会造成的混乱,在失去音频焦点时反注册,这样才能保证其它应用能正常使用媒体键;

    该广播必须在AndroidManifest.xml文件中进行声明,否则就监听不到该MEDIA_BUTTON广播了

 在AudioManager对象注册一个MediaoButtonRecevie;


下面看一下MediaButtonReceiver类 的实现:

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class MediaButtonReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// 获得Action
		String intentAction = intent.getAction();

		// 获得KeyEvent对象
		KeyEvent keyEvent = (KeyEvent) intent
				.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

		Log.e("MediaButtonReceiver", "Action ---->" + intentAction
				+ "  KeyEvent----->" + keyEvent.toString());

		if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
			
	        boolean isActionUp = (keyEvent.getAction()==KeyEvent.ACTION_UP);
	        // 这里会收到两次,我们只判断 up 
	        if(!isActionUp)
	        {
	        	return;
	        }
	             
			// 获得按键字节码
			int keyCode = keyEvent.getKeyCode();
			// 按下 / 松开 按钮
			int keyAction = keyEvent.getAction();
			// 获得事件的时间
			long downtime = keyEvent.getEventTime();

			// 获取按键码 keyCode
			StringBuilder sb = new StringBuilder();
			// 这些都是可能的按键码 , 打印出来用户按下的键
			if (KeyEvent.KEYCODE_MEDIA_NEXT == keyCode) {
				sb.append("KEYCODE_MEDIA_NEXT");
				Toast.makeText(context,
						"receive KEYCODE_MEDIA_NEXT",
						Toast.LENGTH_SHORT).show();
			}
	
			if (KeyEvent.KEYCODE_MEDIA_PREVIOUS == keyCode) {
				sb.append("KEYCODE_MEDIA_PREVIOUS");
				Toast.makeText(context,
						"receive KEYCODE_MEDIA_PREVIOUS",
						Toast.LENGTH_SHORT).show();
			}
		
			// 输出点击的按键码
			Log.e("MediaButtonReceiver", sb.toString());
		}
	}

}



在AndroidManifest.xml声明我们定义的广播类,它需要通过AudioManager对象注册

 

<span style="font-size:18px;">         <receiver android:name="MediaButtonReceiver">
          <intent-filter >
                <action android:name="android.intent.action.MEDIA_BUTTON"></action>
          </intent-filter>
        </receiver></span>
AudioManager注册一个MediaButtonReceiver() ;

<span style="font-size:18px;">		//获得AudioManager对象  
		AudioManager mAudioManager =(AudioManager)getSystemService(Context.AUDIO_SERVICE);     
		//构造一个ComponentName,指向MediaoButtonReceiver类  
		//下面为了叙述方便,我直接使用ComponentName类来替代MediaoButtonReceiver类  
		ComponentName  mbCN = new ComponentName(getPackageName(),MediaButtonReceiver.class.getName());  
		//注册一个MedioButtonReceiver广播监听  
		mAudioManager.registerMediaButtonEventReceiver(mbCN);</span>

下面看一下调用类的实现MainActivity .java

import com.example.ydsdkdemo.R;
 

import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    private Context mContext;
    private AudioManager audioManager;
    private ComponentName mComponentName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        init();

    }

    private void init() {
        
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mComponentName = new ComponentName(getPackageName(),
                MediaButtonReceiver.class.getName());
        
        if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager
                .requestAudioFocus(focusChangeListener,
                        AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)) {
            audioManager.registerMediaButtonEventReceiver(mComponentName);
        }
        
  
        
        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MEDIA_NEXT;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);
     
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
    }
    
 
    public void lastOne(View v)
    {
        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MEDIA_PREVIOUS;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void nextOne(View v)
    {
        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MEDIA_NEXT;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);
     
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void voiceSearch(View v)
    {
        try
        {
            String keyCommand = "input keyevent " + KeyEvent.KEYCODE_MEDIA_RECORD;
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(keyCommand);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //焦点问题
    private AudioManager.OnAudioFocusChangeListener focusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {

            case AudioManager.AUDIOFOCUS_LOSS:// 长时间失去
             
                Toast.makeText(mContext,
                        "receive AudioManager.AUDIOFOCUS_LOSS",
                        Toast.LENGTH_SHORT).show();
                audioManager.unregisterMediaButtonEventReceiver(mComponentName);
                audioManager.abandonAudioFocus(focusChangeListener);//放弃焦点监听
                break;

            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:// 短时间失去
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:// 短时间失去,但可以共用
             
                break;

            case AudioManager.AUDIOFOCUS_GAIN:// 获得音频焦点
                audioManager.registerMediaButtonEventReceiver(mComponentName);
                break;

            }
        }
    };


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        audioManager.unregisterMediaButtonEventReceiver(mComponentName);
        super.onDestroy();
    }

}
值得注意的一点时,当我们为一个应用程序注册了MediaoButtonReceiver时,在程序离开时,我们需要取消该







Demo地址:

http://download.csdn.net/detail/q610098308/9147909



posted @ 2015-09-29 18:01  恋恋西风  阅读(1649)  评论(0编辑  收藏  举报