android下载管理器通知

时间:2017-02-23 01:44:58

标签: android notifications

我是android.make的新手一个视频播放器代码从网址播放视频,用户可以从应用下载视频。直到下载并推送通知和使用服务。问题是我在下载一个视频时用户点击下载另一个视频会覆盖第一个下载。任何人都可以给我解决方案..

package crazysing.crazyweb.my.fragment;


import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.MediaController;

import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import crazysing.crazyweb.my.MainActivity;
import crazysing.crazyweb.my.R;
import crazysing.crazyweb.my.adater.CustomListAdapter;
import crazysing.crazyweb.my.app.AppController;
import crazysing.crazyweb.my.model.Movie;
import crazysing.crazyweb.my.service.NLService;


/**
 * Created by LENOVO on 14/02/2017.
 */
    public class SongPlayerFragment extends Fragment {

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    String videopath = "http://crazysing.crazyweb.my/upload/vid/";

    NotificationCompat.Builder mBuilder;
    NotificationManager mNotifyManager;

    int id = 1;
    int counter = 0;
    private NotificationReceiver nReceiver;

    String sdCard = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(sdCard, "Video/CrazySing");

    VideoView videov;
    MediaController mediaC;

    NetworkImageView videothumbNail;


    // Movies json url
    private static final String url = "http://crazysing.crazyweb.my/api/songlist.php";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */

    class NotificationReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String event = intent.getExtras().getString(NLService.NOT_EVENT_KEY);
            Log.i("NotificationReceiver", "NotificationReceiver onReceive : " + event);
            if (event.trim().contentEquals(NLService.NOT_REMOVED)) {
                killTasks();
            }
        }
    }

    private void killTasks() {
        mNotifyManager.cancelAll();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.song_player_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        videov = (VideoView) view.findViewById(R.id.videov);
        mediaC = new MediaController(getActivity());

        listView = (ListView) view.findViewById(R.id.list);
        adapter = new CustomListAdapter(getActivity(), movieList);
        listView.setAdapter(adapter);

        // Register the ListView  for Context menu
        registerForContextMenu(listView);
        listView.setOnItemClickListener(new ItemList());

        videothumbNail = (NetworkImageView) view.findViewById(R.id.placeholder);

        pDialog = new ProgressDialog(getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();


        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setFileName(obj.getString("filename"));
                                movie.setVideoPath(obj.getString("video_path"));
                                movie.setSingerName(obj.getString("singer_name"));
                                movie.setSongId(obj.getInt("songId"));
                                movie.setDuration(obj.getString("duration"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movieList.add(movie);

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

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

        videoView(" ", " "," ");

    }


    public void videoView(String videopath,String fileName, String imageName) {

        // videopath = videopath + filename;

        if (imageName == " ") {
            videothumbNail.setDefaultImageResId(R.drawable.sing);
            videothumbNail.setErrorImageResId(R.drawable.sing);
            videothumbNail.setVisibility(View.VISIBLE);
            videov.setVisibility(View.INVISIBLE);
            Log.d(TAG, "empty vedeio");
        } else {
            videothumbNail.setImageUrl(imageName, imageLoader);
            videothumbNail.setVisibility(View.VISIBLE);
            videov.setVisibility(View.INVISIBLE);

            File file = new File(myDir, fileName);
            if (file.exists()){
                Uri uri = Uri.parse(myDir+"/"+fileName);
                videov.setVideoURI(uri);
                videov.setMediaController(mediaC);
                mediaC.setAnchorView(videov);
                videov.start();
                videov.setVisibility(View.VISIBLE);
                videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        videothumbNail.setVisibility(View.GONE);
                    }
                });
            }else {

                try {
                    Uri uri = Uri.parse(videopath);
                    videov.setVideoURI(uri);
                    videov.setMediaController(mediaC);
                    mediaC.setAnchorView(videov);
                    videov.start();
                    videov.setVisibility(View.VISIBLE);
                    videov.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            videothumbNail.setVisibility(View.GONE);
                        }
                    });
                } catch (Exception e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
            }

        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.song_list_menu, menu);
        menu.setHeaderTitle("Options");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        int index = info.position;
        View view = info.targetView;

        String VideoPath = ((Movie) movieList.get(index)).getVideoPath();
        String FileName = ((Movie) movieList.get(index)).getFileName();

        String urlsToDownload[] = {VideoPath,FileName};

        switch (item.getItemId()) {
            case R.id.download:
                NotificationManager(urlsToDownload);
                Log.d(TAG, "value=" + VideoPath);
                return true;
            default:
                return super.onContextItemSelected(item);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
        killTasks();
        getActivity().unregisterReceiver(nReceiver);
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    class ItemList implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            view.setSelected(true);
            String videoUrl = ((Movie) movieList.get(position)).getVideoPath();
            String fileName = ((Movie) movieList.get(position)).getFileName();
            String bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
            Toast.makeText(SongPlayerFragment.this.getActivity(), videoUrl, Toast.LENGTH_SHORT).show();
            videoView(videoUrl,fileName, bitmap);
        }
    }


    private void downloadImagesToSdCard(String downloadUrl, String videoName) {
        FileOutputStream fos;
        InputStream inputStream = null;

        try {
            URL url = new URL(downloadUrl);
            /* making a directory in sdcard */

            /* if specified not exist create new */
            if (!myDir.exists()) {
                myDir.mkdir();
                Log.v("", "inside mkdir");
            }

            /* checks the file and if it already exist delete */
            String fname = videoName;
            File file = new File(myDir, fname);
            Log.d("file===========path", "" + file);
            if (file.exists())
                file.delete();

            /* Open a connection */
            URLConnection ucon = url.openConnection();

            HttpURLConnection httpConn = (HttpURLConnection) ucon;
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            inputStream = httpConn.getInputStream();

            /*
             * if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
             * inputStream = httpConn.getInputStream(); }
             */

            fos = new FileOutputStream(file);
            // int totalSize = httpConn.getContentLength();
            // int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fos.write(buffer, 0, bufferLength);
                // downloadedSize += bufferLength;
                // Log.i("Progress:", "downloadedSize:" + downloadedSize +
                // "totalSize:" + totalSize);
            }
            inputStream.close();
            fos.close();
            Log.d("test", "Video Saved in sdcard..");
        } catch (IOException io) {
            inputStream = null;
            fos = null;
            io.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

    private class ImageDownloader extends AsyncTask<String, String, Void> {

        @Override
        protected Void doInBackground(String... param) {
            downloadImagesToSdCard(param[0], param[1]);
            return null;
        }

        protected void onProgressUpdate(String... values) {
        }

        @Override
        protected void onPreExecute() {
            Log.i("Async-Example", "onPreExecute Called");
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i("Async-Example", "onPostExecute Called");
            mBuilder.setContentTitle("Done.");
            mBuilder.setContentText("Download complete")
                    // Removes the progress bar
                    .setProgress(0, 0, false);
            mNotifyManager.notify(id, mBuilder.build());

        }

    }

    private void NotificationManager(String... param){
        mNotifyManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(getActivity());
        mBuilder.setContentTitle("Downloading Video...").setContentText("Download in progress").setSmallIcon(R.mipmap.ic_launcher);
        //add sound
        Uri nUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(nUri);

        //vibrate
        long[] v = {500,1000};
        mBuilder.setVibrate(v);

        // Start a lengthy operation in a background thread
        mBuilder.setProgress(0, 0, true);
        mNotifyManager.notify(id, mBuilder.build());
        mBuilder.setAutoCancel(true);

        ImageDownloader imageDownloader = new ImageDownloader();
        imageDownloader.execute(param);

        ContentResolver contentResolver = getActivity().getContentResolver();
        String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
        String packageName = getActivity().getPackageName();

        // check to see if the enabledNotificationListeners String contains our
        // package name
        if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
            // in this situation we know that the user has not granted the app
            // the Notification access permission
            // Check if notification is enabled for this application
            Log.i("ACC", "Dont Have Notification access");
            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            startActivity(intent);
        } else {
            Log.i("ACC", "Have Notification access");
        }

        nReceiver = new NotificationReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(NLService.NOT_TAG);
        getActivity().registerReceiver(nReceiver, filter);
    }

}

1 个答案:

答案 0 :(得分:0)

而不是仅使用

File myDir = new File(sdCard, "Video/CrazySing");

使用

Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Video" + n + ".mp4";
            File file = new File(myDir, fname);

这将为每次生成一个唯一的文件名。

相反.mp4您可以使用视频扩展程序