Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DownloadResourcesActivity.java « maps « mapswithme « com « src « android - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b227916e5b8d1a54d00f55aba914459440d424f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
package com.mapswithme.maps;

import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mapswithme.maps.MWMActivity.*;
import com.mapswithme.maps.MapStorage.Index;
import com.mapswithme.maps.api.Const;
import com.mapswithme.maps.api.MWMRequest;
import com.mapswithme.maps.base.MapsWithMeBaseActivity;
import com.mapswithme.maps.location.LocationService;
import com.mapswithme.maps.state.SuppotedState;
import com.mapswithme.util.ConnectionState;
import com.mapswithme.util.Utils;
import com.mapswithme.util.statistics.Statistics;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DownloadResourcesActivity extends MapsWithMeBaseActivity
                                       implements LocationService.Listener, MapStorage.Listener
{
  private static final String TAG = "DownloadResourcesActivity";

  // Error codes, should match the same codes in JNI

  private static final int ERR_DOWNLOAD_SUCCESS = 0;
  private static final int ERR_NOT_ENOUGH_MEMORY = -1;
  private static final int ERR_NOT_ENOUGH_FREE_SPACE = -2;
  private static final int ERR_STORAGE_DISCONNECTED = -3;
  private static final int ERR_DOWNLOAD_ERROR = -4;
  private static final int ERR_NO_MORE_FILES = -5;
  private static final int ERR_FILE_IN_PROGRESS = -6;

  private MWMApplication mApplication = null;
  private MapStorage mMapStorage = null;
  private int mSlotId = 0;
  private TextView mMsgView = null;
  private TextView mLocationMsgView = null;
  private ProgressBar mProgress = null;
  private Button mButton = null;
  private CheckBox mDownloadCountryCheckBox = null;
  private LocationService mLocationService = null;
  private Index mCountryIndex = null;

  private MapTask mMapTaskToForward;

  private IntentProcessor[] mIntentProcessors = {
      new GeoIntentProcessor(),
      new HttpGe0IntentProcessor(),
      new Ge0IntentProcessor(),
      new MapsWithMeIntentProcessor()
  };

  private void setDownloadMessage(int bytesToDownload)
  {
    Log.d(TAG, "prepareFilesDownload, bytesToDownload:" + bytesToDownload);

    if (bytesToDownload < 1024 * 1024)
      mMsgView.setText(String.format(getString(R.string.download_resources),
                                     (float)bytesToDownload / 1024,
                                     getString(R.string.kb)));
    else
      mMsgView.setText(String.format(getString(R.string.download_resources,
                                               (float)bytesToDownload / 1024 / 1024,
                                               getString(R.string.mb))));

  }

  private boolean prepareFilesDownload()
  {
    final int bytes = getBytesToDownload();

    // Show map if no any downloading needed.
    if (bytes == 0)
    {
      showMapView();
      return false;
    }

    // Do initialization once.
    if (mMapStorage == null)
      initDownloading();

    if (bytes > 0)
    {
      setDownloadMessage(bytes);

      mProgress.setMax(bytes);
      mProgress.setProgress(0);
    }
    else
    {
      finishFilesDownload(bytes);
    }

    return true;
  }

  private static final int DOWNLOAD = 0;
  private static final int PAUSE = 1;
  private static final int RESUME = 2;
  private static final int TRY_AGAIN = 3;
  private static final int PROCEED_TO_MAP = 4;
  private static final int BTN_COUNT = 5;

  private View.OnClickListener m_btnListeners[] = null;
  private String m_btnNames[] = null;

  private void initDownloading()
  {
    // Get GUI elements and subscribe to map storage (for country downloading).
    mMapStorage = mApplication.getMapStorage();
    mSlotId = mMapStorage.subscribe(this);

    mMsgView = (TextView)findViewById(R.id.download_resources_message);
    mProgress = (ProgressBar)findViewById(R.id.download_resources_progress);
    mButton = (Button)findViewById(R.id.download_resources_button);
    mDownloadCountryCheckBox = (CheckBox)findViewById(R.id.download_country_checkbox);
    mLocationMsgView = (TextView)findViewById(R.id.download_resources_location_message);

    // Initialize button states.
    m_btnListeners = new View.OnClickListener[BTN_COUNT];
    m_btnNames = new String[BTN_COUNT];

    m_btnListeners[DOWNLOAD] = new View.OnClickListener()
    {
      @Override
      public void onClick(View v) { onDownloadClicked(v); }
    };
    m_btnNames[DOWNLOAD] = getString(R.string.download);

    m_btnListeners[PAUSE] = new View.OnClickListener()
    {
      @Override
      public void onClick(View v) { onPauseClicked(v); }
    };
    m_btnNames[PAUSE] = getString(R.string.pause);

    m_btnListeners[RESUME] = new View.OnClickListener()
    {
      @Override
      public void onClick(View v) { onResumeClicked(v); }
    };
    m_btnNames[RESUME] = getString(R.string.continue_download);

    m_btnListeners[TRY_AGAIN] = new View.OnClickListener()
    {
      @Override
      public void onClick(View v) { onTryAgainClicked(v); }
    };
    m_btnNames[TRY_AGAIN] = getString(R.string.try_again);

    m_btnListeners[PROCEED_TO_MAP] = new View.OnClickListener()
    {
      @Override
      public void onClick(View v) { onProceedToMapClicked(v); }
    };
    m_btnNames[PROCEED_TO_MAP] = getString(R.string.download_resources_continue);

    // Start listening the location.
    mLocationService = mApplication.getLocationService();
    mLocationService.startUpdate(this);
  }

  private void setAction(int action)
  {
    mButton.setOnClickListener(m_btnListeners[action]);
    mButton.setText(m_btnNames[action]);
  }

  private void doDownload()
  {
    if (startNextFileDownload(this) == ERR_NO_MORE_FILES)
      finishFilesDownload(ERR_NO_MORE_FILES);
  }

  public void onDownloadClicked(View v)
  {
    setAction(PAUSE);
    doDownload();
  }

  private void onPauseClicked(View v)
  {
    setAction(RESUME);
    cancelCurrentFile();
  }

  private void onResumeClicked(View v)
  {
    setAction(PAUSE);
    doDownload();
  }

  private void onTryAgainClicked(View v)
  {
    // Initialize downloading from the beginning.
    if (prepareFilesDownload())
    {
      setAction(PAUSE);
      doDownload();
    }
  }

  private void onProceedToMapClicked(View v)
  {
    showMapView();
  }

  public String getErrorMessage(int res)
  {
    int id;
    switch (res)
    {
    case ERR_NOT_ENOUGH_FREE_SPACE: id = R.string.not_enough_free_space_on_sdcard; break;
    case ERR_STORAGE_DISCONNECTED: id = R.string.disconnect_usb_cable; break;

    case ERR_DOWNLOAD_ERROR:
      if (ConnectionState.isConnected(this))
        id = R.string.download_has_failed;
      else
        id = R.string.no_internet_connection_detected;
      break;

    default: id = R.string.not_enough_memory;
    }

    return getString(id);
  }

  public void showMapView()
  {
    // Continue with Main UI initialization (MWMActivity)
    Intent mwmActivityIntent = new Intent(this, MWMActivity.class);

    // Disable animation because MWMActivity should appear exactly over this one
    // Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
    mwmActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    //add task to forward
    if (mMapTaskToForward != null)
    {
      mwmActivityIntent.putExtra(MWMActivity.EXTRA_TASK, mMapTaskToForward);
      mMapTaskToForward = null;
    }

    startActivity(mwmActivityIntent);

    finish();
  }

  public void finishFilesDownload(int result)
  {
    if (result == ERR_NO_MORE_FILES)
    {
      if (mCountryIndex != null && mDownloadCountryCheckBox.isChecked())
      {
        mDownloadCountryCheckBox.setVisibility(View.GONE);
        mLocationMsgView.setVisibility(View.GONE);
        mMsgView.setText(String.format(getString(R.string.downloading_country_can_proceed),
                                       mMapStorage.countryName(mCountryIndex)));

        mProgress.setMax((int)mMapStorage.countryRemoteSizeInBytes(mCountryIndex));
        mProgress.setProgress(0);

        mMapStorage.downloadCountry(mCountryIndex);

        setAction(PROCEED_TO_MAP);
      }
      else
        showMapView();
    }
    else
    {
      mMsgView.setText(getErrorMessage(result));
      mMsgView.setTextColor(Color.RED);

      setAction(TRY_AGAIN);
    }
  }

  @Override
  public void onCountryStatusChanged(MapStorage.Index idx)
  {
    final int status = mMapStorage.countryStatus(idx);

    if (status == MapStorage.ON_DISK)
      showMapView();
  }

  @Override
  public void onCountryProgress(MapStorage.Index idx, long current, long total)
  {
    // Important check - activity can be destroyed
    // but notifications from downloading thread are coming.
    if (mProgress != null)
      mProgress.setProgress((int)current);
  }

  private Intent getPackageIntent(String s)
  {
    return getPackageManager().getLaunchIntentForPackage(s);
  }

  private boolean checkLiteProPackages(boolean isPro)
  {
    try
    {
      if (!isPro)
      {
        final Intent intent = getPackageIntent("com.mapswithme.maps.pro");
        if (intent != null)
        {
          Log.i(TAG, "Trying to launch pro version");

          startActivity(intent);
          finish();
          return true;
        }
      }
      else
      {
        if (getPackageIntent("com.mapswithme.maps") != null)
        {
          Toast.makeText(this, R.string.suggest_uninstall_lite, Toast.LENGTH_LONG).show();
        }
      }
    }
    catch (ActivityNotFoundException ex)
    {
      Log.d(TAG, "Intent not found", ex);
    }

    return false;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    // Do not turn off the screen while downloading needed resources
    getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    super.onCreate(savedInstanceState);

    mApplication = (MWMApplication)getApplication();

    final boolean isPro = mApplication.isProVersion();
    if (checkLiteProPackages(isPro))
      return;

    final boolean dispatched = dispatchIntent();
    if (!dispatched)
      parseIntentForKMZFile();

    setContentView(R.layout.download_resources);

    if (prepareFilesDownload())
    {
      setAction(DOWNLOAD);

      if (ConnectionState.getState(this) == ConnectionState.CONNECTED_BY_WIFI)
        onDownloadClicked(mButton);
    }
  }

  private boolean dispatchIntent()
  {
    if (getIntent() != null)
    {
      final Intent intent = getIntent();
      for (IntentProcessor ip : mIntentProcessors)
      {
        if (ip.isIntentSupported(intent))
        {
          ip.processIntent(intent);
          return true;
        }
      }
    }
    return false;
  }

  private String getExtensionFromMime(String mime)
  {
    final int i = mime.lastIndexOf('.');
    if (i == -1)
      return null;

    mime = mime.substring(i+1);
    if (mime.equalsIgnoreCase("kmz"))
      return ".kmz";
    else if (mime.equalsIgnoreCase("kml+xml"))
      return ".kml";
    else
      return null;
  }

  private void parseIntentForKMZFile()
  {
    final Intent intent = getIntent();
    if (intent != null)
    {
      final Uri data = intent.getData();
      if (data != null)
      {
        String path = null;
        File tmpFile = null;
        if (!data.getScheme().equalsIgnoreCase("file"))
        {
          // scheme is "content" or "http" - need to download file first
          InputStream input = null;
          OutputStream output = null;

          try
          {
            final ContentResolver resolver = getContentResolver();
            final String ext = getExtensionFromMime(resolver.getType(data));
            if (ext != null)
            {
              final String filePath = mApplication.getTempPath() + "Attachment" + ext;

              tmpFile = new File(filePath);
              output = new FileOutputStream(tmpFile);
              input = resolver.openInputStream(data);

              byte buffer[] = new byte[512 * 1024];
              int read;
              while ((read = input.read(buffer)) != -1)
                output.write(buffer, 0, read);
              output.flush();

              path = filePath;
            }
          }
          catch (Exception ex)
          {
            Log.w(TAG, "Attachment not found or io error: " + ex);
          }
          finally
          {
            try
            {
              if (input != null)
                input.close();
              if (output != null)
                output.close();
            }
            catch (IOException ex)
            {
              Log.w(TAG, "Close stream error: " + ex);
            }
          }
        }
        else
          path = data.getPath();

        boolean success = false;
        if (path != null)
        {
          Log.d(TAG, "Loading bookmarks file from: " + path);
          success = loadKMZFile(path);
        }
        else
          Log.w(TAG, "Can't get bookmarks file from URI: " + data.getPath());

        if (tmpFile != null)
          tmpFile.delete();

        Utils.toastShortcut(this, success ? R.string.load_kmz_successful : R.string.load_kmz_failed);
      }
    }
  }

  @Override
  protected void onDestroy()
  {
    super.onDestroy();

    if (mLocationService != null)
    {
      mLocationService.stopUpdate(this);
      mLocationService = null;
    }

    if (mMapStorage != null)
      mMapStorage.unsubscribe(mSlotId);
  }

  @Override
  protected void onPause()
  {
    super.onPause();

    if (mLocationService != null)
      mLocationService.stopUpdate(this);
  }

  @Override
  protected void onResume()
  {
    super.onResume();

    if (mLocationService != null)
      mLocationService.startUpdate(this);
  }

  public void onDownloadProgress(int currentTotal, int currentProgress, int globalTotal, int globalProgress)
  {
    if (mProgress != null)
      mProgress.setProgress(globalProgress);
  }

  public void onDownloadFinished(int errorCode)
  {
    if (errorCode == ERR_DOWNLOAD_SUCCESS)
    {
      int res = startNextFileDownload(this);
      if (res == ERR_NO_MORE_FILES)
        finishFilesDownload(res);
    }
    else
      finishFilesDownload(errorCode);
  }

  @Override
  public void onLocationUpdated(final Location l)
  {
    if (mCountryIndex == null)
    {
      final double lat = l.getLatitude();
      final double lon = l.getLongitude();
      Log.i(TAG, "Searching for country name at location lat=" + lat + ", lon=" + lon);

      mCountryIndex = findIndexByPos(lat, lon);
      if (mCountryIndex != null)
      {
        mLocationMsgView.setVisibility(View.VISIBLE);

        final int countryStatus = mMapStorage.countryStatus(mCountryIndex);
        final String name = mMapStorage.countryName(mCountryIndex);

        if (countryStatus == MapStorage.ON_DISK)
          mLocationMsgView.setText(String.format(getString(R.string.download_location_map_up_to_date), name));
        else
        {
          CheckBox checkBox = (CheckBox)findViewById(R.id.download_country_checkbox);
          checkBox.setVisibility(View.VISIBLE);

          String msgViewText;
          String checkBoxText;

          if (countryStatus == MapStorage.ON_DISK_OUT_OF_DATE)
          {
            msgViewText = getString(R.string.download_location_update_map_proposal);
            checkBoxText = String.format(getString(R.string.update_country_ask), name);
          }
          else
          {
            msgViewText = getString(R.string.download_location_map_proposal);
            checkBoxText = String.format(getString(R.string.download_country_ask), name);
          }

          mLocationMsgView.setText(msgViewText);
          checkBox.setText(checkBoxText);
        }

        mLocationService.stopUpdate(this);
        mLocationService = null;
      }
    }
  }

  @Override
  public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy)
  {
  }

  @Override
  public void onLocationError(int errorCode)
  {
  }

  private class GeoIntentProcessor implements IntentProcessor
  {
    @Override
    public boolean isIntentSupported(Intent intent)
    {
      return "geo".equals(intent.getScheme());
    }

    @Override
    public boolean processIntent(Intent intent)
    {
      mMapTaskToForward = new OpenUrlTask(intent.getData().toString());
      return true;
    }
  }

  private class Ge0IntentProcessor implements IntentProcessor
  {
    @Override
    public boolean isIntentSupported(Intent intent)
    {
      return "ge0".equals(intent.getScheme());
    }

    @Override
    public boolean processIntent(Intent intent)
    {
      mMapTaskToForward = new OpenUrlTask(intent.getData().toString());
      return true;
    }
  }

  private class HttpGe0IntentProcessor implements IntentProcessor
  {
    @Override
    public boolean isIntentSupported(Intent intent)
    {
      if ("http".equalsIgnoreCase(intent.getScheme()) && "ge0.me".equals(intent.getData().getHost()))
        return true;
      else
        return false;
    }

    @Override
    public boolean processIntent(Intent intent)
    {
      final Uri data = intent.getData();
      if (data != null)
      {
        final String ge0Url = "ge0:/" + data.getPath();
        mMapTaskToForward = new OpenUrlTask(ge0Url);
        return true;
      }
      else
        return false;
    }
  }

  /**
   * Use this to invoke API task.
   */
  private class MapsWithMeIntentProcessor implements IntentProcessor
  {
    @Override
    public boolean isIntentSupported(Intent intent)
    {
      return Const.ACTION_MWM_REQUEST.equals(intent.getAction());
    }

    @Override
    public boolean processIntent(final Intent intent)
    {
      final String apiUrl = intent.getStringExtra(Const.EXTRA_URL);
      if (apiUrl != null)
      {
        final MWMRequest request = MWMRequest.extractFromIntent(intent, getApplicationContext());
        MWMRequest.setCurrentRequest(request);
        Statistics.INSTANCE.trackApiCall(request);
        getMwmApplication().getAppStateManager().transitionTo(SuppotedState.API_REQUEST);

        mMapTaskToForward = new OpenUrlTask(apiUrl);
        return true;
      }
      return false;
    }
  }

  private native int getBytesToDownload();
  private native boolean isWorldExists(String path);
  private native int startNextFileDownload(Object observer);
  private native Index findIndexByPos(double lat, double lon);
  private native void cancelCurrentFile();
  private native boolean loadKMZFile(String path);
}