本文主要是介绍Android添加USB连接提示音(SettingsProvider,PowerUI),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在framework/base/package/SettingsProvider/src/DatabaseHelper.java的方法loadGlobalSettings中添加如下内容:loadStringSetting(stmt,Settings.Global.USB_BATTERY_SOUND,R.string.def_usb_battery_sound);
参数stmt定义和初始化
SQLiteStatement stmt=null;
stmt=db.compileStatement(“INSERT OR IGNORE INTO global(name,value)”+” VALUES(?,?);”);
loadStringSetting ->loadSetting
private void loadSetting(SQLiteStatement stmt,String key,Object value){
stmt.bindString(1,key);
stmt.bindString(2,value.toString());
stmt.execute();
}//这个方法实际上就是把数据存入数据库的操作
SQLiteStatement的使用见https://liuzhichao.com/p/1664.html
参数Settings.Gloval.USB_BATTERY_SOUND是在framework/base/core/java/android/provider/Settings里面添加的URI
/***URI for the charge sound file.*@hide(不对外部开发)*/
public static final String USB_BATTERY_SOUND=”usb_battery_sound”;
<string name=”def_usb_battery_sound” translatable=”false”>/system/media/audio/notifications/Hs_in_charger.mp3</string>
该文件是通过mk文件拷贝到相应路径下的,framework/base/data/sounds/AllAudio.mk中添加
$(LOCAL_PATH)/notifications/Hs_in_charger.mp3:system/media/audio/notifications/Hs_in_charger.mp3 \
首先要在路径$(LOCAL_PATH)/notifications/下放入文件Hs_in_charger.mp3
播放提示音添加的代码,位置是framework/base/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
1. 导入用到的类
import android.media.MediaPlayer;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Vibrator;
2. 设置振动间隔
private static final long[] sVibratePattern={50,200};
3. 在onReceive方法中添加
if(plugged && !oldPlugged){playSoundbattery();//判断当前USB是否插入,如果插入,播放提示音
}
4. 编写播放提示音的方法
private void playSoundbattery(){
MediaPlayer player=new MeidaPlayer();
final ContentResolver cr=mContext.getContentResolver();
final String mSoundPath=Settings.Global.getString(cr,
Settings.Global.USB_BATTERY_SOUND);//得到之前载入到数据库的文件路径if(mSoundPath!=null){final Uri soundUri=Uri.parse(“file://”+mSoundPath);try{player.setDataSource(mContext,soundUri);
}catch(Exception e){e.printStackTrace();
}
}final AudioManager audioManager=
(AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
if(audioManager.getStreamVolume(AudioManager.STREAN_RING)!=0){player.setAudioStreamType(AudioManager.STREAM_RING);//设置音量
try{player.prepare();
}catch(Exception e){e.printStackTrace();
}
player.start();
}//only in silent mode vibrator work
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT||audioManager.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE){Vibrator vibrator=(Vibrator)mContext.getSystemService(Context.VIBRATOR_SERVICE);if(vibrator!=null){vibrator.vibrate(sVibratePattern,-1);//Vibrator shold shutdown at onStop,but if it won’ttry{Thread.sleep(1000);vibrator.cancel();
}catch(Exception e){e.printStackTrace();
}
}
}
}
这篇关于Android添加USB连接提示音(SettingsProvider,PowerUI)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!