欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

与蓝牙耳机主动连接的 Android 实现

最编程 2024-04-20 14:42:08
...
  •     private void initA2dpService(){  
  • //      Intent i = getExplicitIntent(mContext,new Intent(IBluetoothA2dp.class.getName()));//5.0以上系统需要显示intent  
  • //详细参考http://blog.****.net/l2show/article/details/47421961  
  •         Intent i = new Intent(IBluetoothA2dp.class.getName());  
  •         boolean success = mContext.bindService(i, mConnection, Context.BIND_AUTO_CREATE);  
  •         if (success) {  
  •   
  •         } else {  
  •         }  
  •     }  
  •   
  •     public ServiceConnection mConnection = new ServiceConnection() {  
  •   
  •         @Override  
  •         public void onServiceConnected(ComponentName name, IBinder service) {  
  •             try {  
  •                 mA2dpService = IBluetoothA2dp.Stub.asInterface(service);  
  •             } catch (Exception e) {  
  •                 e.printStackTrace();  
  •             }  
  •         }  
  •   
  •         @Override  
  •         public void onServiceDisconnected(ComponentName name) {  
  •             // TODO Auto-generated method stub  
  •   
  •         }  
  •   
  •     };  
  •       
  •     public Intent getExplicitIntent(Context context, Intent implicitIntent) {  
  •         // Retrieve all services that can match the given intent  
  •         PackageManager pm = context.getPackageManager();  
  •         List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);  
  •         // Make sure only one match was found  
  •         if (resolveInfo == null || resolveInfo.size() != 1) {  
  •             return null;  
  •         }  
  •         // Get component info and create ComponentName  
  •         ResolveInfo serviceInfo = resolveInfo.get(0);  
  •         String packageName = serviceInfo.serviceInfo.packageName;  
  •         String className = serviceInfo.serviceInfo.name;  
  •         ComponentName component = new ComponentName(packageName, className);  
  •         // Create a new intent. Use the old one for extras and such reuse  
  •         Intent explicitIntent = new Intent(implicitIntent);  
  •         // Set the component to be explicit  
  •         explicitIntent.setComponent(component);  
  •         return explicitIntent;  
  •     }