<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" /> <VideoView android:id="@+id/ha" android:visibility="gone" android:layout_marginTop="200dp" android:layout_width="match_parent" android:layout_height="match_parent" />
</RelativeLayout>
213121321321321322132
321321321231231321312132132<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/file_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ProgressBar android:id="@+id/progressBar2" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/file_textview" /> <Button android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/progressBar2" android:layout_toLeftOf="@+id/stop_button" android:text="start" /> <Button android:id="@+id/stop_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@+id/progressBar2" android:text="stop" /> </RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/file_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ProgressBar android:id="@+id/progressBar2" style="?android:attr/progressBarStyleHorizontal" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" /> <Button android:id="@+id/start_button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="start" /> <Button android:id="@+id/stop_button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="stop" /> </LinearLayout> </LinearLayout>415646546545665
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sjx.bawei.com.download2"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".service.DownloadService"/> </application> </manifest>/*/*/*/*//*/*//**/
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sjx.bawei.com.download2"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".service.DownloadService"/> </application> </manifest>/-/-/-/-/-/-/-/-/-/-/
package sjx.bawei.com.download2.util; import java.util.HashMap; import java.util.Map; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; import sjx.bawei.com.download2.MainActivity; import sjx.bawei.com.download2.R; import sjx.bawei.com.download2.entitis.FileInfo; import sjx.bawei.com.download2.service.DownloadService; public class NotificationUtil { private Context mContext; private NotificationManager mNotificationManager = null; private Map<Integer, Notification> mNotifications = null; public NotificationUtil(Context context) { this.mContext = context; // 获得系统通知管理者 mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // 创建通知的集合 mNotifications = new HashMap<Integer, Notification>(); } /** * 显示通知栏 * @param fileInfo */ public void showNotification(FileInfo fileInfo) { // 判断通知是否已经显示 if(!mNotifications.containsKey(fileInfo.getId())){ Notification notification = new Notification(); notification.tickerText = fileInfo.getFileName() + "开始下载"; notification.when = System.currentTimeMillis(); notification.icon = R.mipmap.ic_launcher; notification.flags = Notification.FLAG_AUTO_CANCEL; // 点击通知之后的意图 Intent intent = new Intent(mContext, MainActivity.class); PendingIntent pd = PendingIntent.getActivity(mContext, 0, intent, 0); notification.contentIntent = pd; // 设置远程试图RemoteViews对象 RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.notification); // 控制远程试图,设置开始点击事件 Intent intentStart = new Intent(mContext, DownloadService.class); intentStart.setAction(DownloadService.ACTION_START); intentStart.putExtra("fileInfo", fileInfo); PendingIntent piStart = PendingIntent.getService(mContext, 0, intentStart, 0); remoteViews.setOnClickPendingIntent(R.id.start_button, piStart); // 控制远程试图,设置结束点击事件 Intent intentStop = new Intent(mContext, DownloadService.class); intentStop.setAction(DownloadService.ACTION_STOP); intentStop.putExtra("fileInfo", fileInfo); PendingIntent piStop = PendingIntent.getService(mContext, 0, intentStop, 0); remoteViews.setOnClickPendingIntent(R.id.stop_button, piStop); // 设置TextView中文件的名字 remoteViews.setTextViewText(R.id.file_textview, fileInfo.getFileName()); // 设置Notification的视图 notification.contentView = remoteViews; // 发出Notification通知 mNotificationManager.notify(fileInfo.getId(), notification); // 把Notification添加到集合中 mNotifications.put(fileInfo.getId(), notification); } } /** * 取消通知栏通知 */ public void cancelNotification(int id) { mNotificationManager.cancel(id); mNotifications.remove(id); } /** * 更新通知栏进度条 * @param id 获取Notification的id * @param progress 获取的进度 */ public void updataNotification(int id, int progress) { Notification notification = mNotifications.get(id); if (notification != null) { // 修改进度条进度 notification.contentView.setProgressBar(R.id.progressBar2, 100, progress, false); mNotificationManager.notify(id, notification); } } }//*-*/*/*/*-*/
package sjx.bawei.com.download2.service; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.content.Context; import android.content.Intent; import android.util.Log; import sjx.bawei.com.download2.db.ThreadDAO; import sjx.bawei.com.download2.db.ThreadDAOImple; import sjx.bawei.com.download2.entitis.FileInfo; import sjx.bawei.com.download2.entitis.ThreadInfo; public class DownloadTask { private Context mComtext = null; private FileInfo mFileInfo = null; private ThreadDAO mDao = null; private int mFinished = 0; private int mThreadCount = 1; public boolean mIsPause = false; private List<DownloadThread> mThreadlist = null; public static ExecutorService sExecutorService = Executors.newCachedThreadPool(); public DownloadTask(Context comtext, FileInfo fileInfo, int threadCount) { super(); this.mThreadCount = threadCount; this.mComtext = comtext; this.mFileInfo = fileInfo; this.mDao = new ThreadDAOImple(mComtext); } public void download() { List<ThreadInfo> list = mDao.queryThreads(mFileInfo.getUrl()); if (list.size() == 0) { int length = mFileInfo.getLength(); int block = length / mThreadCount; for (int i = 0; i < mThreadCount; i++) { int start = i * block; int end = (i + 1) * block - 1; if (i == mThreadCount - 1) { end = length - 1; } ThreadInfo threadInfo = new ThreadInfo(i, mFileInfo.getUrl(), start, end, 0); list.add(threadInfo); } } mThreadlist = new ArrayList<DownloadThread>(); for (ThreadInfo info : list) { DownloadThread thread = new DownloadThread(info); // thread.start(); DownloadTask.sExecutorService.execute(thread); mThreadlist.add(thread); mDao.insertThread(info); } } public synchronized void checkAllFinished() { boolean allFinished = true; for (DownloadThread thread : mThreadlist) { if (!thread.isFinished) { allFinished = false; break; } } if (allFinished == true) { mDao.deleteThread(mFileInfo.getUrl()); Intent intent = new Intent(DownloadService.ACTION_FINISHED); intent.putExtra("fileInfo", mFileInfo); mComtext.sendBroadcast(intent); } } class DownloadThread extends Thread { private ThreadInfo threadInfo = null; public boolean isFinished = false; public DownloadThread(ThreadInfo threadInfo) { this.threadInfo = threadInfo; } @Override public void run() { HttpURLConnection conn = null; RandomAccessFile raf = null; InputStream is = null; try { URL url = new URL(mFileInfo.getUrl()); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); int start = threadInfo.getStart() + threadInfo.getFinished(); conn.setRequestProperty("Range", "bytes=" + start + "-" + threadInfo.getEnd()); File file = new File(DownloadService.DownloadPath, mFileInfo.getFileName()); raf = new RandomAccessFile(file, "rwd"); raf.seek(start); mFinished += threadInfo.getFinished(); Intent intent = new Intent(); intent.setAction(DownloadService.ACTION_UPDATE); int code = conn.getResponseCode(); if (code == HttpURLConnection.HTTP_PARTIAL) { is = conn.getInputStream(); byte[] bt = new byte[1024]; int len = -1; long time = System.currentTimeMillis(); while ((len = is.read(bt)) != -1) { raf.write(bt, 0, len); mFinished += len; threadInfo.setFinished(threadInfo.getFinished() + len); if (System.currentTimeMillis() - time > 1000) { time = System.currentTimeMillis(); intent.putExtra("finished", mFinished * 100 / mFileInfo.getLength()); intent.putExtra("id", mFileInfo.getId()); Log.i("test", mFinished * 100 / mFileInfo.getLength() + ""); mComtext.sendBroadcast(intent); } if (mIsPause) { mDao.updateThread(threadInfo.getUrl(), threadInfo.getId(), threadInfo.getFinished()); return; } } } isFinished = true; checkAllFinished(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } try { if (is != null) { is.close(); } if (raf != null) { raf.close(); } } catch (IOException e) { e.printStackTrace(); } } super.run(); } } }/*-*-/*-*/*-*/*/*-*-
package sjx.bawei.com.download2.service; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import android.app.Service; import android.content.Intent; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import sjx.bawei.com.download2.entitis.FileInfo; public class DownloadService extends Service { public static final String ACTION_START = "ACTION_START"; public static final String ACTION_STOP = "ACTION_STOP"; public static final String ACTION_UPDATE = "ACTION_UPDATE"; public static final String ACTION_FINISHED = "ACTION_FINISHED"; public static final String DownloadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sjx/"; public static final int MSG_INIT = 0; private Map<Integer, DownloadTask> mTasks = new LinkedHashMap<Integer, DownloadTask>(); @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (ACTION_START.equals(intent.getAction())) { FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); Log.i("test", "START" + fileInfo.toString()); InitThread initThread = new InitThread(fileInfo); DownloadTask.sExecutorService.execute(initThread); } else if (ACTION_STOP.equals(intent.getAction())) { FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); DownloadTask task = mTasks.get(fileInfo.getId()); if (task != null) { task.mIsPause = true; } } return super.onStartCommand(intent, flags, startId); } Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case MSG_INIT: FileInfo fileInfo = (FileInfo) msg.obj; Log.i("test", "INIT:" + fileInfo.toString()); DownloadTask task = new DownloadTask(DownloadService.this, fileInfo, 3); task.download(); mTasks.put(fileInfo.getId(), task); Intent intent = new Intent(ACTION_START); intent.putExtra("fileInfo", fileInfo); sendBroadcast(intent); break; } }; }; class InitThread extends Thread { private FileInfo mFileInfo = null; public InitThread(FileInfo mFileInfo) { super(); this.mFileInfo = mFileInfo; } @Override public void run() { HttpURLConnection conn = null; RandomAccessFile raf = null; try { URL url = new URL(mFileInfo.getUrl()); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); int length = -1; if (code == HttpURLConnection.HTTP_OK) { length = conn.getContentLength(); } if (length <= 0) { return; } File dir = new File(DownloadPath); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, mFileInfo.getFileName()); raf = new RandomAccessFile(file, "rwd"); raf.setLength(length); mFileInfo.setLength(length); Message msg = Message.obtain(); msg.obj = mFileInfo; msg.what = MSG_INIT; mHandler.sendMessage(msg); // msg.setTarget(mHandler); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } try { if (raf != null) { raf.close(); } } catch (IOException e) { e.printStackTrace(); } } super.run(); } } }/*--*/*-*/*/*-*-*/*-*-*-
package sjx.bawei.com.download2.entitis; public class ThreadInfo { private int id; private String url; private int start; private int end; private int finished; public ThreadInfo() { super(); } public ThreadInfo(int id, String url, int start, int end, int finished) { super(); this.id = id; this.url = url; this.start = start; this.end = end; this.finished = finished; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public int getFinished() { return finished; } public void setFinished(int finished) { this.finished = finished; } @Override public String toString() { return "ThreadInfo [id=" + id + ", url=" + url + ", start=" + start + ", end=" + end + ", finished=" + finished + "]"; } }/*-*--*-*/*-*/*-*-*/*-*/*-
package sjx.bawei.com.download2.entitis; import java.io.Serializable; public class FileInfo implements Serializable { private int id; private String url; private String fileName; private int length; private int finished; public FileInfo() { super(); } /** * * @param id �ļ���ID * @param url �ļ������d��ַ * @param fileName �ļ������� * @param length �ļ��Ŀ���С * @param finished �ļ��ѽ�����˶��� */ public FileInfo(int id, String url, String fileName, int length, int finished) { super(); this.id = id; this.url = url; this.fileName = fileName; this.length = length; this.finished = finished; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public int getFinished() { return finished; } public void setFinished(int finished) { this.finished = finished; } @Override public String toString() { return "FileInfo [id=" + id + ", url=" + url + ", fileName=" + fileName + ", length=" + length + ", finished=" + finished + "]"; } }/*-*/*-*/*-*--*/*-*/*--*+
package sjx.bawei.com.download2.db; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import sjx.bawei.com.download2.entitis.ThreadInfo; public class ThreadDAOImple implements ThreadDAO { private DBHelper dbHelper = null; public ThreadDAOImple(Context context) { super(); this.dbHelper = DBHelper.getInstance(context); } // 插入綫程 @Override public synchronized void insertThread(ThreadInfo info) { SQLiteDatabase db = dbHelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("thread_id", info.getId()); values.put("url", info.getUrl()); values.put("start", info.getStart()); values.put("end", info.getEnd()); values.put("finished", info.getFinished()); db.insert("thread_info", null, values); db.close(); } // 刪除綫程 @Override public synchronized void deleteThread(String url) { SQLiteDatabase db = dbHelper.getReadableDatabase(); db.delete("thread_info", "url = ?", new String[] { url}); db.close(); } // 更新綫程 @Override public synchronized void updateThread(String url, int thread_id, int finished) { SQLiteDatabase db = dbHelper.getReadableDatabase(); db.execSQL("update thread_info set finished = ? where url = ? and thread_id = ?", new Object[]{finished, url, thread_id}); db.close(); } // 查詢綫程 @Override public List<ThreadInfo> queryThreads(String url) { SQLiteDatabase db = dbHelper.getReadableDatabase(); List<ThreadInfo> list = new ArrayList<ThreadInfo>(); Cursor cursor = db.query("thread_info", null, "url = ?", new String[] { url }, null, null, null); while (cursor.moveToNext()) { ThreadInfo thread = new ThreadInfo(); thread.setId(cursor.getInt(cursor.getColumnIndex("thread_id"))); thread.setUrl(cursor.getString(cursor.getColumnIndex("url"))); thread.setStart(cursor.getInt(cursor.getColumnIndex("start"))); thread.setEnd(cursor.getInt(cursor.getColumnIndex("end"))); thread.setFinished(cursor.getInt(cursor.getColumnIndex("finished"))); list.add(thread); } cursor.close(); db.close(); return list; } @Override public boolean isExists(String url, int thread_id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query("thread_info", null, "url = ? and thread_id = ?", new String[] { url, thread_id + "" }, null, null, null); boolean exists = cursor.moveToNext(); db.close(); cursor.close(); return exists; } }++++++++++++++++++++++++++++++++++++++
package sjx.bawei.com.download2.db; import java.util.List; import sjx.bawei.com.download2.entitis.ThreadInfo; public interface ThreadDAO { public void insertThread(ThreadInfo info); // 刪除綫程 public void deleteThread(String url); // 更新綫程 public void updateThread(String url, int thread_id, int finished); // 查詢綫程 public List<ThreadInfo> queryThreads(String url); // 判斷綫程是否存在 public boolean isExists(String url, int threadId); }/*-/*-*-*/*-*/*-*/*-*+package sjx.bawei.com.download2.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "download.db"; private static final int VERSION = 1; private static final String SQL_CREATE = "create table thread_info(_id integer primary key autoincrement, " + "thread_id integer, url text, start integer, end integer, finished integer)"; private static final String SQL_DROP = "drop table if exists thread_info"; private static DBHelper sHelper = null; private DBHelper(Context context) { super(context, DB_NAME, null, VERSION); } public static DBHelper getInstance(Context context) { if (sHelper == null) { sHelper = new DBHelper(context); } return sHelper; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DROP); db.execSQL(SQL_CREATE); } }/*/*/*/*/*/*/*/*/*/*/*/*/*/package sjx.bawei.com.download2.adapter; import java.util.List; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import sjx.bawei.com.download2.R; import sjx.bawei.com.download2.entitis.FileInfo; import sjx.bawei.com.download2.service.DownloadService; public class FileAdapter extends BaseAdapter { private Context mContext = null; private List<FileInfo> mFilelist = null; private LayoutInflater layoutInflater; public FileAdapter(Context mContext, List<FileInfo> mFilelist) { super(); this.mContext = mContext; this.mFilelist = mFilelist; layoutInflater = LayoutInflater.from(mContext); } @Override public int getCount() { return mFilelist.size(); } @Override public Object getItem(int position) { return mFilelist.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; final FileInfo mFileInfo = mFilelist.get(position); if(convertView == null) { convertView = layoutInflater.inflate(R.layout.item, null); viewHolder = new ViewHolder(); viewHolder.textview = (TextView) convertView.findViewById(R.id.file_textview); viewHolder.startButton = (Button) convertView.findViewById(R.id.start_button); viewHolder.stopButton = (Button) convertView.findViewById(R.id.stop_button); viewHolder.progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar2); viewHolder.textview.setText(mFileInfo.getFileName()); viewHolder.progressBar.setMax(100); viewHolder.startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(mContext,"asdasd",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(mContext, DownloadService.class); intent.setAction(DownloadService.ACTION_START); intent.putExtra("fileInfo", mFileInfo); mContext.startService(intent); } }); viewHolder.stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, DownloadService.class); intent.setAction(DownloadService.ACTION_STOP); intent.putExtra("fileInfo", mFileInfo); mContext.startService(intent); } }); convertView.setTag(viewHolder); } else{ viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.progressBar.setProgress(mFileInfo.getFinished()); return convertView; } public void updataProgress(int id , int progress) { FileInfo info = mFilelist.get(id); info.setFinished(progress); notifyDataSetChanged(); } static class ViewHolder{ TextView textview; Button startButton; Button stopButton; ProgressBar progressBar; } }/*-*/*-/*-*/*-*/*-*/*-*/*-*-package sjx.bawei.com.download2; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ListView; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; import java.util.ArrayList; import java.util.List; import sjx.bawei.com.download2.adapter.FileAdapter; import sjx.bawei.com.download2.entitis.FileInfo; import sjx.bawei.com.download2.service.DownloadService; import sjx.bawei.com.download2.util.NotificationUtil; public class MainActivity extends AppCompatActivity { private ListView listView; private List<FileInfo> mFileList; private FileAdapter mAdapter; private NotificationUtil mNotificationUtil = null; private String urlone = "http://pic.ibaotu.com/00/34/48/06n888piCANy.mp4_10s.mp4"; // private String urltwo = "http://www.imooc.com/download/Activator.exe"; // private String urlthree = "http://s1.music.126.net/download/android/CloudMusic_3.4.1.133604_official.apk"; // private String urlfour = "http://study.163.com/pub/study-android-official.apk"; private UIRecive mRecive; private VideoView videoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); videoView= (VideoView) findViewById(R.id.ha); // 初始化控件 listView = (ListView) findViewById(R.id.list_view); mFileList = new ArrayList<FileInfo>(); // 初始化文件对象 FileInfo fileInfo1 = new FileInfo(0, urlone, getfileName(urlone), 0, 0); // FileInfo fileInfo2 = new FileInfo(1, urltwo, getfileName(urltwo), 0, 0); // FileInfo fileInfo3 = new FileInfo(2, urlthree, getfileName(urlthree), 0, 0); // FileInfo fileInfo4 = new FileInfo(3, urlfour, getfileName(urlfour), 0, 0); mFileList.add(fileInfo1); // mFileList.add(fileInfo2); // mFileList.add(fileInfo3); // mFileList.add(fileInfo4); mAdapter = new FileAdapter(this, mFileList); listView.setAdapter(mAdapter); mNotificationUtil = new NotificationUtil(MainActivity.this); mRecive = new UIRecive(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(DownloadService.ACTION_UPDATE); intentFilter.addAction(DownloadService.ACTION_FINISHED); intentFilter.addAction(DownloadService.ACTION_START); registerReceiver(mRecive, intentFilter); } @Override protected void onDestroy() { unregisterReceiver(mRecive); super.onDestroy(); } // 從URL地址中獲取文件名,即/後面的字符 private String getfileName(String url) { return url.substring(url.lastIndexOf("/") + 1); } // 從DownloadTadk中獲取廣播信息,更新進度條 class UIRecive extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) { // 更新进度条的时候 int finished = intent.getIntExtra("finished", 0); int id = intent.getIntExtra("id", 0); mAdapter.updataProgress(id, finished); // mNotificationUtil.updataNotification(id, finished); } else if (DownloadService.ACTION_FINISHED.equals(intent.getAction())){ // 下载结束的时候 FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); mAdapter.updataProgress(fileInfo.getId(), 0); Toast.makeText(MainActivity.this, mFileList.get(fileInfo.getId()).getFileName() + "下载完毕", Toast.LENGTH_SHORT).show(); videoView.setVisibility(View.VISIBLE); Uri uri = Uri.parse("storage/emulated/legacy/sjx/"+getfileName(urlone)+""); videoView.setMediaController(new MediaController(MainActivity.this)); videoView.setVideoURI(uri); videoView.start(); videoView.requestFocus(); // 下载结束后取消通知 // mNotificationUtil.cancelNotification(fileInfo.getId()); } else if (DownloadService.ACTION_START.equals(intent.getAction())){ // 下载开始的时候启动通知栏 // mNotificationUtil.showNotification((FileInfo) intent.getSerializableExtra("fileInfo")); } } } }