• Hola, con los nuevos cambios del sitio he puesto diferentes tipos de publicidad que podrian resultar algo molestas. Sin embargo, luego de registrarte e interactuar un poco con la pagina, van a ser reemplazados por otros mas sutiles y pequeños! * A mi tampoco me gusta la publicidad, pero es una de las piezas para que el sitio esté disponible. Si bloqueas la publicidad, probá desactivarla unos dias.
    Gracias

Ayuda con permisos en Android

#1
Hola a todos, estoy creando una aplicación para Android, pero la verdad es que soy muy novato y me esta dando muchos errores... Cree un reproductor mp3, pero al momento de iniciar la aplicación se detiene la aplicación y me sale el mensaje en pantalla. Llegue a la conclusión que debe ser un problema de permisos al leer la tarjeta sd, pero el tema es que no se como solicitarlos de manera adecuada. Paso a dejar mis actividades, clases y el manifest, ignorando los layout. Si alguien es tan amable de ayudarme se los agradecería muchísimo. 

MainActivity.java :

 

package com.app1.appm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnCompletionListener {

    public MediaPlayer mp;
    public ImageView play;
    public ImageView next;
    public ImageView plus;
    public Handler mHandler = new Handler();;
    public SongsManager songManager;
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    public int currentSongIndex = 0;

    [MENTION=42589]override[/MENTION]
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // All player buttons
        final ImageView play = (ImageView) findViewById(R.id.play);
        final ImageView next = (ImageView) findViewById(R.id.next);
        final ImageView plus = (ImageView) findViewById(R.id.plus);

        // Mediaplayer
        final MediaPlayer mp = new MediaPlayer();
        SongsManager songManager = new SongsManager();

        // Getting all songs list

        songsList = songManager.getPlayList();

        // By default play first song
        playSong(0);

        /**
         * Play button click event
         * plays a song and changes button to pause image
         * pauses a song and changes button to play image
         * */
        play.setOnClickListener(new View.OnClickListener() {

            [MENTION=42589]override[/MENTION]
            public void onClick(View arg0) {
                // check for already playing
                if(mp.isPlaying()){
                        mp.pause();
                        // Changing button image to play button
                        play.setImageResource(R.drawable.play);
                }else{
                        mp.start();
                        // Changing button image to pause button
                        play.setImageResource(R.drawable.pause);
                }

            }
        });

        /**
         * Next button click event
         * Plays next song by taking currentSongIndex + 1
         * */
        next.setOnClickListener(new View.OnClickListener() {

            [MENTION=42589]override[/MENTION]
            public void onClick(View arg0) {
                // check if next song is there or not
                if(currentSongIndex < (songsList.size() - 1)){
                    playSong(currentSongIndex + 1);
                    currentSongIndex = currentSongIndex + 1;
                }else{
                    // play first song
                    playSong(0);
                    currentSongIndex = 0;
                }

            }
        });

        /**
         * Button Click event for Play list click event
         * Launches list activity which displays list of songs
         * */
        plus.setOnClickListener(new View.OnClickListener() {

            [MENTION=42589]override[/MENTION]
            public void onClick(View arg0) {
                Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
                startActivityForResult(i, 100);
            }
        });

    }

    //Permisos

    //

    /**
     * Receiving song index from playlist view
     * and play the song
     * */
    [MENTION=42589]override[/MENTION]
    protected void onActivityResult(int requestCode,
                                    int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
            currentSongIndex = data.getExtras().getInt("songIndex");
            // play selected song
            playSong(currentSongIndex);
        }

    }

    /**
     * Function to play a song
     * [MENTION=73810]par[/MENTION]am songIndex - index of song
     * */
    public void  playSong(int songIndex) {
        // Play song
        try {
            mp.reset();
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            mp.prepare();
            mp.start();

            // Changing Button Image to pause image
            play.setImageResource(R.drawable.pause);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    [MENTION=42589]override[/MENTION]
    public void onCompletion(MediaPlayer arg0) {
            if(currentSongIndex < (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                // play first song
                playSong(0);
                currentSongIndex = 0;
            }
        }
    [MENTION=42589]override[/MENTION]
    public void onDestroy(){
        super.onDestroy();
        mp.release();
    }

}
PlayListActivity.java :
 

package com.app1.appm;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class PlayListActivity extends ListActivity {
    // Songs list
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    [MENTION=42589]override[/MENTION]
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playlist);

        ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();

        SongsManager plm = new SongsManager();
        // get all songs from sdcard
        this.songsList = plm.getPlayList();

        // looping through playlist
        for (int i = 0; i < songsList.size(); i++) {
            // creating new HashMap
            HashMap<String, String> song = songsList.get(i);

            // adding HashList to ArrayList
            songsListData.add(song);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
                R.id.songTitle });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {

            [MENTION=42589]override[/MENTION]
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting listitem index
                int songIndex = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        MainActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                // Closing PlayListView
                finish();
            }
        });
    }
}


SongsManager.java (Supongo que aquí está el problema):
 

package com.app1.appm;

import android.os.Environment;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;

public class SongsManager {
    // SDCard Path
    final String MEDIA_PATH = Environment.getExternalStorageDirectory().getPath() + "/";
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    // Constructor
    public SongsManager(){

    }

    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     * */
    public ArrayList<HashMap<String, String>> getPlayList(){
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        return songsList;
    }

    /**
     * Class to filter files which are having .mp3 extension
     * */
    class FileExtensionFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
            return (name.endsWith(".mp3") || name.endsWith(".MP3"));
        }
    }
}
Utilities.java :
 

package com.app1.appm;

public class Utilities {

    /**
     * Function to convert milliseconds time to
     * Timer Format
     * Hours:Minutes:Seconds
     * */
    public String milliSecondsToTimer(long milliseconds){
        String finalTimerString = "";
        String secondsString = "";

        // Convert total duration into time
        int hours = (int)( milliseconds / (1000*60*60));
        int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
        int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
        // Add hours if there
        if(hours > 0){
            finalTimerString = hours + ":";
        }

        // Prepending 0 to seconds if it is one digit
        if(seconds < 10){
            secondsString = "0" + seconds;
        }else{
            secondsString = "" + seconds;}

        finalTimerString = finalTimerString + minutes + ":" + secondsString;

        // return timer string
        return finalTimerString;
    }

    /**
     * Function to get Progress percentage
     * [MENTION=73810]par[/MENTION]am currentDuration
     * [MENTION=73810]par[/MENTION]am totalDuration
     * */
    public int getProgressPercentage(long currentDuration, long totalDuration){
        Double percentage = (double) 0;

        long currentSeconds = (int) (currentDuration / 1000);
        long totalSeconds = (int) (totalDuration / 1000);

        // calculating percentage
        percentage =(((double)currentSeconds)/totalSeconds)*100;

        // return percentage
        return percentage.intValue();
    }

    /**
     * Function to change progress to timer
     * [MENTION=73810]par[/MENTION]am progress -
     * [MENTION=73810]par[/MENTION]am totalDuration
     * returns current duration in milliseconds
     * */
    public int progressToTimer(int progress, int totalDuration) {
        int currentDuration = 0;
        totalDuration = (int) (totalDuration / 1000);
        currentDuration = (int) ((((double)progress) / 100) * totalDuration);

        // return current duration in milliseconds
        return currentDuration * 1000;
    }
}