ListView ImageButton设置铃声

时间:2014-01-27 19:59:40

标签: android listview imagebutton

我想做以下链接:http://imagizer.imageshack.us/v2/800x600q90/42/gbs4.jpg

但是当我按下ImageButton时,我希望将声音设为铃声。

这是我的代码:


    public class ListViewAdapter extends BaseAdapter {

        private Context context;
        private List items;
        private LayoutInflater inflater;
        String path="sdcard/media/ringtone";

        public ListViewAdapter(Context context,
                               List items ) {
            inflater = LayoutInflater.from( context );
            this.context = context;
            this.items = items;
        }

        public int getCount() {
            return items.size();
        }

        public Object getItem(int position) {
            return items.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            String item = items.get(position);
            View v = null;
            if( convertView != null )
                v = convertView;
            else
                v = inflater.inflate( R.layout.list_row, parent, false);
            TextView itemTV = (TextView)v.findViewById( R.id.itemText);
            itemTV.setText( item );
            ImageButton button =
                    (ImageButton)v.findViewById( R.id.button);
            button.setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            Toast.makeText( context,
                                    "ImageButton clicked",
                                    Toast.LENGTH_SHORT).show();

                            File k = new File(path, "my sound");

                            ContentValues values = new ContentValues();
                            values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
                            values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
                            values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
                            values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
                            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);

    //Insert it into the database
                           //Insert it into the database
                        Uri newUri= context.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

                        RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
                    });
            return v;
        }
    }

这是我没有错误的MainActivity代码:


    public class MainActivity extends Activity {

        MediaPlayer mp = new MediaPlayer();
        Button stop;
        ListViewAdapter adapter;
        int s1[] =
                {
                        R.raw.el_tri_abuelita_soy_tu_nieto,
                        R.raw.el_tri_ahi_te_lo_lavas,
                        R.raw.el_tri_bajate_del_avion,

                };

        ImageButton imageButonMsj, imageButtonPhone;
        int position;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            ListView list30 = (ListView) findViewById(R.id.list);

            ArrayList items = new ArrayList();
            items.add("Abuelita soy tu nieto");
            items.add("Ahi te lo lavas");
            items.add("Bajate del avion");


            adapter = new ListViewAdapter(this, items );
            list30.setAdapter(adapter);

            list30.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView parent, View view, int position, long id) {
                    method(position);
                    }
                });
            Log.i("ramiro", "llego al final");
        }

     public void method(int position){
            if((mp.isPlaying()==true) && (this.position == position))
                mp.stop();
            else{
                this.position = position;
                try{
                    mp.reset();                               //resets the media player
                    mp.release();                             //release the media player of current audio playing
                    mp=MediaPlayer.create(this,s1[position]); //create a new  media player with the selected id
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    //mp.prepare(); //salta exception
                    mp.seekTo(0);                             //seek to starting of song means time=0 ms
                    mp.start();                               //start media player
                }
                catch (Exception e)
                {
                    Toast.makeText(getApplication(), "error exception", Toast.LENGTH_SHORT).show();
                }
            }
        }

我编辑了,现在应用程序编译了,但是当我按下ImageButton时,应用程序发送了一条消息 - >不幸的是,El Tri Sonidos已经停止了。


    FATAL EXCEPTION: main
        java.lang.SecurityException: Permission Denial: writing com.android.providers.settings.SettingsProvider uri content://settings/system from pid=690, uid=10052 requires android.permission.WRITE_SETTINGS, or grantUriPermission()
                at android.os.Parcel.readException(Parcel.java:1425)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
                at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
                at android.content.ContentResolver.insert(ContentResolver.java:864)
                at android.provider.Settings$NameValueTable.putString(Settings.java:665)
                at android.provider.Settings$System.putString(Settings.java:862)
                at android.media.RingtoneManager.setActualDefaultRingtoneUri(RingtoneManager.java:655)
                at com.institutovilma.eltri.ListViewAdapterImageButton$1.onClick(ListViewAdapterImageButton.java:80)
                at android.view.View.performClick(View.java:4084)
                at android.view.View$PerformClick.run(View.java:16966)
                at android.os.Handler.handleCallback(Handler.java:615)
                at android.os.Handler.dispatchMessage(Handler.java:92)
                at android.os.Looper.loop(Looper.java:137)
                at android.app.ActivityThread.main(ActivityThread.java:4745)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:511)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                at dalvik.system.NativeStart.main(Native Method)

如何修复此运行时错误?

4 个答案:

答案 0 :(得分:1)

您的IDE已经为您提供了正确的提示。改变您的马车线以匹配这些:

RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);

Uri newUri= context.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

请注意,在这两种情况下都必须传递上下文。

答案 1 :(得分:1)

您应该在AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

答案 2 :(得分:0)

onClickListener内,this指的是按钮,而您无法在contentResolver上调用button,您需要一个上下文。你可以尝试:

getApplicationContext().getContentResolver()

答案 3 :(得分:0)

从 API29 开始的范围存储,如果你真的不需要它,你不能拥有写权限。 有很多方法可以做到这一点。

  • 在 API29 级别,您需要像往常一样添加标志“android:requestLegacyExternalStorage="true”并请求写入权限。
  • 级别 29 以上,您需要添加权限才能读取和写入内存。
  • 如果您低于 API 级别 29,那么您应该找到一种方法来请求具有特定说明和示例的权限写入存储“https://stackoverflow.com/questions/33162152/storage-permission-error-in-marshmallow”