samedi 9 mai 2015

Set sound as ringtone/notification without copying to phone/SD card

I'm trying to set a sound of my choice as a ringtone or notification sound using a selection list but I've come across these issues that I don't know how to resolve. All help would be appreciated.

  1. When I select either of the options from the context menu, a dialog appears but OK and Cancel buttons don't appear (check attached images below).
  2. When a sound is set as a ringtone or notification sound is it possible to set it directly to the phone rather than copying the sound to the phone or SD card storage? I know the copy to SD card code is there but I don't know what to do with it.

Java code

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class MainActivity extends Activity {
    // variable declaration
    public AlertDialog tonePickerDialog;
    final int TYPE_RINGTONE_CHOICE = 1;
    final int TYPE_NOTIFICATION_CHOICE = 2;
    final int REQUEST_CODE_RINGTONE_PICKER = 999;
    final int REQUEST_CODE_NOTIFICATION_TONE_PICKER = 666;
    static Context context;


    private ListView mainList;
    private MediaPlayer mp;
    private final String[] listContent = {
            "chimes",
            "chord",
            "ding"
    };

    private final int[] resID = {
            R.raw.chimes,
            R.raw.chord,
            R.raw.ding
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Initializing variables
        mp = new MediaPlayer();
        mainList = (ListView) findViewById(R.id.main_listView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listContent);
        mainList.setAdapter(adapter);
        registerForContextMenu(this.mainList);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo info) {
        super.onCreateContextMenu(menu, v, info);
        menu.add(0, v.getId(), 0, "Set as Ringtone");
        menu.add(0, v.getId(), 0, "Set as Notification Sound");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo extraInfo = (AdapterContextMenuInfo) item.getMenuInfo();
        if (item.getTitle().equals("Set as Ringtone")){
            function1(item.getItemId(), extraInfo.position);
        } else if (item.getTitle().equals("Set as Notification Sound")){
            function2(item.getItemId(), extraInfo.position);
        } else {
            return false;
        }
        return true;
    }

    public void function1(int id, int resourcePosition){
        // Function to set the ringtone
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        /* Your dialog title here >> */ builder.setTitle("Ringtone");
        int currentIndex = resourcePosition; // Change this to the index of the list item long pressed item
        builder.setSingleChoiceItems(listContent, currentIndex, new
                DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int itemPosition) {

                        Toast.makeText(context, "Ringtone Selected: " + listContent[itemPosition], Toast.LENGTH_SHORT).show();

                        Uri path = null;

                        String fileName = listContent[itemPosition] + ".mp3";
                        File file = new File(Environment.getExternalStorageDirectory(), fileName);
                        if (file.exists()) {
                            Log.i("Ringtone", "File already exists");
                            //Do action
                            path = getMediaUri(file, TYPE_RINGTONE_CHOICE);
                            if (path != null) {
                                Log.i("Ringtone Uri", path.toString());
                                path = Uri.fromFile(file);
                                RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this,
                                        RingtoneManager.TYPE_RINGTONE, path);
                            }
                        } else {
                            Log.i("Ringtone", "File copying to sdcard");
                            path = copyFileToExternalStorage(context, resID[itemPosition], fileName, TYPE_RINGTONE_CHOICE);
                            if (path != null) {
                                Log.i("Ringtone Uri", path.toString());
                                RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this,
                                        RingtoneManager.TYPE_RINGTONE, path);
                            }
                        }
                        tonePickerDialog.dismiss();
                    }
                });
        tonePickerDialog = builder.create();
        tonePickerDialog.show();
    }

    public void function2(int id, int resourcePosition){
        // Function to set the notification

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        /* Your dialog title here >> */ builder.setTitle("Notificaton Sound");
        int currentIndex = resourcePosition; // Change this to the index of the list item long pressed item
        builder.setSingleChoiceItems(listContent, currentIndex, new
                DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int itemPosition) {

                        Toast.makeText(context, "Notification Sound Selected: " + listContent[itemPosition], Toast.LENGTH_SHORT).show();

                        Uri path = null;

                        String fileName = listContent[itemPosition] + ".mp3";
                        File file = new File(Environment.getExternalStorageDirectory(), fileName);
                        if (file.exists()) {
                            Log.i("Ringtone", "File already exists");
                            //Do action
                            path = getMediaUri(file, TYPE_NOTIFICATION_CHOICE);
                            if (path != null) {
                                // String completePath = Environment.getExternalStorageDirectory() + "/" + fileName;
                                Log.i("Ringtone Uri", path.toString());
                                path = Uri.fromFile(file);
                                RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this,
                                        RingtoneManager.TYPE_NOTIFICATION, path);
                            }
                        } else {
                            Log.i("Ringtone", "File copying to sdcard");
                            path = copyFileToExternalStorage(context, resID[itemPosition], fileName, TYPE_NOTIFICATION_CHOICE);
                            if (path != null) {
                                Log.i("Ringtone Uri", path.toString());
                                RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this,
                                        RingtoneManager.TYPE_NOTIFICATION, path);
                            }
                        }
                        tonePickerDialog.dismiss();
                    }
                });
        tonePickerDialog = builder.create();
        tonePickerDialog.show();
    }

    public Uri copyFileToExternalStorage (Context context, int resId, String name, int type) {
        // To make a tone a ringtone or notification tone, it should reside in sd-card.
        // This method copies the resource into the sd-card
        Uri pathUri = null;
        try {
            InputStream in = getResources().openRawResource(resId);
            // FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + name);
            File sdCardPath = Environment.getExternalStorageDirectory();
            File outFile = new File(sdCardPath, name);
            sdCardPath.mkdirs();
            FileOutputStream out = new FileOutputStream(outFile);

            byte[] buff = new byte[1024];
            int read = 0;
            while ((read = in.read(buff)) > 0) {
                out.write(buff, 0, read);
            }

            // To get the resource uri on sd-card
            Uri newUri = getMediaUri(outFile, type);
            pathUri = newUri;

            in.close();
            out.close();
        } catch(Exception e) {
            Log.e("Ringtone", "Error while copying file!");
            e.printStackTrace();
            Toast.makeText(context, "Something went wrong while copying file", Toast.LENGTH_SHORT).show();
        }
        return pathUri;
    }

    public Uri getMediaUri(File outFile, int type) {
        // To set any tone as ringtone on sd-card, it should have appropriate content values.
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, outFile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, outFile.getName());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
        if(type == TYPE_NOTIFICATION_CHOICE) {
            values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
            values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        }
        if(type == TYPE_RINGTONE_CHOICE) {
            values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
            values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        }
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        //Delete if present and insert it into the media database
        Uri uri = MediaStore.Audio.Media.getContentUriForPath(outFile.getAbsolutePath());
        getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + outFile.getAbsolutePath() + "\"", null);
        Uri newUri = getContentResolver().insert(uri, values);
        return newUri;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Toast.makeText(getActivity(), "Fragment onActivityResult() ",
        // Toast.LENGTH_SHORT).show();
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_RINGTONE_PICKER)
        {
            if (data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) != null) {
                Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                if (uri != null) {
                    Log.i("ActivityResult", "onActivityResult(): Selected Ringtone: " + uri.toString());
                    RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_RINGTONE, uri);
                }
            }
        }
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_NOTIFICATION_TONE_PICKER)
        {
            if (data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) != null) {
                Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                if (uri != null) {
                    Log.i("ActivityResult", "onActivityResult(): Selected Notification Tone: " + uri.toString());
                    RingtoneManager.setActualDefaultRingtoneUri(MainActivity.this, RingtoneManager.TYPE_NOTIFICATION, uri);
                }
            }
        }
    }
}

enter image description here enter image description here

Aucun commentaire:

Enregistrer un commentaire