Example usage for android.media RingtoneManager getRingtone

List of usage examples for android.media RingtoneManager getRingtone

Introduction

In this page you can find the example usage for android.media RingtoneManager getRingtone.

Prototype

public static Ringtone getRingtone(final Context context, Uri ringtoneUri) 

Source Link

Document

Returns a Ringtone for a given sound URI.

Usage

From source file:im.vector.activity.CallViewActivity.java

/**
 * Provices a ringtone from a resource and a filename.
 * The audio file must have a ANDROID_LOOP metatada set to true to loop the sound.
 * @param resid The audio resource./*from ww  w  .  ja v  a  2  s  .co  m*/
 * @param filename the audio filename
 * @return a RingTone, null if the operation fails.
 */
static Ringtone getRingTone(Context context, int resid, String filename) {
    Ringtone ringtone = null;

    try {
        Uri ringToneUri = null;
        File directory = new File(Environment.getExternalStorageDirectory(),
                "/" + context.getApplicationContext().getPackageName().hashCode() + "/Audio/");

        // create the directory if it does not exist
        if (!directory.exists()) {
            directory.mkdirs();
        }

        File file = new File(directory + "/", filename);

        // if the file exists, check if the resource has been created
        if (file.exists()) {
            Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] { MediaStore.Audio.Media._ID }, MediaStore.Audio.Media.DATA + "=? ",
                    new String[] { file.getAbsolutePath() }, null);

            if ((null != cursor) && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
                ringToneUri = Uri.withAppendedPath(Uri.parse("content://media/external/audio/media"), "" + id);
            }

            if (null != cursor) {
                cursor.close();
            }
        }

        // the Uri has been received
        if (null == ringToneUri) {
            // create the file
            if (!file.exists()) {
                try {
                    byte[] readData = new byte[1024];
                    InputStream fis = context.getResources().openRawResource(resid);
                    FileOutputStream fos = new FileOutputStream(file);
                    int i = fis.read(readData);

                    while (i != -1) {
                        fos.write(readData, 0, i);
                        i = fis.read(readData);
                    }

                    fos.close();
                } catch (Exception e) {
                }
            }

            // and the resource Uri
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
            values.put(MediaStore.MediaColumns.TITLE, filename);
            values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
            values.put(MediaStore.MediaColumns.SIZE, file.length());
            values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
            values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
            values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
            values.put(MediaStore.Audio.Media.IS_ALARM, true);
            values.put(MediaStore.Audio.Media.IS_MUSIC, true);

            ringToneUri = context.getContentResolver()
                    .insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), values);
        }

        if (null != ringToneUri) {
            ringtone = RingtoneManager.getRingtone(context, ringToneUri);
        }
    } catch (Exception e) {

    }

    return ringtone;
}

From source file:org.telegram.ui.ProfileNotificationsActivity.java

@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (data == null) {
            return;
        }/* w  w  w. j  a  v  a2s .co m*/
        Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
        String name = null;
        if (ringtone != null) {
            Ringtone rng = RingtoneManager.getRingtone(ApplicationLoader.applicationContext, ringtone);
            if (rng != null) {
                if (ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
                    name = LocaleController.getString("SoundDefault", R.string.SoundDefault);
                } else {
                    name = rng.getTitle(getParentActivity());
                }
                rng.stop();
            }
        }

        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        if (requestCode == 12) {
            if (name != null) {
                editor.putString("sound_" + dialog_id, name);
                editor.putString("sound_path_" + dialog_id, ringtone.toString());
            } else {
                editor.putString("sound_" + dialog_id, "NoSound");
                editor.putString("sound_path_" + dialog_id, "NoSound");
            }
        }
        editor.commit();
        listView.invalidateViews();
    }
}

From source file:de.lespace.apprtc.ConnectActivity.java

@Override
public void onIncomingCall(final String from) {

    // Notify UI that registration has completed, so the progress indicator can be hidden.
    /*/* ww  w  . ja v  a2s.c  om*/
            //Send Broadcast message to Service
            Intent registrationComplete = new Intent(QuickstartPreferences.INCOMING_CALL);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
            
            startActivity(intent);*/

    /* Intent intent = new Intent(this, ConnectActivity.class);
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     startActivity(intent);
     Intent intent = new Intent(this,CallActivity.class);
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);*/
    // r.stop();
    //startActivity(intent);

    roomConnectionParameters.to = from;
    roomConnectionParameters.initiator = false;
    DialogFragment newFragment = new RTCConnection.CallDialogFragment();

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);

    if (alert == null) {
        // alert is null, using backup
        alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        // I can't see this ever being null (as always have a default notification)
        // but just incase
        if (alert == null) {
            // alert backup is null, using 2nd backup
            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALL);
        }
    }
    r = RingtoneManager.getRingtone(getApplicationContext(), alert);
    //  r.play();

    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(newFragment, "loading");
    transaction.commitAllowingStateLoss();

}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

