下面列出了怎么用android.media.RingtoneManager的API类实例代码及写法,或者点击链接到github查看源代码。
private String shortPath(String path) {
try {
if (path != null) {
if (path.length() == 0) {
return "xDrip Default";
}
Ringtone ringtone = RingtoneManager.getRingtone(mContext, Uri.parse(path));
if (ringtone != null) {
return ringtone.getTitle(mContext);
} else {
String[] segments = path.split("/");
if (segments.length > 1) {
return segments[segments.length - 1];
}
}
}
return "";
} catch (SecurityException e) {
// need external storage permission?
checkStoragePermissions(gs(R.string.need_permission_to_access_audio_files));
return "";
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Uri value = (Uri) newValue;
if (value == null || TextUtils.isEmpty(value.toString())) {
preference.setSummary(R.string.pref_silent);
} else {
Ringtone tone = RingtoneManager.getRingtone(getActivity(), value);
if (tone != null) {
preference.setSummary(tone.getTitle(getActivity()));
}
}
return true;
}
/**
* Preview the sound on the "media" volume channel.
*
* @param alarmio The active Application instance.
*/
public void preview(Alarmio alarmio) {
if (url.startsWith("content://")) {
if (ringtone == null) {
ringtone = RingtoneManager.getRingtone(alarmio, Uri.parse(url));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ringtone.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.build());
}
}
alarmio.playRingtone(ringtone);
} else {
alarmio.playStream(url, type,
new com.google.android.exoplayer2.audio.AudioAttributes.Builder()
.setUsage(C.USAGE_ALARM)
.build());
}
}
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(long count) {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(this.cordova.getActivity().getBaseContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
}
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(final long count) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
});
}
public void onSoundSettings() {
Uri current = Prefs.getChatRingtone(this, chatId);
Uri defaultUri = Prefs.getNotificationRingtone(this);
if (current == null) current = Settings.System.DEFAULT_NOTIFICATION_URI;
else if (current.toString().isEmpty()) current = null;
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, defaultUri);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, current);
startActivityForResult(intent, REQUEST_CODE_PICK_RINGTONE);
}
public RingtonePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.RingtonePreference, defStyleAttr, defStyleRes);
mRingtoneType = TypedArrayUtils.getInt(a, R.styleable.RingtonePreference_ringtoneType,
R.styleable.RingtonePreference_android_ringtoneType, RingtoneManager.TYPE_RINGTONE);
mShowDefault = TypedArrayUtils.getBoolean(a, R.styleable.RingtonePreference_showDefault,
R.styleable.RingtonePreference_android_showDefault, true);
mShowSilent = TypedArrayUtils.getBoolean(a, R.styleable.RingtonePreference_showSilent,
R.styleable.RingtonePreference_android_showSilent, true);
mSummaryNone = a.getString(R.styleable.RingtonePreference_summaryNone);
a.recycle();
/* Retrieve the Preference summary attribute since it's private
* in the Preference class.
*/
a = context.obtainStyledAttributes(attrs,
R.styleable.Preference, defStyleAttr, defStyleRes);
mSummary = TypedArrayUtils.getString(a, R.styleable.Preference_summary,
R.styleable.Preference_android_summary);
a.recycle();
}
public String shortPath(String path) {
if(path != null) {
if(path.length() == 0) {
return "xDrip Default";
}
Ringtone ringtone = RingtoneManager.getRingtone(mContext, Uri.parse(path));
if (ringtone != null) {
return ringtone.getTitle(mContext);
} else {
String[] segments = path.split("/");
if (segments.length > 1) {
return segments[segments.length - 1];
}
}
}
return "";
}
private void sendNotification(Intent intent, String content, String title) {
intent.putExtra(NOTIFICATION_TYPE, mType);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.n_icon_couriers)
.setContentText(content)
.setContentTitle(title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(001 /* ID of notification */, notificationBuilder.build());
}
private void sendNotification(String msg) {
Intent intent = new Intent(ctx, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mNotificationManager = (NotificationManager)
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
ctx,
NOTIFICATION_CHANNEL_ID)
.setContentText(msg)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSmallIcon(android.R.drawable.ic_popup_reminder)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL);
notificationBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
public static void showNotification(String title, String content, PendingIntent intent, int notificationId, boolean sound, boolean vibrate, PendingIntent deleteIntent, Uri sound_uri) {
final Notification.Builder mBuilder = notificationBuilder(title, content, intent);
final long[] vibratePattern = {0, 1000, 300, 1000, 300, 1000};
if (vibrate) mBuilder.setVibrate(vibratePattern);
if (deleteIntent != null) mBuilder.setDeleteIntent(deleteIntent);
mBuilder.setLights(0xff00ff00, 300, 1000);
if (sound) {
Uri soundUri = (sound_uri != null) ? sound_uri : RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(soundUri);
}
final NotificationManager mNotifyMgr = (NotificationManager) xdrip.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
// if (!onetime) mNotifyMgr.cancel(notificationId);
mNotifyMgr.notify(notificationId, mBuilder.build());
}
private void playRingtone(int newRingtoneType) {
Ringtone newRingtone = RingtoneManager.getRingtone(
getApplicationContext(), RingtoneManager
.getDefaultUri(newRingtoneType));
if (null != mCurrentRingtone && mCurrentRingtone.isPlaying())
mCurrentRingtone.stop();
mCurrentRingtone = newRingtone;
if (null != newRingtone) {
mCurrentRingtone.play();
postStopRingtoneMessage();
}
}
/**
* Get the title of the ringtone from the uri of ringtone.
*
* @param context instance of the caller
* @param uri uri of the tone to search
* @return title of the tone or return null if no tone found.
*/
@Nullable
public static String getRingtoneName(@NonNull final Context context,
@NonNull final Uri uri) {
final Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
if (ringtone != null) {
return ringtone.getTitle(context);
} else {
Cursor cur = context
.getContentResolver()
.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.TITLE},
MediaStore.Audio.Media._ID + " =?",
new String[]{uri.getLastPathSegment()},
null);
String title = null;
if (cur != null) {
title = cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE));
cur.close();
}
return title;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null) {
audioPath = uri.toString();
alertMp3File.setText(shortPath(audioPath));
} else {
if (requestCode == REQUEST_CODE_CHOOSE_FILE) {
Uri selectedImageUri = data.getData();
// Todo this code is very flacky. Probably need a much better understanding of how the different programs
// select the file names. We might also have to
// - See more at: http://blog.kerul.net/2011/12/pick-file-using-intentactiongetcontent.html#sthash.c8xtIr1Y.cx7s9nxH.dpuf
//MEDIA GALLERY
String selectedAudioPath = getPath(selectedImageUri);
if (selectedAudioPath == null) {
//OI FILE Manager
selectedAudioPath = selectedImageUri.getPath();
}
audioPath = selectedAudioPath;
alertMp3File.setText(shortPath(audioPath));
}
}
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_CHOOSE_RINGTONE) {
final Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null) {
//JoH.static_toast_long(uri.toString());
selectedSound = uri.toString();
PersistentStore.setString("reminders-last-sound", selectedSound);
}
} else {
if (requestCode == REQUEST_CODE_CHOOSE_FILE) {
final Uri selectedFileUri = data.getData();
//JoH.static_toast_long(selectedFileUri.toString());
try {
selectedSound = selectedFileUri.toString();
PersistentStore.setString("reminders-last-sound", selectedSound);
// play it?
} catch (NullPointerException e) {
JoH.static_toast_long(xdrip.getAppContext().getString(R.string.problem_with_sound));
}
}
}
}
}
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == mRequestCode) {
if (data != null) {
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (callChangeListener(uri != null ? uri.toString() : "")) {
onSaveRingtone(uri);
}
}
return true;
}
return false;
}
private void performErroredNotification(Context context, RemoteMessage remoteMessage){
NotificationCompat.Builder builder;
android.app.NotificationManager notificationManager = (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, weMessage.NOTIFICATION_CHANNEL_NAME);
} else {
builder = new NotificationCompat.Builder(context);
builder.setVibrate(new long[]{1000, 1000})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
}
Notification notification = builder
.setContentTitle(context.getString(R.string.notification_error))
.setContentText(context.getString(R.string.notification_error_body))
.setSmallIcon(R.drawable.ic_app_notification_white_small)
.setWhen(remoteMessage.getSentTime())
.setAutoCancel(true)
.build();
notificationManager.cancel(ERRORED_NOTIFICATION_TAG);
notificationManager.notify(ERRORED_NOTIFICATION_TAG, notification);
}
public String shortPath(String path) {
if(path != null) {
if(path.length() == 0) {
return "xDrip Default";
}
Ringtone ringtone = RingtoneManager.getRingtone(mContext, Uri.parse(path));
if (ringtone != null) {
return ringtone.getTitle(mContext);
} else {
String[] segments = path.split("/");
if (segments.length > 1) {
return segments[segments.length - 1];
}
}
}
return "";
}
/**
* Create and show a simple notification containing the received GCM message.
*
* @param message GCM message received.
*/
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("GCM Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
private void maybePlaySound() {
if (mSoundEnabled &&
(!mPowerManager.isInteractive() || !mSoundWhenScreenOffOnly)) {
try {
final Ringtone sfx = RingtoneManager.getRingtone(mContext,
Uri.parse(mSoundUri));
if (sfx != null) {
AudioAttributes attrs = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
sfx.setAudioAttributes(attrs);
sfx.play();
}
} catch (Throwable t) {
XposedBridge.log(t);
}
}
}
private void sendMultilineNotification(String title, String messageBody) {
//Log.e("DADA", "ADAD---"+title+"---message---"+messageBody);
int notificationId = 0;
Intent intent = new Intent(this, MainDashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, notificationId, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_custom_notification)
.setLargeIcon(largeIcon)
.setContentTitle(title/*"Firebase Push Notification"*/)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
}
/**
* Sets the ringtone of type specified by the name.
*
* @param name should be Settings.System.RINGTONE or Settings.System.NOTIFICATION_SOUND.
* @param value can be a canonicalized uri or "_silent" to indicate a silent (null) ringtone.
*/
private void setRingtone(String name, String value) {
// If it's null, don't change the default
if (value == null) return;
Uri ringtoneUri = null;
if (SILENT_RINGTONE.equals(value)) {
ringtoneUri = null;
} else {
Uri canonicalUri = Uri.parse(value);
ringtoneUri = mContext.getContentResolver().uncanonicalize(canonicalUri);
if (ringtoneUri == null) {
// Unrecognized or invalid Uri, don't restore
return;
}
}
final int ringtoneType = Settings.System.RINGTONE.equals(name)
? RingtoneManager.TYPE_RINGTONE : RingtoneManager.TYPE_NOTIFICATION;
RingtoneManager.setActualDefaultRingtoneUri(mContext, ringtoneType, ringtoneUri);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null){
return;
}
switch(requestCode){
case REQUEST_SELECT_ALARM_RINGTONE:
Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
L.i("pickedUri:" + pickedUri);
if (pickedUri == null){
showMsg("请选择一个报警铃音" + SF.TIP);
}else{
setSP.setAntiTheftRingtoneUriString(pickedUri.toString());
showMsg("报警铃音设置已保存" + SF.TIP);
}
break;
}
}
private void buildSummary() {
if (SettingUtils.getEnableFetchMSG()) {
String value = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(SettingActivity.FREQUENCY,
"1");
frequency.setSummary(getActivity().getResources().getStringArray(R.array.frequency)[Integer.valueOf(value) - 1]);
} else {
frequency.setSummary(getString(R.string.stopped));
}
if (uri != null) {
Ringtone r = RingtoneManager.getRingtone(getActivity(), uri);
ringtone.setSummary(r.getTitle(getActivity()));
} else {
ringtone.setSummary(getString(R.string.silent));
}
}
private void ringPhone(){
int ringerMode = ((AudioManager) getSystemService(AUDIO_SERVICE)).getRingerMode();
if(ringerMode == AudioManager.RINGER_MODE_SILENT) return;
vibrator = ((Vibrator) getSystemService(VIBRATOR_SERVICE));
long[] pattern = {1500, 800, 800, 800};
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
VibrationEffect vibe = VibrationEffect.createWaveform(pattern, 0);
vibrator.vibrate(vibe);
}else{
vibrator.vibrate(pattern, 0);
}
if(ringerMode == AudioManager.RINGER_MODE_VIBRATE) return;
ringtone = RingtoneManager.getRingtone(this, RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE));
ringtone.play();
}
@Override
public void onCreate() {
SharedPreferences sharedPreferences = getSharedPreferences("karmaDetectorPrefs", Context.MODE_PRIVATE);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "WifiScannerService");
defaultNotificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
shouldRun = true;
int DEFAULT_SCAN_FREQ = 300;
frequency = sharedPreferences.getInt("scanFrequency", DEFAULT_SCAN_FREQ);
if (!wifiManager.isWifiEnabled()) {
boolean ret = wifiManager.setWifiEnabled(true);
if (!ret)
addToLog("Problem activating Wifi. Active scans will not work.");
}
removeDecoyNetworks();
createDecoyNetwork();
startBroadcastReceiver();
super.onCreate();
}
@Test
public void testGetSoundUriNotRaw() {
final String packageName = "com.package";
final String soundName = "sound.wav";
final String rawSoundName = "sound";
final int soundResourceID = 1;
Uri defaultSoundUri = PowerMockito.mock(Uri.class);
when(mReactApplicationContext.getPackageName()).thenReturn(packageName);
when(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).thenReturn(defaultSoundUri);
when(mBundle.getString(KEY_REMOTE_NOTIFICATION_SOUND_NAME)).thenReturn(soundName);
Resources res = PowerMockito.mock(Resources.class);
when(res.getIdentifier(soundName, RESOURCE_DEF_TYPE_RAW, packageName)).thenReturn(0);
when(res.getIdentifier(rawSoundName, RESOURCE_DEF_TYPE_RAW, packageName)).thenReturn(soundResourceID);
when(mReactApplicationContext.getResources()).thenReturn(res);
getSoundUri(mReactApplicationContext, mBundle);
verifyStatic(Uri.class);
Uri.parse("android.resource://" + packageName + "/" + soundResourceID);
}
private @NonNull String getRingtoneSummary(@NonNull Context context, @Nullable Uri ringtone) {
if (ringtone == null) {
return context.getString(R.string.preferences__default);
} else if (ringtone.toString().isEmpty()) {
return context.getString(R.string.preferences__silent);
} else {
Ringtone tone = RingtoneManager.getRingtone(getActivity(), ringtone);
if (tone != null) {
return tone.getTitle(context);
}
}
return context.getString(R.string.preferences__default);
}
private @NonNull String getRingtoneSummary(@NonNull Context context, @Nullable Uri ringtone) {
if (ringtone == null) {
return context.getString(R.string.preferences__default);
} else if (ringtone.toString().isEmpty()) {
return context.getString(R.string.preferences__silent);
} else {
Ringtone tone = RingtoneManager.getRingtone(getActivity(), ringtone);
if (tone != null) {
return tone.getTitle(context);
}
}
return context.getString(R.string.preferences__default);
}
/**
* Handles incoming data events from the mesh - toasts the contents of the data.
*
* @param e event object from mesh
*/
private void handleDataReceived(RightMeshEvent e) {
final MeshManager.DataReceivedEvent event = (MeshManager.DataReceivedEvent) e;
runOnUiThread(() -> {
// Toast data contents.
String message = new String(event.data);
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
// Play a notification.
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(MainActivity.this, notification);
r.play();
});
}