android下载管理器通知

android下载管理器通知,android,notifications,Android,Notifications,我是android新手。制作一个视频播放器从url编码视频播放,用户可以从应用程序下载视频。在下载和推送通知以及使用服务之前,我一直在做。问题是,当下载一个视频时,用户单击“下载另一个视频”将覆盖第一次下载。任何人都能给我答案 package crazysing.crazyweb.my.fragment; import android.app.NotificationManager; import android.app.ProgressDialog; import android.cont

我是android新手。制作一个视频播放器从url编码视频播放,用户可以从应用程序下载视频。在下载和推送通知以及使用服务之前,我一直在做。问题是,当下载一个视频时,用户单击“下载另一个视频”将覆盖第一次下载。任何人都能给我答案

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);
    }

}
包franchysing.franchyweb.my.fragment;
导入android.app.NotificationManager;
导入android.app.ProgressDialog;
导入android.content.BroadcastReceiver;
导入android.content.ContentResolver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.media.MediaPlayer;
导入android.media.ringtonemager;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Environment;
导入android.provider.Settings;
导入android.support.v4.app.Fragment;
导入android.support.v4.app.NotificationCompat;
导入android.util.Log;
导入android.view.ContextMenu;
导入android.view.LayoutInflater;
导入android.view.MenuInflater;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.AdapterView;
导入android.widget.ListView;
导入android.widget.MediaController;
导入android.widget.Toast;
导入android.widget.VideoView;
导入com.android.volley.Response;
导入com.android.volley.VolleyError;
导入com.android.volley.VolleyLog;
导入com.android.volley.toolbox.ImageLoader;
导入com.android.volley.toolbox.JsonArrayRequest;
导入com.android.volley.toolbox.NetworkImageView;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.URLConnection;
导入java.util.ArrayList;
导入java.util.List;
导入crazysing.crazyweb.my.MainActivity;
输入crazysing.crazyweb.my.R;
导入crazysing.crazyweb.my.adater.CustomListAdapter;
导入crazysing.crazyweb.my.app.AppController;
导入crazysing.crazyweb.my.model.Movie;
导入crazysing.crazyweb.my.service.NLService;
/**
*由联想于2017年2月14日创建。
*/
公共类SongPlayerFragment扩展了片段{
//日志标签
私有静态最终字符串标记=MainActivity.class.getSimpleName();
字符串videopath=”http://crazysing.crazyweb.my/upload/vid/";
通知建筑商和造船商;
通知经理通知经理;
int-id=1;
int计数器=0;
私人通知接收人和接收人;
字符串sdCard=Environment.getExternalStorageDirectory().toString();
File myDir=新文件(SD卡,“视频/疯狂搜索”);
视讯电视;
MediaController mediaC;
NetworkImageView视频缩略图;
//电影json url
私有静态最终字符串url=”http://crazysing.crazyweb.my/api/songlist.php";
私人对话;
private List movieList=new ArrayList();
私有列表视图列表视图;
专用自定义列表适配器;
ImageLoader ImageLoader=AppController.getInstance().getImageLoader();
/**
*注意:这是自动生成的,用于实现应用程序索引API。
*看https://g.co/AppIndexing/AndroidStudio 了解更多信息。
*/
类NotificationReceiver扩展了BroadcastReceiver{
@凌驾
公共void onReceive(上下文、意图){
String event=intent.getExtras().getString(NLService.NOT_event_KEY);
Log.i(“NotificationReceiver”、“NotificationReceiver onReceive:+事件”);
if(event.trim().contentEquals(NLService.NOT_remove)){
killTasks();
}
}
}
私有任务(){
mNotifyManager.cancelAll();
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
返回充气机。充气(R.layout.song\u player\u碎片,容器,错误);
}
@凌驾
已创建视图上的公共void(视图,捆绑保存状态){
videov=(VideoView)view.findviewbyd(R.id.videov);
mediaC=新的MediaController(getActivity());
listView=(listView)view.findViewById(R.id.list);
adapter=新的CustomListAdapter(getActivity(),movieList);
setAdapter(适配器);
//为上下文菜单注册ListView
registerForContextMenu(列表视图);
setOnItemClickListener(newitemlist());
videothumbNail=(NetworkImageView)view.findViewById(R.id.placeholder);
pDialog=newprogressdialog(getActivity());
//在发出http请求之前显示进度对话框
设置消息(“加载…”);
pDialog.show();
//创建截击请求对象
JsonArrayRequest movieReq=新的JsonArrayRequest(url,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONArray响应){
Log.d(TAG,response.toString());
hidePDialog();
//解析json
对于(int i=0;iFile 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);