void makeNoise() {
    if (car_theft) {
        noise = RingtoneManager.getRingtone(this, Settings.System.DEFAULT_RINGTONE_URI);
        noise.play();/* w  w  w  . ja  v  a2  s.c  o m*/
        return;
    }

    boolean toRing = false;
    //String fileName=MainActivity.getFileHeader()+ProfilePage.getTableName();
    String fileName = MainActivity.package_name + ".profile";
    SharedPreferences mem = getSharedPreferences(fileName, Context.MODE_PRIVATE);
    String sRing = mem.getString(PickActivity.CURRENT_RINGTON, "--");//, String);
    if (sRing.charAt(0) == '-')
        return;
    Uri ringUri = Uri.parse(sRing);//, String);
    String t0 = mem.getString(PickActivity.NO_NOISE_START, "--");//, noNoiseStart);
    String t1 = mem.getString(PickActivity.NO_NOISE_END, "--");//, noNoiseEnd);
    String[] sT0 = t0.split(":");
    int h0 = Integer.parseInt(sT0[0]);
    int m0 = Integer.parseInt(sT0[1]);
    sT0 = t1.split(":");
    int h1 = Integer.parseInt(sT0[0]);
    int m1 = Integer.parseInt(sT0[1]);
    MyTime tm = new MyTime(
            new GregorianCalendar(TimeZone.getTimeZone(getResources().getString(R.string.my_time_zone_en))));
    int iNow = tm.hour * 60 + tm.minute;
    int iU = h1 * 60 + m1;
    int iL = h0 * 60 + m0;
    if (h1 < h0) {
        toRing = (iNow > iU && iNow < iL);
    } else
        toRing = (iNow > iU || iNow < iL);
    //android.os.Debug.waitForDebugger();
    if (toRing) {
        noise = RingtoneManager.getRingtone(getApplicationContext(), ringUri);
        noise.play();
    } else
        noise = null;
}

From source file:org.telegram.ui.NotificationsSettingsActivity.java

@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
        String name = null;//from  www.  j  av  a  2s. co m
        if (ringtone != null) {
            Ringtone rng = RingtoneManager.getRingtone(getParentActivity(), ringtone);
            if (rng != null) {
                if (ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
                    name = LocaleController.getString("SoundDefault", R.string.SoundDefault);
                } else {
                    name = rng.getTitle(getParentActivity());
                }
                rng.stop();
            }
        }

        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        if (requestCode == messageSoundRow) {
            if (name != null && ringtone != null) {
                editor.putString("GlobalSound", name);
                editor.putString("GlobalSoundPath", ringtone.toString());
            } else {
                editor.putString("GlobalSound", "NoSound");
                editor.putString("GlobalSoundPath", "NoSound");
            }
        } else if (requestCode == groupSoundRow) {
            if (name != null && ringtone != null) {
                editor.putString("GroupSound", name);
                editor.putString("GroupSoundPath", ringtone.toString());
            } else {
                editor.putString("GroupSound", "NoSound");
                editor.putString("GroupSoundPath", "NoSound");
            }
        }
        editor.commit();
        listView.invalidateViews();
    }
}

From source file:com.microsoft.projectoxford.face.samples.ui.Camera2BasicFragment.java

