dongtang5057
dongtang5057
2018-09-15 08:38

从我的内部存储android手机6.0.0中读取文件

已采纳

My app downloads mp3 files from the server and puts in the downloads folder of my internal storage (/storage/emulated/0). Now the problem I am facing is that I can't read the files and display them in the recyclerview. Its been days I am trying to access the folder but no luck.

My MainActivity.java file

public class MainActivity extends AppCompatActivity {

    private static  final String URL = "http://myurl.com/mylanguage/a_displays.php";

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    private List<Radio> radioList;
     ProgressDialog progressDialog;
    long queueid;
    DownloadManager dm;
            private MediaPlayer mediaplayer;

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

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        radioList = new ArrayList<>();

        mediaplayer = new MediaPlayer();
        adapter = new RadioAdapter(radioList,this);

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

                    DownloadManager.Query req_query = new DownloadManager.Query();
                    req_query.setFilterById(queueid);

                    Cursor c = dm.query(req_query);

                    if (c.moveToFirst()) {
                        int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                        if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                            String uriString= c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                            String path = Environment.DIRECTORY_DOWNLOADS;
                            String path1 = getFilesDir()
                                    + File.separator + path + File.separator;


                            Log.d("PathFile", path1);

                            File dir = Environment.getExternalStorageDirectory();
                            String pather = dir.getAbsolutePath();

                              Log.d("Pather", String.valueOf(pather));
                            final File folder = Environment.getExternalStorageDirectory() ;
                                                    Log.d("asd", String.valueOf(folder));
                            listFilesForFolder(folder);
                            adapter.notifyDataSetChanged();
                        }

                    }

                }
            }
        };

        registerReceiver(receiver,new IntentFilter((DownloadManager.ACTION_DOWNLOAD_COMPLETE)));

        String codeValue = getIntent().getStringExtra("CODEINTENT");
        datadummy(codeValue);
        recyclerView.setAdapter(adapter);

    }
    public void listFilesForFolder(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            } else {
                System.out.println(fileEntry.getName());
            }
        }
    }

    public void datadummy(final String codeVal) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST,URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response){
                        try {
                            JSONArray array = new JSONArray(response);

                            for (int i = 0; i < array.length(); i++) {


                                Log.d("MusicName", String.valueOf(array.getJSONObject(i).getString("audio_sound")));

                                final String music_uri = "http://myurl.com/mylanguage/" + array.getJSONObject(i).getString("audio_sound");

                                Uri uri = Uri.parse(music_uri);

                                dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                DownloadManager.Request request = new DownloadManager.Request(uri);

                                String.valueOf(request.setDestinationInExternalFilesDir(MainActivity.this,
                                        Environment.DIRECTORY_DOWNLOADS,
                                        String.valueOf(array.getJSONObject(i).getString("audio_sound"))));
                                queueid = dm.enqueue(request);
                            }


                            Log.d("-response",response);


                        }catch (JSONException e){
                            e.printStackTrace();
                            Log.d("Main", "JsonException: " + e);
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }

        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("album_code", codeVal);
                return params;
            }
        };

        RequestQueue requestqueue = Volley.newRequestQueue(this);
        requestqueue.add(stringRequest);
    }
}

I have tried almost all the ways. I need to then play those mp3 files. I am working on a live project and I am struggling a lot.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanqiang3925 duanqiang3925 3年前

    Well I found a solution myself!. We can get the path of Internal storage (Android) by using getExternalFilesDir(DIRECTORY_DOWNLOADS).

    for eg: File folder = new File(getExternalFilesDir(DIRECTORY_DOWNLOADS)+ "/uploads/" );

    For further reference refer this link, its really helpful http://grishma102.blogspot.com/2014/01/android-storage-system-to-access-path.html

    Thanks!

    点赞 评论 复制链接分享
  • duancenxie2233 duancenxie2233 3年前

    You can use this code for upload files:

    public void goforIt(){
            FTPClient con = null;
            try
            {
                con = new FTPClient();
                con.connect("192.168.2.57");
    
                if (con.login("Administrator", "KUjWbk"))
                {
                    con.enterLocalPassiveMode(); // important!
                    con.setFileType(FTP.BINARY_FILE_TYPE);
                    String data = "/sdcard/vivekm4a.m4a";
    
                    FileInputStream in = new FileInputStream(new File(data));
                    boolean result = con.storeFile("/vivekm4a.m4a", in);
                    in.close();
                    if (result) Log.v("upload result", "succeeded");
                    con.logout();
                    con.disconnect();
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    

    And for download you can use this:

    public void goforIt(){
        FTPClient con = null;
        try
        {
            con = new FTPClient();
            con.connect("192.168.2.57");
            if (con.login("Administrator", "KUjWbk"))
            {
                con.enterLocalPassiveMode(); // important!
                con.setFileType(FTP.BINARY_FILE_TYPE);
                String data = "/sdcard/vivekm4a.m4a";
                OutputStream out = new FileOutputStream(new File(data));
                boolean result = con.retrieveFile("vivekm4a.m4a", out);
                out.close();
                if (result) Log.v("download result", "succeeded");
                con.logout();
                con.disconnect();
            }
        }
        catch (Exception e)
        {
            Log.v("download result","failed");
            e.printStackTrace();
        }
    }
    
    点赞 评论 复制链接分享