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

MWMActivity.java « maps « mapswithme « com « src « android - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9fab4f544ffcaf07055bf35184bfbb6fe376d57b (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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
package com.mapswithme.maps;

import java.io.Serializable;
import java.util.Locale;
import java.util.Stack;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mapswithme.maps.Framework.OnBalloonListener;
import com.mapswithme.maps.api.MWMRequest;
import com.mapswithme.maps.bookmarks.BookmarkCategoriesActivity;
import com.mapswithme.maps.location.LocationService;
import com.mapswithme.maps.promo.ActivationSettings;
import com.mapswithme.maps.promo.PromocodeActivationDialog;
import com.mapswithme.maps.settings.UnitLocale;
import com.mapswithme.maps.state.SuppotedState;
import com.mapswithme.util.ConnectionState;
import com.mapswithme.util.Utils;
import com.nvidia.devtech.NvEventQueueActivity;

public class MWMActivity extends NvEventQueueActivity implements LocationService.Listener, OnBalloonListener
{
  public static final String EXTRA_TASK = "map_task";

  private static final int PRO_VERSION_DIALOG = 110001;
  private static final String PRO_VERSION_DIALOG_MSG = "pro_version_dialog_msg";
  private static final int PROMO_DIALOG = 110002;
  //VideoTimer m_timer;

  private static String TAG = "MWMActivity";

  private MWMApplication mApplication = null;
  private BroadcastReceiver m_externalStorageReceiver = null;
  private AlertDialog m_storageDisconnectedDialog = null;

  private ImageButton mMyPositionButton;
  private SurfaceView mMapSurface;
  // for API
  private View mTitleBar;
  private ImageView mAppIcon;
  private TextView mAppTitle;
  // Map tasks that we run AFTER rendering initialized
  private Stack<MapTask> mTasks = new Stack<MWMActivity.MapTask>();



  //showDialog(int, Bundle) available only form API 8
  private String mProDialogMessage;

  private native void deactivatePopup();

  private LocationService getLocationService()
  {
    return mApplication.getLocationService();
  }

  private MapStorage getMapStorage()
  {
    return mApplication.getMapStorage();
  }

  private LocationState getLocationState()
  {
    return mApplication.getLocationState();
  }

  private void startLocation()
  {
    getLocationState().onStartLocation();
    resumeLocation();
  }

  private void stopLocation()
  {
    getLocationState().onStopLocation();
    pauseLocation();
  }

  private void pauseLocation()
  {
    getLocationService().stopUpdate(this);
    // Enable automatic turning screen off while app is idle
    Utils.automaticIdleScreen(true, getWindow());
  }

  private void resumeLocation()
  {
    getLocationService().startUpdate(this);
    // Do not turn off the screen while displaying position
    Utils.automaticIdleScreen(false, getWindow());
  }

  public void checkShouldResumeLocationService()
  {
    ImageButton v = mMyPositionButton;
    if (v != null)
    {
      final LocationState state = getLocationState();
      final boolean hasPosition = state.hasPosition();

      // check if we need to start location observing
      int resID = 0;
      if (hasPosition)
        resID = R.drawable.myposition_button_found;
      else if (state.isFirstPosition())
        resID = R.drawable.myposition_button_normal;

      if (resID != 0)
      {
        if (hasPosition && (state.getCompassProcessMode() == LocationState.COMPASS_FOLLOW))
        {
          state.startCompassFollowing();

          v.setImageResource(R.drawable.myposition_button_follow);
        }
        else
          v.setImageResource(resID);

        v.setSelected(true);

        // start observing in the end (button state can changed here from normal to found).
        resumeLocation();
      }
      else
      {
        v.setImageResource(R.drawable.myposition_button_normal);
        v.setSelected(false);
      }
    }
  }

  public void OnDownloadCountryClicked()
  {
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        nativeDownloadCountry();
      }
    });
  }

  @Override
  public void OnRenderingInitialized()
  {
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        // Run all checks in main thread after rendering is initialized.
        checkMeasurementSystem();
        checkUpdateMaps();
        checkFacebookDialog();
        checkBuyProDialog();
      }
    });

    // Task are not UI-thread bounded,
    // if any task need UI-thread it should implicitly
    // use Activity.runOnUiThread().
    while (!mTasks.isEmpty())
      mTasks.pop().run(this);
  }

  private Activity getActivity() { return this; }

  @Override
  public void ReportUnsupported()
  {
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        new AlertDialog.Builder(getActivity())
        .setMessage(getString(R.string.unsupported_phone))
        .setCancelable(false)
        .setPositiveButton(getString(R.string.close), new DialogInterface.OnClickListener()
        {
          @Override
          public void onClick(DialogInterface dlg, int which)
          {
            getActivity().moveTaskToBack(true);
            dlg.dismiss();
          }
        })
        .create()
        .show();
      }
    });
  }

  private void checkMeasurementSystem()
  {
    UnitLocale.initializeCurrentUnits();
  }

  private native void nativeScale(double k);

  public void onPlusClicked(View v)
  {
    nativeScale(3.0 / 2);
  }

  public void onMinusClicked(View v)
  {
    nativeScale(2.0 / 3);
  }

  public void onBookmarksClicked(View v)
  {
    if (!mApplication.isProVersion())
    {
      showProVersionBanner(getString(R.string.bookmarks_in_pro_version));
    }
    else
    {
      startActivity(new Intent(this, BookmarkCategoriesActivity.class));
    }
  }

  public void onMyPositionClicked(View v)
  {
    final LocationState state = mApplication.getLocationState();
    ImageView vImage = (ImageView)v;
    if (!state.hasPosition())
    {
      if (!state.isFirstPosition())
      {
        // If first time pressed - start location observing:

        // Set the button state to "searching" first ...
        vImage.setImageResource(R.drawable.myposition_button_normal);
        vImage.setSelected(true);

        // ... and then call startLocation, as there could be my_position button
        // state changes in the startLocation.
        startLocation();
        return;
      }
    }
    else
    {
      if (!state.isCentered())
      {
        state.animateToPositionAndEnqueueLocationProcessMode(LocationState.LOCATION_CENTER_ONLY);
        vImage.setSelected(true);
        return;
      }
      else
        if (mApplication.isProVersion())
        {
          // Check if we need to start compass following.
          if (state.hasCompass())
          {
            if (state.getCompassProcessMode() != LocationState.COMPASS_FOLLOW)
            {
              state.startCompassFollowing();

              vImage.setImageResource(R.drawable.myposition_button_follow);
              vImage.setSelected(true);
              return;
            }
            else
              state.stopCompassFollowingAndRotateMap();
          }
        }
    }

    // Turn off location search:

    // Stop location observing first ...
    stopLocation();

    // ... and then set button state to default.
    vImage.setImageResource(R.drawable.myposition_button_normal);
    vImage.setSelected(false);
  }

  private boolean m_needCheckUpdate = true;


  private void checkUpdateMaps()
  {
    // do it only once
    if (m_needCheckUpdate)
    {
      m_needCheckUpdate = false;

      getMapStorage().updateMaps(R.string.advise_update_maps, this, new MapStorage.UpdateFunctor()
      {
        @Override
        public void doUpdate()
        {
          runDownloadActivity();
        }
        @Override
        public void doCancel()
        {
        }
      });
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig)
  {
    super.onConfigurationChanged(newConfig);
    alignZoomButtons();
  }

  private void showDialogImpl(final int dlgID, int resMsg, DialogInterface.OnClickListener okListener)
  {
    new AlertDialog.Builder(this)
    .setCancelable(false)
    .setMessage(getString(resMsg))
    .setPositiveButton(getString(R.string.ok), okListener)
    .setNeutralButton(getString(R.string.never), new DialogInterface.OnClickListener()
    {
      @Override
      public void onClick(DialogInterface dlg, int which)
      {
        dlg.dismiss();
        mApplication.submitDialogResult(dlgID, MWMApplication.NEVER);
      }
    })
    .setNegativeButton(getString(R.string.later), new DialogInterface.OnClickListener()
    {
      @Override
      public void onClick(DialogInterface dlg, int which)
      {
        dlg.dismiss();
        mApplication.submitDialogResult(dlgID, MWMApplication.LATER);
      }
    })
    .create()
    .show();
  }

  private void showFacebookPage()
  {
    try
    {
      // Trying to find package with installed Facebook application.
      // Exception is thrown if we don't have one.
      getPackageManager().getPackageInfo("com.facebook.katana", 0);

      // Profile id is taken from http://graph.facebook.com/MapsWithMe
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/111923085594432")));
    }
    catch (Exception e)
    {
      // Show Facebook page in browser.
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com/MapsWithMe")));
    }
  }

  private boolean isChinaISO(String iso)
  {
    String arr[] = { "CN", "CHN", "HK", "HKG", "MO", "MAC" };
    for (String s : arr)
      if (iso.equalsIgnoreCase(s))
        return true;
    return false;
  }

  private boolean isChinaRegion()
  {
    final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    if (tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA)
    {
      final String iso = tm.getNetworkCountryIso();
      Log.i(TAG, "TelephonyManager country ISO = " + iso);
      if (isChinaISO(iso))
        return true;
    }
    else
    {
      final Location l = mApplication.getLocationService().getLastKnown();
      if (l != null && nativeIsInChina(l.getLatitude(), l.getLongitude()))
        return true;
      else
      {
        final String code = Locale.getDefault().getCountry();
        Log.i(TAG, "Locale country ISO = " + code);
        if (isChinaISO(code))
          return true;
      }
    }

    return false;
  }

  private void checkFacebookDialog()
  {
    if ((ConnectionState.getState(this) != ConnectionState.NOT_CONNECTED) &&
        mApplication.shouldShowDialog(MWMApplication.FACEBOOK) &&
        !isChinaRegion())
    {
      showDialogImpl(MWMApplication.FACEBOOK, R.string.share_on_facebook_text,
                     new DialogInterface.OnClickListener()
      {
        @Override
        public void onClick(DialogInterface dlg, int which)
        {
          mApplication.submitDialogResult(MWMApplication.FACEBOOK, MWMApplication.OK);

          dlg.dismiss();
          showFacebookPage();
        }
      });
    }
  }

  private void showProVersionBanner(final String message)
  {
    mProDialogMessage = message;
    runOnUiThread(new Runnable()
    {

      @SuppressWarnings("deprecation")
      @Override
      public void run()
      {
        showDialog(PRO_VERSION_DIALOG);
      }
    });
  }

  private void runProVersionMarketActivity()
  {
    try
    {
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mApplication.getProVersionURL())));
    }
    catch (Exception e1)
    {
      try
      {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mApplication.getDefaultProVersionURL())));
      }
      catch (Exception e2)
      {
        /// @todo Probably we should show some alert toast here?
        Log.w(TAG, "Can't run activity" + e2);
      }
    }
  }

  private void checkBuyProDialog()
  {
    if (!mApplication.isProVersion() &&
        (ConnectionState.getState(this) != ConnectionState.NOT_CONNECTED) &&
        mApplication.shouldShowDialog(MWMApplication.BUYPRO))
    {
      showDialogImpl(MWMApplication.BUYPRO, R.string.pro_version_available,
                     new DialogInterface.OnClickListener()
      {
        @Override
        public void onClick(DialogInterface dlg, int which)
        {
          mApplication.submitDialogResult(MWMApplication.BUYPRO, MWMApplication.OK);
          dlg.dismiss();
          runProVersionMarketActivity();
        }
      });
    }
  }

  private void runSearchActivity()
  {
    startActivity(new Intent(this, SearchActivity.class));
  }

  public void onSearchClicked(View v)
  {
    if (!(mApplication.isProVersion() || ActivationSettings.isSearchActivated(this)))
    {
      showProVersionBanner(getString(R.string.search_available_in_pro_version));
    }
    else
    {
      if (!getMapStorage().updateMaps(R.string.search_update_maps, this, new MapStorage.UpdateFunctor()
      {
        @Override
        public void doUpdate()
        {
          runDownloadActivity();
        }
        @Override
        public void doCancel()
        {
          runSearchActivity();
        }
      }))
      {
        runSearchActivity();
      }
    }
  }

  @Override
  public boolean onSearchRequested()
  {
    onSearchClicked(null);
    return false;
  }

  private void runDownloadActivity()
  {
    startActivity(new Intent(this, DownloadUI.class));
  }

  public void onDownloadClicked(View v)
  {
    runDownloadActivity();
  }

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    // Use full-screen on Kindle Fire only
    if (Utils.isAmazonDevice())
    {
      getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
      getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
    }

    super.onCreate(savedInstanceState);
    mApplication = (MWMApplication)getApplication();

    // Do not turn off the screen while benchmarking
    if (mApplication.nativeIsBenchmarking())
      getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    nativeConnectDownloadButton();

    //set up view
    mMyPositionButton = (ImageButton) findViewById(R.id.map_button_myposition);
    mTitleBar = findViewById(R.id.title_bar);
    mAppIcon = (ImageView) findViewById(R.id.app_icon);
    mAppTitle = (TextView) findViewById(R.id.app_title);
    mMapSurface = (SurfaceView) findViewById(R.id.map_surfaceview);

    alignZoomButtons();

    Framework.connectBalloonListeners(this);

    Intent intent = getIntent();
    // We need check for tasks both in onCreate and onNewIntent
    // because of bug in OS: https://code.google.com/p/android/issues/detail?id=38629
    addTask(intent);
  }

  @Override
  public void onDestroy()
  {
    Framework.clearBalloonListeners();

    super.onDestroy();
  }

  @Override
  protected void onNewIntent(Intent intent)
  {
    super.onNewIntent(intent);
    addTask(intent);
  }

  private void addTask(Intent intent)
  {
    if (intent != null
        && intent.hasExtra(EXTRA_TASK)
        && ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0))
    {
      MapTask mapTask = (MapTask) intent.getSerializableExtra(EXTRA_TASK);
      mTasks.add(mapTask);
      intent.removeExtra(EXTRA_TASK);
    }
    setIntent(null);
  }

  @Override
  protected void onStop()
  {
    deactivatePopup();
    super.onStop();
  }

  private void alignZoomButtons()
  {
    // Get screen density
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    final double k = metrics.density;
    final int offs = (int)(53 * k); // height of button + half space between buttons.
    final int margin = (int)(5 * k);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                                                 LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(margin, (metrics.heightPixels / 4) - offs, margin, margin);
    findViewById(R.id.map_button_plus).setLayoutParams(lp);
  }

  /// @name From Location interface
  //@{
  @Override
  public void onLocationError(int errorCode)
  {
    nativeOnLocationError(errorCode);

    // Notify user about turned off location services
    if (errorCode == LocationService.ERROR_DENIED)
    {
      getLocationState().turnOff();

      // Do not show this dialog on Kindle Fire - it doesn't have location services
      // and even wifi settings can't be opened programmatically
      if (!Utils.isAmazonDevice())
      {
        new AlertDialog.Builder(this).setTitle(R.string.location_is_disabled_long_text)
        .setPositiveButton(R.string.connection_settings, new DialogInterface.OnClickListener()
        {
          @Override
          public void onClick(DialogInterface dialog, int which)
          {
            try
            {
              startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
            catch (Exception e1)
            {
              // On older Android devices location settings are merged with security
              try
              {
                startActivity(new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS));
              }
              catch (Exception e2)
              {
                Log.w(TAG, "Can't run activity" + e2);
              }
            }

            dialog.dismiss();
          }
        })
        .setNegativeButton(R.string.close, new DialogInterface.OnClickListener()
        {
          @Override
          public void onClick(DialogInterface dialog, int which)
          {
            dialog.dismiss();
          }
        })
        .create()
        .show();
      }
    }
    else if (errorCode == LocationService.ERROR_GPS_OFF)
    {
      Toast.makeText(this, R.string.gps_is_disabled_long_text, Toast.LENGTH_LONG).show();
    }
  }

  public void onCompassStatusChanged(int newStatus)
  {

    if (newStatus == 1)
    {
      mMyPositionButton.setImageResource(R.drawable.myposition_button_follow);
    }
    else
    {
      if (getLocationState().hasPosition())
        mMyPositionButton.setImageResource(R.drawable.myposition_button_found);
      else
        mMyPositionButton.setImageResource(R.drawable.myposition_button_normal);
    }

    mMyPositionButton.setSelected(true);
  }

  public void OnCompassStatusChanged(int newStatus)
  {
    final int val = newStatus;
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        onCompassStatusChanged(val);
      }
    });
  }

  @Override
  public void onLocationUpdated(final Location l)
  {
    if (getLocationState().isFirstPosition())
    {

      mMyPositionButton.setImageResource(R.drawable.myposition_button_found);
      mMyPositionButton.setSelected(true);
    }

    nativeLocationUpdated(l.getTime(), l.getLatitude(), l.getLongitude(), l.getAccuracy(), l.getAltitude(), l.getSpeed(), l.getBearing());
  }

  @Override
  public void onCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy)
  {
    double angles[] = { magneticNorth, trueNorth };
    getLocationService().correctCompassAngles(getWindowManager().getDefaultDisplay(), angles);
    nativeCompassUpdated(time, angles[0], angles[1], accuracy);
  }
  //@}

  private int m_compassStatusListenerID = -1;

  private void startWatchingCompassStatusUpdate()
  {
    m_compassStatusListenerID = mApplication.getLocationState().addCompassStatusListener(this);
  }

  private void stopWatchingCompassStatusUpdate()
  {
    mApplication.getLocationState().removeCompassStatusListener(m_compassStatusListenerID);
  }

  @Override
  protected void onPause()
  {
    pauseLocation();

    stopWatchingExternalStorage();

    stopWatchingCompassStatusUpdate();

    super.onPause();
  }

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

    checkShouldResumeLocationService();

    startWatchingCompassStatusUpdate();

    startWatchingExternalStorage();
  }

  @Override
  public void setViewFromState(SuppotedState state)
  {
    final LayoutParams mapLp = mMapSurface.getLayoutParams();
    int marginTopForMap = 0;

    if (state == SuppotedState.API_REQUEST && MWMRequest.hasRequest())
    {
      // show title
      mTitleBar.findViewById(R.id.up_block).setOnClickListener(new OnClickListener()
      {
        @Override
        public void onClick(View v)
        {
          onBackPressed();
        }
      });

      final MWMRequest request = MWMRequest.getCurrentRequest();
      if (request.hasTitle())
        mAppTitle.setText(request.getTitle());
      else
        mAppTitle.setText(request.getCallerName(this));

      mAppIcon.setImageDrawable(request.getIcon(this));
      mTitleBar.setVisibility(View.VISIBLE);

      marginTopForMap = (int) getResources().getDimension(R.dimen.abs__action_bar_default_height);
    }
    else
    {
      // hide title
      mTitleBar.setVisibility(View.GONE);
    }
    //we use <merge> so we not sure of type here
    if (mapLp instanceof MarginLayoutParams)
      ((MarginLayoutParams)mapLp).setMargins(0, marginTopForMap, 0, 0);
  }

  @Override
  public void onBackPressed()
  {
    if (getState() == SuppotedState.API_REQUEST)
      getMwmApplication().getAppStateManager().transitionTo(SuppotedState.DEFAULT_MAP);

    super.onBackPressed();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    return ContextMenu.onCreateOptionsMenu(this, menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    if (ContextMenu.onOptionsItemSelected(this, item))
      return true;
    else
      return super.onOptionsItemSelected(item);
  }

  // Initialized to invalid combination to force update on the first check
  private boolean m_storageAvailable = false;
  private boolean m_storageWriteable = true;

  private void updateExternalStorageState()
  {
    boolean available, writeable;
    final String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state))
    {
      available = writeable = true;
    }
    else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
    {
      available = true;
      writeable = false;
    }
    else
      available = writeable = false;

    if (m_storageAvailable != available || m_storageWriteable != writeable)
    {
      m_storageAvailable = available;
      m_storageWriteable = writeable;
      handleExternalStorageState(available, writeable);
    }
  }

  private void handleExternalStorageState(boolean available, boolean writeable)
  {
    if (available && writeable)
    {
      // Add local maps to the model
      nativeStorageConnected();

      // enable downloader button and dismiss blocking popup
      findViewById(R.id.map_button_download).setVisibility(View.VISIBLE);
      if (m_storageDisconnectedDialog != null)
        m_storageDisconnectedDialog.dismiss();
    }
    else if (available)
    {
      // Add local maps to the model
      nativeStorageConnected();

      // disable downloader button and dismiss blocking popup
      findViewById(R.id.map_button_download).setVisibility(View.INVISIBLE);
      if (m_storageDisconnectedDialog != null)
        m_storageDisconnectedDialog.dismiss();
    }
    else
    {
      // Remove local maps from the model
      nativeStorageDisconnected();

      // enable downloader button and show blocking popup
      findViewById(R.id.map_button_download).setVisibility(View.VISIBLE);
      if (m_storageDisconnectedDialog == null)
      {
        m_storageDisconnectedDialog = new AlertDialog.Builder(this)
        .setTitle(R.string.external_storage_is_not_available)
        .setMessage(getString(R.string.disconnect_usb_cable))
        .setCancelable(false)
        .create();
      }
      m_storageDisconnectedDialog.show();
    }
  }

  private boolean isActivityPaused()
  {
    // This receiver is null only when activity is paused (see onPause, onResume).
    return (m_externalStorageReceiver == null);
  }

  private void startWatchingExternalStorage()
  {
    m_externalStorageReceiver = new BroadcastReceiver()
    {
      @Override
      public void onReceive(Context context, Intent intent)
      {
        updateExternalStorageState();
      }
    };

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(Intent.ACTION_MEDIA_EJECT);
    filter.addAction(Intent.ACTION_MEDIA_SHARED);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
    filter.addAction(Intent.ACTION_MEDIA_CHECKING);
    filter.addAction(Intent.ACTION_MEDIA_NOFS);
    filter.addDataScheme("file");
    registerReceiver(m_externalStorageReceiver, filter);

    updateExternalStorageState();
  }

  @Override
  @Deprecated
  protected void onPrepareDialog(int id, Dialog dialog, Bundle args)
  {
    if (id == PRO_VERSION_DIALOG)
    {
      ((AlertDialog)dialog).setMessage(mProDialogMessage);
    }
    else
    {
      super.onPrepareDialog(id, dialog, args);
    }
  }

  @Override
  @Deprecated
  protected Dialog onCreateDialog(int id)
  {
    if (id == PRO_VERSION_DIALOG)
    {
      return new AlertDialog.Builder(getActivity())
      .setMessage("")
      .setPositiveButton(getString(R.string.get_it_now), new DialogInterface.OnClickListener()
      {
        @Override
        public void onClick(DialogInterface dlg, int which)
        {
          dlg.dismiss();
          runProVersionMarketActivity();
        }
      })
      .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
      {
        @Override
        public void onClick(DialogInterface dlg, int which)
        {
          dlg.dismiss();
        }
      })
      .setOnKeyListener(new OnKeyListener()
      {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
        {
          if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP)
          {
            if (ActivationSettings.isSearchActivated(getApplicationContext()))
              return false;

            showDialog(PROMO_DIALOG);
            dismissDialog(PRO_VERSION_DIALOG);
            return true;
          }
          return false;
        }
      })
      .create();
    }
    else if (id == PROMO_DIALOG)
      return new PromocodeActivationDialog(this);
    else
      return super.onCreateDialog(id);
  }

  private void stopWatchingExternalStorage()
  {
    if (m_externalStorageReceiver != null)
    {
      unregisterReceiver(m_externalStorageReceiver);
      m_externalStorageReceiver = null;
    }
  }

  ////
  //    Map TASKS
  ////

  public interface MapTask extends Serializable
  {
    public boolean run(MWMActivity target);
  }

  public static class OpenUrlTask implements MapTask
  {
    private static final long serialVersionUID = 1L;
    private final String mUrl;

    public OpenUrlTask(String url)
    {
      Utils.checkNotNull(url);
      mUrl = url;
    }

    @Override
    public boolean run(MWMActivity target)
    {
      return target.setViewPortByUrl(mUrl);
    }
  }


  ////
  //   NATIVE callbacks and methods
  ////

  @Override
  public void onApiPointActivated(final double lat, final double lon, final String name, final String id)
  {
    if (MWMRequest.hasRequest())
      MWMRequest.getCurrentRequest().setPointData(lat, lon, name, id);
    // This is case for "mwm" scheme,
    // if point is from "geo" or "ge0" - this is wrong. So we check here.

    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        MapObjectActivity.startWithApiPoint(getActivity(), name, null, null, lat, lon);
      }
    });
  }

  @Override
  public void onPoiActivated(final String name, final String type, final String address, final double lat, final double lon)
  {
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        MapObjectActivity.startWithPoi(getActivity(), name, type, address, lat, lon);
      }
    });
  }

  @Override
  public void onBookmarkActivated(final int category, final int bookmarkIndex)
  {
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        MapObjectActivity.startWithBookmark(getActivity(), category, bookmarkIndex);
      }
    });
  }

  @Override
  public void onMyPositionActivated(final double lat, final double lon)
  {
    runOnUiThread(new Runnable()
    {
      @Override
      public void run()
      {
        MapObjectActivity.startWithMyPosition(getActivity(), lat, lon);
      }
    });
  }

  private native void nativeStorageConnected();
  private native void nativeStorageDisconnected();

  private native void nativeConnectDownloadButton();
  private native void nativeDownloadCountry();

  private native void nativeDestroy();

  private native void nativeOnLocationError(int errorCode);
  private native void nativeLocationUpdated(long time, double lat, double lon, float accuracy, double altitude, float speed, float bearing);
  private native void nativeCompassUpdated(long time, double magneticNorth, double trueNorth, double accuracy);

  private native boolean nativeIsInChina(double lat, double lon);

  private native boolean setViewPortByUrl(String url);
}