private void detectAndFrame() {
    final Bitmap bm = BitmapFactory
            .decodeFile(getActivity().getExternalFilesDir(null).getAbsolutePath() + "/pic.jpg");
    final Bitmap bitm = Bitmap.createScaledBitmap(bm, bm.getWidth() / 8, bm.getHeight() / 8, true);
    final Bitmap bn = BitmapFactory
            .decodeFile(getActivity().getExternalFilesDir(null).getAbsolutePath() + "/pic_l.jpg");
    final Bitmap bitn = Bitmap.createScaledBitmap(bn, bn.getWidth() / 8, bn.getHeight() / 8, true);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitm.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    final AsyncTask<UUID, String, IdentifyResult[]> identifyTask = new AsyncTask<UUID, String, IdentifyResult[]>() {
        private boolean mSucceed = true;
        private String mPersonGroupId = getString(R.string.group_id);

        @Override/*  ww  w . ja v  a2s .  c  o  m*/
        protected IdentifyResult[] doInBackground(UUID... params) {
            try {

                // Start identification.
                return faceServiceClient.identity(this.mPersonGroupId, /* personGroupId */
                        params, /* faceIds */
                        1); /* maxNumOfCandidatesReturned */
            } catch (Exception e) {
                mSucceed = false;
                return null;
            }
        }

        @Override
        protected void onPostExecute(IdentifyResult[] result) {
            // Show the result on screen when detection is done.
            if (result == null) {
                showToast("error");
                return;
            }
            if (result[0].candidates.size() > 0) {
                showToast("pass");
                plu.unlock();
            } else {
                showToast("no such user");
            }
        }
    };

    AsyncTask<InputStream, String, Face[]> detectTask = new AsyncTask<InputStream, String, Face[]>() {
        @Override
        protected Face[] doInBackground(InputStream... params) {
            try {
                publishProgress("Detecting...");
                result = faceServiceClient.detect(params[0], true, // returnFaceId
                        true, // returnFaceLandmarks
                        null // returnFaceAttributes: a string like "age, gender"
                );
                if (result == null) {
                    publishProgress("Detection Finished. Nothing detected");
                    return null;
                }
                publishProgress(String.format("Detection Finished. %d face(s) detected", result.length));
                return result;
            } catch (Exception e) {
                publishProgress("Detection failed");
                return null;
            }
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(String... progress) {
        }

        @Override
        protected void onPostExecute(Face[] result) {
            if (result == null || result.length == 0) {
                showToast("No Face");
                return;
            }
            if (result.length > 1) {
                showToast("More than one Face");
                return;
            }
            if (checkb(bitm, bitn)
                    && checkl(bitm, bitn, result[0].faceLandmarks.eyeLeftOuter.x,
                            result[0].faceLandmarks.eyeLeftTop.y, result[0].faceLandmarks.eyeLeftInner.x,
                            result[0].faceLandmarks.eyeLeftBottom.y)
                    && checkl(bitm, bitn, result[0].faceLandmarks.eyeRightInner.x,
                            result[0].faceLandmarks.eyeRightTop.y, result[0].faceLandmarks.eyeRightOuter.x,
                            result[0].faceLandmarks.eyeRightBottom.y)) {

                List<UUID> faceIds = new ArrayList<>();
                for (Face face : result) {
                    faceIds.add(face.faceId);
                }
                identifyTask.execute(faceIds.toArray(new UUID[faceIds.size()]));

                //showToast("Human");
            } else {
                showToast("Photo");
                try {
                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(),
                            notification);
                    r.play();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
    detectTask.execute(inputStream);
}

From source file:com.jtxdriggers.android.ventriloid.VentriloidService.java

@SuppressWarnings("deprecation")
public boolean disconnect() {
    disconnect = true;//from w  w w.j  av  a2s  .  c  om
    connected = false;

    if (ttsActive && !muted && prefs.getBoolean("tts_disconnect", true)) {
        HashMap<String, String> params = new HashMap<String, String>();
        if (am.isBluetoothScoOn())
            params.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_VOICE_CALL));
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "Disconnected");
        tts.speak("Disconnected.", TextToSpeech.QUEUE_ADD, params);
        tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
            @Override
            public void onUtteranceCompleted(String utteranceId) {
                if (utteranceId.equals("Disconnected")) {
                    tts.shutdown();

                    stopForeground(true);
                    stopSelf();
                }
            }
        });
    } else if (ringtoneActive && !muted) {
        ringtone = RingtoneManager.getRingtone(VentriloidService.this,
                Uri.parse(prefs.getString("disconnect_notification",
                        RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString())));
        ringtone.play();

        stopForeground(true);
        stopSelf();
    } else {
        stopForeground(true);
        stopSelf();
    }

    return true;
}

From source file:org.cryptsecure.Utility.java

/**
 * Notfiy alarm. alarmType == RingtoneManager.TYPE_ALARM |
 * RingtoneManager.TYPE_NOTIFICATION | RingtoneManager.TYPE_RINGTONE
 * //from w ww.ja  v  a  2  s .  c o  m
 * @param context
 *            the context
 * @param alarmType
 *            the alarm type
 */
public static void notfiyAlarm(Context context, final int alarmType) {
    final Ringtone ringtone = RingtoneManager.getRingtone(context, RingtoneManager.getDefaultUri(alarmType));
    new Thread(new Runnable() {
        public void run() {
            ringtone.play();
        }
    }).start();
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Plays the specified ringtone from the application raw folder.
 * /*  www .  ja  v  a  2s  . c o m*/
 * @param appPackage         Application package. (you can get it by using: 
 *                      AppVigilant.thiz.getApplicationContext().getPackageName())
 * @param soundResourceId      Sound resource id
 */
public static void media_soundPlayFromRawFolder(Context context, String appPackage, int soundResourceId) {
    try {
        Uri soundUri = Uri.parse("android.resource://" + appPackage + "/" + soundResourceId);
        Ringtone r = RingtoneManager.getRingtone(context, soundUri);
        r.play();

    } catch (Exception e) {
        if (LOG_ENABLE) {
            Log.e(TAG,
                    "Error playing sound with resource id: '" + soundResourceId + "' (" + e.getMessage() + ")",
                    e);
        }
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Plays the default system notification ringtone.
 * /*from w  w w . j  a  v  a2  s . co  m*/
 * @param context
 */
public static void media_soundPlayNotificationDefault(Context context) {
    try {
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(context, soundUri);
        r.play();

    } catch (Exception e) {
        if (LOG_ENABLE) {
            Log.e(TAG, "Error playing default notification sound (" + e.getMessage() + ")", e);
        }
    }
}