]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/DictionaryManagerActivity.java
Merge pull request #26 from Kteby/master
[Dictionary.git] / src / com / hughes / android / dictionary / DictionaryManagerActivity.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary;
16
17 import android.app.AlertDialog;
18 import android.app.DownloadManager;
19 import android.app.DownloadManager.Request;
20 import android.content.BroadcastReceiver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.SharedPreferences;
25 import android.content.SharedPreferences.Editor;
26 import android.database.Cursor;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.os.Environment;
30 import android.os.Handler;
31 import android.preference.PreferenceManager;
32 import android.support.v7.app.ActionBar;
33 import android.support.v7.app.ActionBarActivity;
34 import android.support.v7.widget.SearchView;
35 import android.support.v7.widget.SearchView.OnQueryTextListener;
36 import android.util.Log;
37 import android.util.TypedValue;
38 import android.view.ContextMenu;
39 import android.view.ContextMenu.ContextMenuInfo;
40 import android.view.LayoutInflater;
41 import android.view.Menu;
42 import android.view.View;
43 import android.view.View.OnClickListener;
44 import android.view.ViewGroup;
45 import android.view.inputmethod.EditorInfo;
46 import android.widget.AdapterView.AdapterContextMenuInfo;
47 import android.widget.BaseAdapter;
48 import android.widget.Button;
49 import android.widget.CompoundButton;
50 import android.widget.CompoundButton.OnCheckedChangeListener;
51 import android.widget.FrameLayout;
52 import android.widget.LinearLayout;
53 import android.widget.ListAdapter;
54 import android.widget.ListView;
55 import android.widget.TextView;
56 import android.widget.Toast;
57 import android.widget.ToggleButton;
58
59 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
60 import com.hughes.android.util.IntentLauncher;
61
62 import java.io.File;
63 import java.io.FileOutputStream;
64 import java.io.IOException;
65 import java.io.InputStream;
66 import java.io.OutputStream;
67 import java.net.MalformedURLException;
68 import java.net.URL;
69 import java.util.Collections;
70 import java.util.List;
71 import java.util.zip.ZipEntry;
72 import java.util.zip.ZipFile;
73
74 // Right-click:
75 //  Delete, move to top.
76
77 public class DictionaryManagerActivity extends ActionBarActivity {
78
79     static final String LOG = "QuickDic";
80     static boolean blockAutoLaunch = false;
81
82     private ListView listView;
83     private ListView getListView() {
84         if (listView == null) {
85             listView = (ListView)findViewById(android.R.id.list);
86         }
87         return listView;
88     }
89     private void setListAdapter(ListAdapter adapter) {
90         getListView().setAdapter(adapter);
91     }
92     private ListAdapter getListAdapter() {
93         return getListView().getAdapter();
94     }
95
96     DictionaryApplication application;
97
98     SearchView filterSearchView;
99     ToggleButton showDownloadable;
100
101     LinearLayout dictionariesOnDeviceHeaderRow;
102     LinearLayout downloadableDictionariesHeaderRow;
103
104     Handler uiHandler;
105
106     Runnable dictionaryUpdater = new Runnable() {
107         @Override
108         public void run() {
109             if (uiHandler == null) {
110                 return;
111             }
112             uiHandler.post(new Runnable() {
113                 @Override
114                 public void run() {
115                     setMyListAdapater();
116                 }
117             });
118         }
119     };
120
121     final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
122         @Override
123         public void onReceive(Context context, Intent intent) {
124             final String action = intent.getAction();
125
126             if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
127                 final long downloadId = intent.getLongExtra(
128                         DownloadManager.EXTRA_DOWNLOAD_ID, 0);
129                 final DownloadManager.Query query = new DownloadManager.Query();
130                 query.setFilterById(downloadId);
131                 final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
132                 final Cursor cursor = downloadManager.query(query);
133
134                 if (cursor == null || !cursor.moveToFirst()) {
135                     Log.e(LOG, "Couldn't find download.");
136                     return;
137                 }
138
139                 final String dest = cursor
140                         .getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
141                 final int status = cursor
142                         .getInt(cursor
143                                 .getColumnIndex(DownloadManager.COLUMN_STATUS));
144                 if (DownloadManager.STATUS_SUCCESSFUL != status) {
145                     final int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
146                     Log.w(LOG,
147                             "Download failed: status=" + status +
148                                     ", reason=" + reason);
149                     String msg = Integer.toString(reason);
150                     switch (reason) {
151                     case DownloadManager.ERROR_FILE_ALREADY_EXISTS: msg = "File exists"; break;
152                     case DownloadManager.ERROR_FILE_ERROR: msg = "File error"; break;
153                     case DownloadManager.ERROR_INSUFFICIENT_SPACE: msg = "Not enough space"; break;
154                     }
155                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(getString(R.string.downloadFailed, reason)).setNeutralButton("Close", null).show();
156                     return;
157                 }
158
159                 Log.w(LOG, "Download finished: " + dest);
160                 Toast.makeText(context, getString(R.string.unzippingDictionary, dest),
161                         Toast.LENGTH_LONG).show();
162                 
163                 
164                 final File localZipFile = new File(Uri.parse(dest).getPath());
165                 try {
166                     ZipFile zipFile = new ZipFile(localZipFile);
167                     final ZipEntry zipEntry = zipFile.entries().nextElement();
168                     Log.d(LOG, "Unzipping entry: " + zipEntry.getName());
169                     final InputStream zipIn = zipFile.getInputStream(zipEntry);
170                     File targetFile = new File(application.getDictDir(), zipEntry.getName());
171                     if (targetFile.exists()) {
172                         targetFile.renameTo(new File(targetFile.getAbsolutePath().replace(".quickdic", ".bak.quickdic")));
173                         targetFile = new File(application.getDictDir(), zipEntry.getName());
174                     }
175                     final OutputStream zipOut = new FileOutputStream(targetFile);
176                     copyStream(zipIn, zipOut);
177                     zipFile.close();
178                     application.backgroundUpdateDictionaries(dictionaryUpdater);
179                     Toast.makeText(context, getString(R.string.installationFinished, dest),
180                             Toast.LENGTH_LONG).show();
181                 } catch (Exception e) {
182                     String msg = getString(R.string.unzippingFailed, dest);
183                     File dir = application.getDictDir();
184                     if (!dir.canWrite() || !application.checkFileCreate(dir)) {
185                         msg = getString(R.string.notWritable, dir.getAbsolutePath());
186                     }
187                     new AlertDialog.Builder(context).setTitle(getString(R.string.error)).setMessage(msg).setNeutralButton("Close", null).show();
188                     Log.e(LOG, "Failed to unzip.", e);
189                 } finally {
190                     localZipFile.delete();
191                 }
192             }
193         }
194     };
195
196     public static Intent getLaunchIntent(Context c) {
197         final Intent intent = new Intent(c, DictionaryManagerActivity.class);
198         intent.putExtra(C.CAN_AUTO_LAUNCH_DICT, false);
199         return intent;
200     }
201
202     @Override
203     public void onCreate(Bundle savedInstanceState) {
204         // This must be first, otherwise the actiona bar doesn't get
205         // styled properly.
206         setTheme(((DictionaryApplication) getApplication()).getSelectedTheme().themeId);
207
208         super.onCreate(savedInstanceState);
209         Log.d(LOG, "onCreate:" + this);
210
211         application = (DictionaryApplication) getApplication();
212
213         blockAutoLaunch = false;
214
215         // UI init.
216         setContentView(R.layout.dictionary_manager_activity);
217
218         dictionariesOnDeviceHeaderRow = (LinearLayout) LayoutInflater.from(
219                 getListView().getContext()).inflate(
220                 R.layout.dictionary_manager_header_row_on_device, getListView(), false);
221
222         downloadableDictionariesHeaderRow = (LinearLayout) LayoutInflater.from(
223                 getListView().getContext()).inflate(
224                 R.layout.dictionary_manager_header_row_downloadable, getListView(), false);
225
226         showDownloadable = (ToggleButton) downloadableDictionariesHeaderRow
227                 .findViewById(R.id.hideDownloadable);
228         showDownloadable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
229             @Override
230             public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
231                 onShowDownloadableChanged();
232             }
233         });
234
235         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
236         final String thanksForUpdatingLatestVersion = getString(R.string.thanksForUpdatingVersion);
237         if (!prefs.getString(C.THANKS_FOR_UPDATING_VERSION, "").equals(
238                 thanksForUpdatingLatestVersion)) {
239             blockAutoLaunch = true;
240             startActivity(HtmlDisplayActivity.getWhatsNewLaunchIntent(getApplicationContext()));
241             prefs.edit().putString(C.THANKS_FOR_UPDATING_VERSION, thanksForUpdatingLatestVersion)
242                     .commit();
243         }
244
245         registerReceiver(broadcastReceiver, new IntentFilter(
246                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));
247
248         setMyListAdapater();
249         registerForContextMenu(getListView());
250
251         final File dictDir = application.getDictDir();
252         if (!dictDir.canRead() || !dictDir.canExecute()) {
253             blockAutoLaunch = true;
254
255             AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
256             builder.setTitle(getString(R.string.error));
257             builder.setMessage(getString(
258                     R.string.unableToReadDictionaryDir,
259                     dictDir.getAbsolutePath(),
260                     Environment.getExternalStorageDirectory()));
261             builder.setNeutralButton("Close", null);
262             builder.create().show();
263         }
264
265         onCreateSetupActionBar();
266     }
267
268     private void onCreateSetupActionBar() {
269         ActionBar actionBar = getSupportActionBar();
270         actionBar.setDisplayShowTitleEnabled(false);
271
272         filterSearchView = new SearchView(getSupportActionBar().getThemedContext());
273         filterSearchView.setIconifiedByDefault(false);
274         // filterSearchView.setIconified(false); // puts the magnifying glass in
275         // the
276         // wrong place.
277         filterSearchView.setQueryHint(getString(R.string.searchText));
278         filterSearchView.setSubmitButtonEnabled(false);
279         final int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300,
280                 getResources().getDisplayMetrics());
281         FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width,
282                 FrameLayout.LayoutParams.WRAP_CONTENT);
283         filterSearchView.setLayoutParams(lp);
284         filterSearchView.setImeOptions(
285                 EditorInfo.IME_ACTION_SEARCH |
286                         EditorInfo.IME_FLAG_NO_EXTRACT_UI |
287                         EditorInfo.IME_FLAG_NO_ENTER_ACTION |
288                         // EditorInfo.IME_FLAG_NO_FULLSCREEN | // Requires API
289                         // 11
290                         EditorInfo.IME_MASK_ACTION |
291                         EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
292
293         filterSearchView.setOnQueryTextListener(new OnQueryTextListener() {
294             @Override
295             public boolean onQueryTextSubmit(String query) {
296                 return true;
297             }
298
299             @Override
300             public boolean onQueryTextChange(String filterText) {
301                 setMyListAdapater();
302                 return true;
303             }
304         });
305         filterSearchView.setFocusable(true);
306
307         actionBar.setCustomView(filterSearchView);
308         actionBar.setDisplayShowCustomEnabled(true);
309     }
310
311     @Override
312     public void onDestroy() {
313         super.onDestroy();
314         unregisterReceiver(broadcastReceiver);
315     }
316
317     private static int copyStream(final InputStream in, final OutputStream out)
318             throws IOException {
319         int bytesRead;
320         final byte[] bytes = new byte[1024 * 16];
321         while ((bytesRead = in.read(bytes)) != -1) {
322             out.write(bytes, 0, bytesRead);
323         }
324         in.close();
325         out.close();
326         return bytesRead;
327     }
328
329     @Override
330     protected void onStart() {
331         super.onStart();
332         uiHandler = new Handler();
333     }
334
335     @Override
336     protected void onStop() {
337         super.onStop();
338         uiHandler = null;
339     }
340
341     @Override
342     protected void onResume() {
343         super.onResume();
344
345         if (PreferenceActivity.prefsMightHaveChanged) {
346             PreferenceActivity.prefsMightHaveChanged = false;
347             finish();
348             startActivity(getIntent());
349         }
350
351         final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
352         showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));
353
354         if (!blockAutoLaunch &&
355                 getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true) &&
356                 prefs.contains(C.DICT_FILE) &&
357                 prefs.contains(C.INDEX_SHORT_NAME)) {
358             Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
359             startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
360                     new File(prefs.getString(C.DICT_FILE, "")),
361                     prefs.getString(C.INDEX_SHORT_NAME, ""),
362                     prefs.getString(C.SEARCH_TOKEN, "")));
363             finish();
364             return;
365         }
366
367         // Remove the active dictionary from the prefs so we won't autolaunch
368         // next time.
369         final Editor editor = prefs.edit();
370         editor.remove(C.DICT_FILE);
371         editor.remove(C.INDEX_SHORT_NAME);
372         editor.remove(C.SEARCH_TOKEN);
373         editor.commit();
374
375         application.backgroundUpdateDictionaries(dictionaryUpdater);
376
377         setMyListAdapater();
378     }
379
380     @Override
381     public boolean onCreateOptionsMenu(final Menu menu) {
382         application.onCreateGlobalOptionsMenu(this, menu);
383         return true;
384     }
385
386     @Override
387     public void onCreateContextMenu(final ContextMenu menu, final View view,
388             final ContextMenuInfo menuInfo) {
389         super.onCreateContextMenu(menu, view, menuInfo);
390         Log.d(LOG, "onCreateContextMenu, " + menuInfo);
391
392         final AdapterContextMenuInfo adapterContextMenuInfo =
393                 (AdapterContextMenuInfo) menuInfo;
394         final int position = adapterContextMenuInfo.position;
395         final MyListAdapter.Row row = (MyListAdapter.Row) getListAdapter().getItem(position);
396
397         if (row.dictionaryInfo == null) {
398             return;
399         }
400
401         if (position > 0 && row.onDevice) {
402             final android.view.MenuItem moveToTopMenuItem =
403                     menu.add(R.string.moveToTop);
404             moveToTopMenuItem.setOnMenuItemClickListener(new
405                     android.view.MenuItem.OnMenuItemClickListener() {
406                         @Override
407                         public boolean onMenuItemClick(android.view.MenuItem item) {
408                             application.moveDictionaryToTop(row.dictionaryInfo);
409                             setMyListAdapater();
410                             return true;
411                         }
412                     });
413         }
414
415         if (row.onDevice) {
416             final android.view.MenuItem deleteMenuItem = menu.add(R.string.deleteDictionary);
417             deleteMenuItem
418                     .setOnMenuItemClickListener(new android.view.MenuItem.OnMenuItemClickListener() {
419                         @Override
420                         public boolean onMenuItemClick(android.view.MenuItem item) {
421                             application.deleteDictionary(row.dictionaryInfo);
422                             setMyListAdapater();
423                             return true;
424                         }
425                     });
426         }
427     }
428
429     private void onShowDownloadableChanged() {
430         setMyListAdapater();
431         Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
432         prefs.putBoolean(C.SHOW_DOWNLOADABLE, showDownloadable.isChecked());
433         prefs.commit();
434     }
435
436     class MyListAdapter extends BaseAdapter {
437
438         List<DictionaryInfo> dictionariesOnDevice;
439         List<DictionaryInfo> downloadableDictionaries;
440
441         class Row {
442             DictionaryInfo dictionaryInfo;
443             boolean onDevice;
444
445             private Row(DictionaryInfo dictinoaryInfo, boolean onDevice) {
446                 this.dictionaryInfo = dictinoaryInfo;
447                 this.onDevice = onDevice;
448             }
449         }
450
451         private MyListAdapter(final String[] filters) {
452             dictionariesOnDevice = application.getDictionariesOnDevice(filters);
453             if (showDownloadable.isChecked()) {
454                 downloadableDictionaries = application.getDownloadableDictionaries(filters);
455             } else {
456                 downloadableDictionaries = Collections.emptyList();
457             }
458         }
459
460         @Override
461         public int getCount() {
462             return 2 + dictionariesOnDevice.size() + downloadableDictionaries.size();
463         }
464
465         @Override
466         public Row getItem(int position) {
467             if (position == 0) {
468                 return new Row(null, true);
469             }
470             position -= 1;
471
472             if (position < dictionariesOnDevice.size()) {
473                 return new Row(dictionariesOnDevice.get(position), true);
474             }
475             position -= dictionariesOnDevice.size();
476
477             if (position == 0) {
478                 return new Row(null, false);
479             }
480             position -= 1;
481
482             assert position < downloadableDictionaries.size();
483             return new Row(downloadableDictionaries.get(position), false);
484         }
485
486         @Override
487         public long getItemId(int position) {
488             return position;
489         }
490
491         @Override
492         public View getView(int position, View convertView, ViewGroup parent) {
493             if (convertView instanceof LinearLayout &&
494                     convertView != dictionariesOnDeviceHeaderRow &&
495                     convertView != downloadableDictionariesHeaderRow) {
496                 /*
497                  * This is done to try to avoid leaking memory that used to
498                  * happen on Android 4.0.3
499                  */
500                 ((LinearLayout) convertView).removeAllViews();
501             }
502
503             final Row row = getItem(position);
504
505             if (row.onDevice) {
506                 if (row.dictionaryInfo == null) {
507                     return dictionariesOnDeviceHeaderRow;
508                 }
509                 return createDictionaryRow(row.dictionaryInfo, parent, true);
510             }
511
512             if (row.dictionaryInfo == null) {
513                 return downloadableDictionariesHeaderRow;
514             }
515             return createDictionaryRow(row.dictionaryInfo, parent, false);
516         }
517
518     }
519
520     private void setMyListAdapater() {
521         final String filter = filterSearchView == null ? "" : filterSearchView.getQuery()
522                 .toString();
523         final String[] filters = filter.trim().toLowerCase().split("(\\s|-)+");
524         setListAdapter(new MyListAdapter(filters));
525     }
526
527     private View createDictionaryRow(final DictionaryInfo dictionaryInfo,
528             final ViewGroup parent, boolean canLaunch) {
529
530         View row = LayoutInflater.from(parent.getContext()).inflate(
531                 R.layout.dictionary_manager_row, parent, false);
532         final TextView name = (TextView) row.findViewById(R.id.dictionaryName);
533         final TextView details = (TextView) row.findViewById(R.id.dictionaryDetails);
534         name.setText(application.getDictionaryName(dictionaryInfo.uncompressedFilename));
535
536         final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
537         final Button downloadButton = (Button) row.findViewById(R.id.downloadButton);
538         final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
539         boolean broken = false;
540         if (!dictionaryInfo.isValid()) {
541             broken = true;
542             canLaunch = false;
543         }
544         if (downloadable != null && (!canLaunch || updateAvailable)) {
545             downloadButton
546                     .setText(getString(
547                             R.string.downloadButton,
548                             downloadable.zipBytes / 1024.0 / 1024.0));
549             downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
550             downloadButton.setOnClickListener(new OnClickListener() {
551                 @Override
552                 public void onClick(View arg0) {
553                     downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
554                 }
555             });
556         } else {
557             downloadButton.setVisibility(View.INVISIBLE);
558         }
559
560         LinearLayout buttons = (LinearLayout) row.findViewById(R.id.dictionaryLauncherButtons);
561         final List<IndexInfo> sortedIndexInfos = application
562                 .sortedIndexInfos(dictionaryInfo.indexInfos);
563         final StringBuilder builder = new StringBuilder();
564         if (updateAvailable) {
565             builder.append(getString(R.string.updateAvailable));
566         }
567         for (IndexInfo indexInfo : sortedIndexInfos) {
568             final View button = application.createButton(buttons.getContext(), dictionaryInfo,
569                     indexInfo);
570             buttons.addView(button);
571
572             if (canLaunch) {
573                 button.setOnClickListener(
574                         new IntentLauncher(buttons.getContext(),
575                                 DictionaryActivity.getLaunchIntent(getApplicationContext(),
576                                         application.getPath(dictionaryInfo.uncompressedFilename),
577                                         indexInfo.shortName, "")));
578
579             } else {
580                 button.setEnabled(false);
581             }
582             if (builder.length() != 0) {
583                 builder.append("; ");
584             }
585             builder.append(getString(R.string.indexInfo, indexInfo.shortName,
586                     indexInfo.mainTokenCount));
587         }
588         if (downloadable != null || dictionaryInfo != null) {
589             builder.append("; ");
590             builder.append(getString(R.string.downloadButton, (dictionaryInfo != null ? dictionaryInfo.uncompressedBytes : downloadable.uncompressedBytes) / 1024.0 / 1024.0));
591         }
592         if (broken) {
593             name.setText("Broken: " + application.getDictionaryName(dictionaryInfo.uncompressedFilename));
594             builder.append("; Cannot be used, redownload, check hardware/file system");
595             // Allow deleting, but cannot open
596             row.setLongClickable(true);
597         }
598         details.setText(builder.toString());
599
600         if (canLaunch) {
601             row.setClickable(true);
602             row.setOnClickListener(new IntentLauncher(parent.getContext(),
603                     DictionaryActivity.getLaunchIntent(getApplicationContext(),
604                             application.getPath(dictionaryInfo.uncompressedFilename),
605                             dictionaryInfo.indexInfos.get(0).shortName, "")));
606             row.setFocusable(true);
607             row.setLongClickable(true);
608         }
609         row.setBackgroundResource(android.R.drawable.menuitem_background);
610
611         return row;
612     }
613
614     private void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) {
615         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
616         final DownloadManager.Query query = new DownloadManager.Query();
617         query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
618         final Cursor cursor = downloadManager.query(query);
619
620         // Due to a bug, cursor is null instead of empty when
621         // the download manager is disabled.
622         if (cursor == null) {
623             new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error))
624                     .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed))
625                     .setNeutralButton("Close", null).show();
626             return;
627         }
628
629         while (cursor.moveToNext()) {
630             if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI))))
631                 break;
632         }
633         if (!cursor.isAfterLast()) {
634             downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID)));
635             downloadButton
636                     .setText(getString(
637                             R.string.downloadButton,
638                             bytes / 1024.0 / 1024.0));
639             cursor.close();
640             return;
641         }
642         cursor.close();
643         Request request = new Request(
644                 Uri.parse(downloadUrl));
645         try {
646             final String destFile = new File(new URL(downloadUrl).getFile())
647                     .getName();
648             Log.d(LOG, "Downloading to: " + destFile);
649
650             try {
651                 request.setDestinationInExternalFilesDir(getApplicationContext(), null, destFile);
652             } catch (IllegalStateException e) {
653                 request.setDestinationUri(Uri.fromFile(new File(Environment
654                         .getExternalStorageDirectory(), destFile)));
655             }
656         } catch (MalformedURLException e) {
657             throw new RuntimeException(e);
658         }
659         downloadManager.enqueue(request);
660         downloadButton.setText("X");
661     }
662
663 }