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