Compare commits

...

27 commits
master ... r3.2

Author SHA1 Message Date
crimean
59c858dc77 Drop wake on voice setting 2019-03-02 12:31:08 +03:00
crimean
950732187d Drop wake on voice 2019-03-02 12:30:16 +03:00
crimean
a79649a4ef Merge subscriptions card fix 2018-11-15 19:11:47 +03:00
crimean
a341b9a91f Cleanup code 2018-11-14 20:48:20 +03:00
crimean
8fbcdb8353 Fix live subscriptions 2018-11-14 20:48:05 +03:00
crimean
b406f76920 Fix old live updates in-apps 2018-11-08 17:05:40 +03:00
crimean
78d29e470d Fix search space issue 2018-11-03 12:37:35 +03:00
crimean
df7d9d36bc Fix request inventory 2018-11-02 22:34:59 +03:00
crimean
855b717dfe Fix subscription UI issues 2018-11-02 16:43:50 +03:00
crimean
1ee6f36724 Update purchase state after purchase 2018-11-02 13:31:23 +03:00
Dmitriy Prodchenko
e9e2d0d4f4 Add icons for Plan screen 2018-11-02 12:18:27 +02:00
crimean
c4eac4d8e2 Fix choose plan ui issues 2018-11-02 12:37:13 +03:00
crimean
2724df5f0e Added new subscriptions - merge 2018-11-02 12:36:37 +03:00
Alex Sytnyk
566e2fe544 Restart search after pausing 2018-10-29 17:11:57 +02:00
Alex Sytnyk
27aa4ae4a7 Add the ability to open activity from notification 2018-10-26 10:52:15 +03:00
Alex Sytnyk
35c2790781 Add text button to the notification 2018-10-25 16:33:20 +03:00
Alex Sytnyk
3eb6f10a5d Use constant instead of hardcode 2018-10-25 11:34:11 +03:00
Alex Sytnyk
180a26077f Refactor the updating of the status bar color 2018-10-24 19:36:53 +03:00
Alex Sytnyk
4a2b9abda1 Add the ability to specify status bar color in the notification json 2018-10-24 11:41:37 +03:00
Alex Sytnyk
6e14f7b495 Move some methods from DiscountHelper to QuickSearchHelper 2018-10-23 17:20:28 +03:00
Alex Sytnyk
9d093e36e2 Fix #6144 2018-10-23 13:27:40 +03:00
Chumva
9c2a51fb4b Fix possible npe
(cherry picked from commit 19464a2)
2018-10-23 12:46:47 +03:00
Alex Sytnyk
a5018b9b98 Fix small issues 2018-10-23 12:06:24 +03:00
Alex Sytnyk
04ca2ba789 Dismiss splash screen before showing Christmas dialog 2018-10-22 18:36:01 +03:00
Alex Sytnyk
a9cf25ad64 Add the ability to show poi types from notification 2018-10-22 18:22:54 +03:00
Alex Sytnyk
3b9e3d2b56 Add support for search from the notification 2018-10-22 18:22:48 +03:00
Alex Sytnyk
1d8ded44bb Add the ability to show christmas dialog instead of notification 2018-10-19 17:25:59 +03:00
79 changed files with 2772 additions and 1038 deletions

View file

@ -530,7 +530,7 @@ public class SearchCoreFactory {
return false; return false;
} }
if (phrase.isNoSelectedType() && phrase.isUnknownSearchWordPresent() if (phrase.isNoSelectedType() && phrase.isUnknownSearchWordPresent()
&& phrase.isUnknownSearchWordComplete() && searchAmenityTypesAPI.hasFoundPoiTypes()) { && phrase.isUnknownSearchWordComplete() && phrase.hasUnknownSearchWordPoiTypes()) {
return false; return false;
} }
final BinaryMapIndexReader[] currentFile = new BinaryMapIndexReader[1]; final BinaryMapIndexReader[] currentFile = new BinaryMapIndexReader[1];
@ -653,30 +653,12 @@ public class SearchCoreFactory {
private List<CustomSearchPoiFilter> customPoiFilters = new ArrayList<>(); private List<CustomSearchPoiFilter> customPoiFilters = new ArrayList<>();
private TIntArrayList customPoiFiltersPriorites = new TIntArrayList(); private TIntArrayList customPoiFiltersPriorites = new TIntArrayList();
private MapPoiTypes types; private MapPoiTypes types;
private List<AbstractPoiType> foundPoiTypes = new ArrayList<>();
private SearchPhrase lastSearchedPhrase;
public SearchAmenityTypesAPI(MapPoiTypes types) { public SearchAmenityTypesAPI(MapPoiTypes types) {
super(ObjectType.POI_TYPE); super(ObjectType.POI_TYPE);
this.types = types; this.types = types;
} }
public List<AbstractPoiType> getFoundPoiTypes() {
return foundPoiTypes;
}
public boolean hasFoundPoiTypes() {
return foundPoiTypes.size() > 0;
}
public SearchPhrase getLastSearchedPhrase() {
return lastSearchedPhrase;
}
public void setLastSearchedPhrase(SearchPhrase lastSearchedPhrase) {
this.lastSearchedPhrase = lastSearchedPhrase;
}
public void clearCustomFilters() { public void clearCustomFilters() {
this.customPoiFilters.clear(); this.customPoiFilters.clear();
this.customPoiFiltersPriorites.clear(); this.customPoiFiltersPriorites.clear();
@ -739,8 +721,7 @@ public class SearchCoreFactory {
} }
} }
} }
foundPoiTypes = new ArrayList<>(results); phrase.setUnknownSearchWordPoiTypes(new ArrayList<>(results));
lastSearchedPhrase = phrase;
if (resultMatcher != null) { if (resultMatcher != null) {
for (AbstractPoiType pt : results) { for (AbstractPoiType pt : results) {
@ -852,18 +833,16 @@ public class SearchCoreFactory {
} }
searchPoi(phrase, resultMatcher, obj, null, ptf); searchPoi(phrase, resultMatcher, obj, null, ptf);
} else if (searchAmenityTypesAPI != null) { } else if (searchAmenityTypesAPI != null) {
if (searchAmenityTypesAPI.lastSearchedPhrase == null if (phrase.getUnknownSearchWordPoiTypes() == null) {
|| !searchAmenityTypesAPI.lastSearchedPhrase.getUnknownSearchPhrase().equals(phrase.getUnknownSearchPhrase())) {
searchAmenityTypesAPI.search(phrase, null); searchAmenityTypesAPI.search(phrase, null);
} }
List<AbstractPoiType> poiTypes = searchAmenityTypesAPI.getFoundPoiTypes(); AbstractPoiType poiType = phrase.getUnknownSearchWordPoiType();
for (AbstractPoiType pt : poiTypes) { if (poiType != null) {
SearchPoiTypeFilter ptf = getPoiTypeFilter(pt); SearchPoiTypeFilter ptf = getPoiTypeFilter(poiType);
String customName = phrase.getPoiNameFilter(pt); String customName = phrase.getPoiNameFilter(poiType);
if (customName != null) { if (customName != null) {
phrase.setUnknownSearchWordPoiType(pt); phrase.setUnknownSearchWordPoiType(poiType);
searchPoi(phrase, resultMatcher, null, customName, ptf); searchPoi(phrase, resultMatcher, null, customName.length() == 0 ? null : customName, ptf);
break;
} }
} }
} }
@ -939,7 +918,14 @@ public class SearchCoreFactory {
res.priority = SEARCH_AMENITY_BY_TYPE_PRIORITY; res.priority = SEARCH_AMENITY_BY_TYPE_PRIORITY;
res.priorityDistance = 1; res.priorityDistance = 1;
if (phraseMatcher != null) { if (phraseMatcher != null) {
res.unknownPhraseMatches = phraseMatcher.matches(res.localeName) || phraseMatcher.matches(res.otherNames); boolean unknownPhraseMatches = phraseMatcher.matches(res.localeName) || phraseMatcher.matches(res.otherNames);
AbstractPoiType unknownSearchWordPoiType = phrase.getUnknownSearchWordPoiType();
if (unknownPhraseMatches && unknownSearchWordPoiType != null) {
unknownPhraseMatches = !phraseMatcher.matches(unknownSearchWordPoiType.getTranslation())
&& !phraseMatcher.matches(unknownSearchWordPoiType.getEnTranslation())
&& !phraseMatcher.matches(unknownSearchWordPoiType.getSynonyms());
}
res.unknownPhraseMatches = unknownPhraseMatches;
} }
res.objectType = ObjectType.POI; res.objectType = ObjectType.POI;
resultMatcher.publish(res); resultMatcher.publish(res);
@ -988,7 +974,7 @@ public class SearchCoreFactory {
@Override @Override
public int getSearchPriority(SearchPhrase p) { public int getSearchPriority(SearchPhrase p) {
if ((p.isLastWord(ObjectType.POI_TYPE) && p.getLastTokenLocation() != null) if ((p.isLastWord(ObjectType.POI_TYPE) && p.getLastTokenLocation() != null)
|| (p.isNoSelectedType() && p.isUnknownSearchWordComplete())) { || (p.isNoSelectedType())) {
return SEARCH_AMENITY_BY_TYPE_PRIORITY; return SEARCH_AMENITY_BY_TYPE_PRIORITY;
} }
return -1; return -1;

View file

@ -36,6 +36,7 @@ public class SearchPhrase {
private String rawUnknownSearchPhrase = ""; private String rawUnknownSearchPhrase = "";
private String unknownSearchPhrase = ""; private String unknownSearchPhrase = "";
private AbstractPoiType unknownSearchWordPoiType; private AbstractPoiType unknownSearchWordPoiType;
private List<AbstractPoiType> unknownSearchWordPoiTypes = null;
private NameStringMatcher sm; private NameStringMatcher sm;
private SearchSettings settings; private SearchSettings settings;
@ -186,7 +187,7 @@ public class SearchPhrase {
public boolean isUnknownSearchWordComplete() { public boolean isUnknownSearchWordComplete() {
return lastUnknownSearchWordComplete || unknownWords.size() > 0; return lastUnknownSearchWordComplete || unknownWords.size() > 0 || unknownSearchWordPoiType != null;
} }
public boolean isLastUnknownSearchWordComplete() { public boolean isLastUnknownSearchWordComplete() {
@ -248,6 +249,24 @@ public class SearchPhrase {
return getPoiNameFilter(unknownSearchWordPoiType); return getPoiNameFilter(unknownSearchWordPoiType);
} }
public boolean hasUnknownSearchWordPoiTypes() {
return unknownSearchWordPoiTypes != null && unknownSearchWordPoiTypes.size() > 0;
}
public List<AbstractPoiType> getUnknownSearchWordPoiTypes() {
return unknownSearchWordPoiTypes;
}
public void setUnknownSearchWordPoiTypes(List<AbstractPoiType> unknownSearchWordPoiTypes) {
this.unknownSearchWordPoiTypes = unknownSearchWordPoiTypes;
for (AbstractPoiType pt : unknownSearchWordPoiTypes) {
if (getPoiNameFilter(pt) != null) {
setUnknownSearchWordPoiType(pt);
break;
}
}
}
public String getPoiNameFilter(AbstractPoiType pt) { public String getPoiNameFilter(AbstractPoiType pt) {
String nameFilter = null; String nameFilter = null;
if (pt != null) { if (pt != null) {
@ -256,11 +275,11 @@ public class SearchPhrase {
String enTranslation = pt.getEnTranslation(); String enTranslation = pt.getEnTranslation();
String translation = pt.getTranslation(); String translation = pt.getTranslation();
String synonyms = pt.getSynonyms(); String synonyms = pt.getSynonyms();
if (unknownSearchPhrase.length() > enTranslation.length() && nm.matches(enTranslation)) { if (unknownSearchPhrase.length() >= enTranslation.length() && nm.matches(enTranslation)) {
nameFilter = unknownSearchPhrase.substring(enTranslation.length()).trim(); nameFilter = unknownSearchPhrase.substring(enTranslation.length()).trim();
} else if (unknownSearchPhrase.length() > translation.length() && nm.matches(translation)) { } else if (unknownSearchPhrase.length() >= translation.length() && nm.matches(translation)) {
nameFilter = unknownSearchPhrase.substring(translation.length()).trim(); nameFilter = unknownSearchPhrase.substring(translation.length()).trim();
} else if (unknownSearchPhrase.length() > synonyms.length() && nm.matches(synonyms)) { } else if (unknownSearchPhrase.length() >= synonyms.length() && nm.matches(synonyms)) {
nameFilter = unknownSearchPhrase.substring(synonyms.length()).trim(); nameFilter = unknownSearchPhrase.substring(synonyms.length()).trim();
} }
} }

View file

@ -744,20 +744,6 @@
<receiver android:name="net.osmand.plus.notifications.NotificationDismissReceiver" /> <receiver android:name="net.osmand.plus.notifications.NotificationDismissReceiver" />
<activity android:name="net.osmand.plus.activities.PrintDialogActivity" /> <activity android:name="net.osmand.plus.activities.PrintDialogActivity" />
<receiver
android:name="net.osmand.plus.DeviceAdminRecv"
android:label="@string/app_name"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
</intent-filter>
</receiver>
<activity android:name=".liveupdates.OsmLiveActivity" <activity android:name=".liveupdates.OsmLiveActivity"
android:label="@string/osm_live"/> android:label="@string/osm_live"/>
<activity android:name=".wikivoyage.explore.WikivoyageExploreActivity"> <activity android:name=".wikivoyage.explore.WikivoyageExploreActivity">

View file

@ -25,6 +25,11 @@
<string name="hint_value">Value</string> <string name="hint_value">Value</string>
<!-- DEVELOPMENT --> <!-- DEVELOPMENT -->
<string name="osm_live_default_price">€1,49</string> <string name="osm_live_default_price">€1,49</string>
<string name="osm_live_monthly_price">€1,99</string>
<string name="osm_live_3_months_price">€3,99</string>
<string name="osm_live_3_months_monthly_price">€1,33</string>
<string name="osm_live_annual_price">€7,99</string>
<string name="osm_live_annual_monthly_price">€2,66</string>
<string name="twitter_address">https://twitter.com/osmandapp</string> <string name="twitter_address">https://twitter.com/osmandapp</string>
<string name="facebook_address">https://www.facebook.com/osmandapp</string> <string name="facebook_address">https://www.facebook.com/osmandapp</string>
<string name="vk_address">https://vk.com/osmandapp</string> <string name="vk_address">https://vk.com/osmandapp</string>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<stroke android:color="@color/color_dialog_buttons_dark" android:width="2dp"/>
<corners android:radius="@dimen/map_button_rect_rad" />
</shape>
</item>
</selector>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<stroke android:color="@color/color_dialog_buttons_light" android:width="2dp"/>
<corners android:radius="@dimen/map_button_rect_rad" />
</shape>
</item>
</selector>

View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/color_transparent" />
<stroke
android:width="1dp"
android:color="@color/wikivoyage_active_dark" />
<corners android:radius="@dimen/map_button_rect_rad" />
</shape>

View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/color_transparent" />
<stroke
android:width="1dp"
android:color="@color/osmand_orange" />
<corners android:radius="@dimen/map_button_rect_rad" />
</shape>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/wikivoyage_card_divider_dark" />
<corners android:radius="@dimen/map_button_rect_rad" />
</shape>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/wikivoyage_card_divider_light" />
<corners android:radius="@dimen/map_button_rect_rad" />
</shape>

View file

@ -437,6 +437,21 @@
android:visibility="gone" android:visibility="gone"
tools:text="New version of OsmAnd+ with 50% discount"/> tools:text="New version of OsmAnd+ with 50% discount"/>
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/widget_top_bar_text_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:ellipsize="end"
android:maxLines="1"
android:layout_marginTop="8dp"
android:textColor="?attr/wikivoyage_active_color"
android:textSize="@dimen/default_list_text_size"
android:visibility="gone"
osmand:typeface="@string/font_roboto_medium"
tools:text="Some button"
tools:visibility="visible"/>
</LinearLayout> </LinearLayout>
<ImageButton <ImageButton

View file

@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
xmlns:osmand="http://schemas.android.com/tools"
android:orientation="vertical" android:orientation="vertical"
android:paddingLeft="6dp" android:paddingLeft="6dp"
android:paddingRight="6dp" android:paddingRight="6dp"
@ -182,6 +182,76 @@
</LinearLayout> </LinearLayout>
<View
android:id="@+id/buttons_div"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/dashboard_divider"
android:visibility="visible"/>
<LinearLayout
android:id="@+id/buttons_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="48dp"
android:orientation="horizontal"
android:visibility="visible">
<LinearLayout
android:id="@+id/button_subscriptions_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:gravity="left|center_vertical">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/button_subscriptions"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:ellipsize="end"
android:gravity="left|center_vertical"
android:lines="1"
android:maxLines="1"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:text="@string/osm_live_subscriptions"
android:textColor="?attr/color_dialog_buttons"
android:textSize="@dimen/default_list_text_size"
app:textAllCapsCompat="true"
app:typeface="@string/font_roboto_medium" />
</LinearLayout>
<LinearLayout
android:id="@+id/button_settings_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:gravity="right|center_vertical">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/button_settings"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:gravity="right|center_vertical"
android:ellipsize="end"
android:lines="1"
android:maxLines="1"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:text="@string/shared_string_settings"
android:textColor="?attr/color_dialog_buttons"
android:textSize="@dimen/default_list_text_size"
app:textAllCapsCompat="true"
app:typeface="@string/font_roboto_medium" />
</LinearLayout>
</LinearLayout>
</LinearLayout> </LinearLayout>
</LinearLayout> </LinearLayout>

View file

@ -214,6 +214,21 @@
android:visibility="gone" android:visibility="gone"
tools:text="New version of OsmAnd+ with 50% discount"/> tools:text="New version of OsmAnd+ with 50% discount"/>
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/widget_top_bar_text_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:ellipsize="end"
android:maxLines="1"
android:layout_marginTop="8dp"
android:textColor="?attr/wikivoyage_active_color"
android:textSize="@dimen/default_list_text_size"
android:visibility="gone"
osmand:typeface="@string/font_roboto_medium"
tools:text="Some button"
tools:visibility="visible"/>
</LinearLayout> </LinearLayout>
<ImageButton <ImageButton

View file

@ -1,52 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:osmand="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/list_header_padding"
android:layout_marginLeft="@dimen/card_padding"
android:layout_marginRight="@dimen/card_padding"
android:background="?attr/purchase_dialog_active_card_bg"
android:orientation="vertical">
<include layout="@layout/purchase_dialog_card_header"/>
<View
android:id="@+id/header_div"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:background="?attr/wikivoyage_card_divider_color"/>
<LinearLayout
android:id="@+id/rows_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/card_descr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/list_content_padding_large"
android:layout_marginRight="@dimen/list_content_padding_large"
android:layout_marginTop="@dimen/list_header_padding"
android:gravity="center"
android:textColor="?attr/card_description_text_color"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text="@string/osm_live_payment_desc"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/card_padding">
<include layout="@layout/purchase_dialog_card_button"/>
</FrameLayout>
</LinearLayout>

View file

@ -43,6 +43,7 @@
android:layout_margin="@dimen/card_padding"> android:layout_margin="@dimen/card_padding">
<include layout="@layout/purchase_dialog_card_button"/> <include layout="@layout/purchase_dialog_card_button"/>
<include layout="@layout/purchase_dialog_card_button_disabled"/>
</FrameLayout> </FrameLayout>

View file

@ -0,0 +1,151 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:osmand="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:background="?attr/subscription_active_bg_color"
android:orientation="vertical">
<View
android:id="@+id/div_top"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/subscription_active_div_color"
android:visibility="gone" />
<LinearLayout
android:id="@+id/button_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:baselineAligned="false"
android:minHeight="@dimen/dialog_button_ex_height"
android:orientation="horizontal"
android:paddingLeft="@dimen/card_padding"
android:paddingRight="@dimen/card_padding">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="@dimen/list_header_padding"
android:layout_marginEnd="@dimen/list_content_padding"
android:layout_marginRight="@dimen/list_content_padding"
android:layout_marginBottom="@dimen/list_header_padding"
android:layout_weight="1"
android:orientation="vertical">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="?attr/dialog_title_color"
android:textSize="@dimen/default_list_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text="Pay monthly" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/card_description_text_color"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text="Monthly payment" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/button_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="?attr/wikivoyage_secondary_btn_bg">
<LinearLayout
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="@dimen/dialog_button_height"
android:gravity="center"
android:orientation="horizontal"
android:padding="@dimen/list_header_padding">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/button_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:letterSpacing="@dimen/text_button_letter_spacing"
android:maxWidth="@dimen/dialog_button_ex_max_width"
android:minWidth="@dimen/dialog_button_ex_min_width"
android:textColor="@color/wikivoyage_secondary_text"
android:textSize="@dimen/text_button_text_size"
osmand:typeface="@string/font_roboto_medium"
tools:text="7,99€" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/button_cancel_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="?attr/wikivoyage_primary_btn_bg">
<LinearLayout
android:id="@+id/button_cancel"
android:layout_width="match_parent"
android:layout_height="@dimen/dialog_button_height"
android:gravity="center"
android:orientation="horizontal"
android:padding="@dimen/list_header_padding">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/button_cancel_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:letterSpacing="@dimen/text_button_letter_spacing"
android:maxWidth="@dimen/dialog_button_ex_max_width"
android:minWidth="@dimen/dialog_button_ex_min_width"
android:text="@string/shared_string_cancel"
android:textColor="@color/color_white"
android:textSize="@dimen/text_button_text_size"
osmand:typeface="@string/font_roboto_medium" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<View
android:id="@+id/div"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="@dimen/card_padding"
android:layout_marginRight="@dimen/card_padding"
android:background="?attr/subscription_active_div_color"
android:visibility="gone" />
<View
android:id="@+id/div_bottom"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?attr/subscription_active_div_color"
android:visibility="gone" />
</LinearLayout>

View file

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:osmand="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/wikivoyage_secondary_btn_bg">
<LinearLayout
android:id="@+id/card_button_disabled"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:gravity="center"
android:minHeight="@dimen/card_button_min_size"
android:orientation="vertical"
android:paddingLeft="@dimen/list_content_padding"
android:paddingTop="@dimen/list_header_padding"
android:paddingRight="@dimen/list_content_padding"
android:paddingBottom="@dimen/list_header_padding">
<ProgressBar
android:id="@+id/card_button_progress"
android:layout_width="@dimen/card_button_progress_size"
android:layout_height="@dimen/card_button_progress_size"
android:indeterminate="true"
android:visibility="gone" />
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/card_button_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:letterSpacing="@dimen/text_button_letter_spacing"
android:textColor="@color/wikivoyage_secondary_text"
android:textSize="@dimen/text_button_text_size"
osmand:typeface="@string/font_roboto_medium"
tools:text="Buy - 5€" />
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/card_button_subtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:letterSpacing="@dimen/text_button_letter_spacing"
android:textColor="@color/wikivoyage_secondary_text"
android:textSize="@dimen/text_button_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text="One time purchase" />
</LinearLayout>
</FrameLayout>

View file

@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:osmand="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/button_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:baselineAligned="false"
android:minHeight="@dimen/dialog_button_ex_height"
android:orientation="horizontal"
android:paddingLeft="@dimen/card_padding"
android:paddingRight="@dimen/card_padding">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="@dimen/list_header_padding"
android:layout_marginEnd="@dimen/list_content_padding"
android:layout_marginRight="@dimen/list_content_padding"
android:layout_marginBottom="@dimen/list_header_padding"
android:layout_weight="1"
android:orientation="vertical">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="?attr/dialog_title_color"
android:textSize="@dimen/default_list_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text="Pay monthly" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="?attr/card_description_text_color"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text="Monthly payment" />
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/discount_banner_regular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="@dimen/list_item_button_padding"
android:layout_marginLeft="@dimen/list_item_button_padding"
android:background="?attr/text_rounded_bg_regular"
android:textColor="?attr/card_description_text_color"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text=" Save 20%! " />
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/discount_banner_active"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginStart="@dimen/list_item_button_padding"
android:layout_marginLeft="@dimen/list_item_button_padding"
android:background="?attr/text_rounded_bg_active"
android:textColor="@color/osmand_orange"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular"
tools:text=" Save 20%! " />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/button_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="?attr/btn_round_border_2">
<LinearLayout
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="@dimen/dialog_button_height"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:orientation="horizontal"
android:padding="@dimen/list_header_padding">
<ProgressBar
android:id="@+id/button_progress"
android:layout_width="@dimen/card_button_progress_size_small"
android:layout_height="@dimen/card_button_progress_size_small"
android:indeterminate="true"
android:visibility="gone" />
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/button_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:letterSpacing="@dimen/text_button_letter_spacing"
android:maxWidth="@dimen/dialog_button_ex_max_width"
android:minWidth="@dimen/dialog_button_ex_min_width"
android:textColor="?attr/color_dialog_buttons"
android:textSize="@dimen/text_button_text_size"
osmand:typeface="@string/font_roboto_medium"
tools:text="7,99€" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/button_ex_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="?attr/wikivoyage_primary_btn_bg">
<LinearLayout
android:id="@+id/button_ex"
android:layout_width="match_parent"
android:layout_height="@dimen/dialog_button_height"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:orientation="horizontal"
android:padding="@dimen/list_header_padding">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/button_ex_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:letterSpacing="@dimen/text_button_letter_spacing"
android:maxWidth="@dimen/dialog_button_ex_max_width"
android:minWidth="@dimen/dialog_button_ex_min_width"
android:textColor="@color/color_white"
android:textSize="@dimen/text_button_text_size"
osmand:typeface="@string/font_roboto_medium"
tools:text="7,99€" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<View
android:id="@+id/div"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="@dimen/card_padding"
android:layout_marginRight="@dimen/card_padding"
android:background="?attr/wikivoyage_card_divider_color"
android:visibility="gone" />
</LinearLayout>

View file

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:osmand="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/card_padding"
android:layout_marginRight="@dimen/card_padding"
android:layout_marginBottom="@dimen/list_header_padding"
android:background="?attr/purchase_dialog_active_card_bg"
android:orientation="vertical">
<include layout="@layout/purchase_dialog_card_header" />
<View
android:id="@+id/header_div"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:background="?attr/wikivoyage_card_divider_color" />
<LinearLayout
android:id="@+id/rows_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
<View
android:id="@+id/buttons_div"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:background="?attr/wikivoyage_card_divider_color"/>
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/card_button_subtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/card_padding"
android:layout_marginLeft="@dimen/card_padding"
android:layout_marginRight="@dimen/card_padding"
android:layout_marginBottom="@dimen/list_header_padding"
android:text="@string/osm_live_payment_header"
android:textColor="@color/dialog_text_description_color"
android:textSize="@dimen/default_desc_text_size"
osmand:typeface="@string/font_roboto_regular" />
<ProgressBar
android:id="@+id/card_progress"
android:layout_width="@dimen/card_button_progress_size"
android:layout_height="@dimen/card_button_progress_size"
android:layout_gravity="center"
android:layout_marginTop="@dimen/card_padding"
android:layout_marginLeft="@dimen/card_padding"
android:layout_marginRight="@dimen/card_padding"
android:layout_marginBottom="@dimen/list_content_padding_large"
android:indeterminate="true"
android:visibility="visible" />
<LinearLayout
android:id="@+id/card_buttons_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:orientation="vertical"
android:visibility="gone" />
</LinearLayout>

View file

@ -277,7 +277,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="16dp" android:layout_marginBottom="16dp"
android:layout_marginTop="16dp" android:layout_marginTop="16dp"
android:visibility="gone"> android:visibility="visible">
<Button <Button
android:id="@+id/saveChangesButton" android:id="@+id/saveChangesButton"
@ -297,105 +297,6 @@
<include layout="@layout/card_bottom_divider"/> <include layout="@layout/card_bottom_divider"/>
<View
android:layout_width="match_parent"
android:layout_height="8dp"/>
<include layout="@layout/card_top_divider"/>
<LinearLayout
android:id="@+id/purchaseCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/bg_color"
android:orientation="vertical"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatImageView
android:layout_width="56dp"
android:layout_height="48dp"
android:scaleType="center"
android:tint="?attr/color_dialog_buttons"
android:src="@drawable/ic_action_payment_card"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal">
<net.osmand.plus.widgets.TextViewEx
android:id="@+id/priceTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:text="@string/osm_live_default_price"
android:textColor="?attr/color_dialog_buttons"
android:textSize="@dimen/default_list_text_size_large"
android:textStyle="bold"/>
<net.osmand.plus.widgets.TextViewEx
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textColor="?android:attr/textColorPrimary"
android:textSize="@dimen/default_list_text_size_large"
android:textStyle="bold"/>
<net.osmand.plus.widgets.TextViewEx
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/osm_live_month_cost"
android:textColor="?android:attr/textColorPrimary"
android:textSize="@dimen/default_list_text_size_large"
android:textStyle="bold"/>
</LinearLayout>
<net.osmand.plus.widgets.TextViewEx
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/osm_live_payment_desc"
android:textColor="?android:attr/textColorSecondary"
android:textSize="@dimen/default_desc_text_size"/>
<android.support.v7.widget.AppCompatButton
android:id="@+id/subscribeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginBottom="20dp"
android:background="@drawable/blue_button_drawable"
android:paddingBottom="4dp"
android:paddingLeft="14dp"
android:paddingRight="14dp"
android:paddingTop="4dp"
android:text="@string/osm_live_subscribe_btn"
android:textColor="@color/color_white"
android:visibility="visible"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<include layout="@layout/card_bottom_divider"/>
<View <View
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="16dp"/> android:layout_height="16dp"/>

View file

@ -19,6 +19,7 @@
<attr name="expandable_list_background" format="color"/> <attr name="expandable_list_background" format="color"/>
<attr name="bg_color" format="reference" /> <attr name="bg_color" format="reference" />
<attr name="btn_round_border" format="reference" /> <attr name="btn_round_border" format="reference" />
<attr name="btn_round_border_2" format="reference" />
<attr name="bg_card" format="reference" /> <attr name="bg_card" format="reference" />
<attr name="context_menu_card" format="reference" /> <attr name="context_menu_card" format="reference" />
<attr name="ctx_menu_card_btn" format="reference" /> <attr name="ctx_menu_card_btn" format="reference" />
@ -74,6 +75,9 @@
<attr name="dialog_text_description_color" format="reference"/> <attr name="dialog_text_description_color" format="reference"/>
<attr name="card_description_text_color" format="reference"/> <attr name="card_description_text_color" format="reference"/>
<attr name="subscription_active_bg_color" format="reference"/>
<attr name="subscription_active_div_color" format="reference"/>
<attr name="wikivoyage_bg_color" format="reference"/> <attr name="wikivoyage_bg_color" format="reference"/>
<attr name="wikivoyage_card_bg_color" format="reference"/> <attr name="wikivoyage_card_bg_color" format="reference"/>
<attr name="wikivoyage_card_divider_color" format="reference"/> <attr name="wikivoyage_card_divider_color" format="reference"/>
@ -96,6 +100,9 @@
<attr name="bottom_nav_shadow" format="reference"/> <attr name="bottom_nav_shadow" format="reference"/>
<attr name="purchase_dialog_active_card_bg" format="reference"/> <attr name="purchase_dialog_active_card_bg" format="reference"/>
<attr name="text_rounded_bg_regular" format="reference" />
<attr name="text_rounded_bg_active" format="reference" />
</declare-styleable> </declare-styleable>
<declare-styleable name="PagerSlidingTabStrip"> <declare-styleable name="PagerSlidingTabStrip">

View file

@ -1,6 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="subscription_active_bg_color_light">#fff9b2</color>
<color name="subscription_active_bg_color_dark">#43453b</color>
<color name="subscription_active_div_color_light">#f3edae</color>
<color name="subscription_active_div_color_dark">#32332c</color>
<color name="feature_purchased_bg">#78cc5c</color> <color name="feature_purchased_bg">#78cc5c</color>
<color name="dialog_bg_color_light">#f0f0f0</color> <color name="dialog_bg_color_light">#f0f0f0</color>

View file

@ -1,6 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<dimen name="dialog_button_ex_height">60dp</dimen>
<dimen name="dialog_button_ex_min_width">72dp</dimen>
<dimen name="dialog_button_ex_max_width">120dp</dimen>
<dimen name="wpt_list_category_height">60dp</dimen> <dimen name="wpt_list_category_height">60dp</dimen>
<dimen name="wpt_list_item_height">56dp</dimen> <dimen name="wpt_list_item_height">56dp</dimen>
<dimen name="list_item_button_padding">4dp</dimen> <dimen name="list_item_button_padding">4dp</dimen>
@ -12,6 +15,7 @@
<dimen name="card_row_min_height">48dp</dimen> <dimen name="card_row_min_height">48dp</dimen>
<dimen name="card_button_min_size">58dp</dimen> <dimen name="card_button_min_size">58dp</dimen>
<dimen name="card_button_progress_size">32dp</dimen> <dimen name="card_button_progress_size">32dp</dimen>
<dimen name="card_button_progress_size_small">24dp</dimen>
<dimen name="card_padding">12dp</dimen> <dimen name="card_padding">12dp</dimen>
<dimen name="widget_turn_lane_size">36dp</dimen> <dimen name="widget_turn_lane_size">36dp</dimen>

View file

@ -10,6 +10,22 @@
- For wording and consistency, please note https://osmand.net/help-online?id=technical-articles#Creating_a_Consistent_User_Experience - For wording and consistency, please note https://osmand.net/help-online?id=technical-articles#Creating_a_Consistent_User_Experience
Thx - Hardy Thx - Hardy
--> -->
<string name="osm_live_subscriptions">Subscriptions</string>
<string name="powered_by_osmand">Powered by OsmAnd</string>
<string name="osm_live_plan_pricing">Plan &amp; Pricing</string>
<string name="osm_live_payment_monthly_title">Pay monthly</string>
<string name="osm_live_payment_3_months_title">Pay once in 3 months</string>
<string name="osm_live_payment_annual_title">Pay once a year</string>
<string name="osm_live_payment_month_cost_descr">%1$s / month</string>
<string name="osm_live_payment_month_cost_descr_ex">%1$.2f %2$s / month</string>
<string name="osm_live_payment_discount_descr">Save %1$s!</string>
<string name="osm_live_payment_current_subscription">Your current subscription</string>
<string name="osm_live_payment_renews_monthly">Renews monthly</string>
<string name="osm_live_payment_renews_quarterly">Renews quarterly</string>
<string name="osm_live_payment_renews_annually">Renews annually</string>
<string name="default_price_currency_format">%1$.2f %2$s</string>
<string name="osm_live_payment_header">Select the payment period convenient for you:</string>
<string name="osm_live_payment_contribute_descr">Part of income goes to OpenStreetMap contributors.</string>
<string name="markers_remove_dialog_msg">Delete Map marker \'%s\'?</string> <string name="markers_remove_dialog_msg">Delete Map marker \'%s\'?</string>
<string name="edit_map_marker">Edit map marker</string> <string name="edit_map_marker">Edit map marker</string>
<string name="third_party_application">Third-party application</string> <string name="third_party_application">Third-party application</string>

View file

@ -130,6 +130,7 @@
<item name="actionBarStyle">@style/Widget.Styled.ActionBarLight</item> <item name="actionBarStyle">@style/Widget.Styled.ActionBarLight</item>
<item name="bg_color">@color/bg_color_light</item> <item name="bg_color">@color/bg_color_light</item>
<item name="btn_round_border">@drawable/btn_round_border_light</item> <item name="btn_round_border">@drawable/btn_round_border_light</item>
<item name="btn_round_border_2">@drawable/btn_round_border_light_2</item>
<item name="bg_card">@drawable/bg_card_light</item> <item name="bg_card">@drawable/bg_card_light</item>
<item name="context_menu_card">@drawable/context_menu_card_light</item> <item name="context_menu_card">@drawable/context_menu_card_light</item>
<item name="bg_map_context_menu">@drawable/bg_map_context_menu_light</item> <item name="bg_map_context_menu">@drawable/bg_map_context_menu_light</item>
@ -199,6 +200,9 @@
<item name="coordinate_input_edit_text_normal">@color/coordinate_input_edit_text_normal_light</item> <item name="coordinate_input_edit_text_normal">@color/coordinate_input_edit_text_normal_light</item>
<item name="subscription_active_bg_color">@color/subscription_active_bg_color_light</item>
<item name="subscription_active_div_color">@color/subscription_active_div_color_light</item>
<item name="dialog_bg_color">@color/dialog_bg_color_light</item> <item name="dialog_bg_color">@color/dialog_bg_color_light</item>
<item name="dialog_transparent_bg_color">@color/dialog_transparent_bg_color_light</item> <item name="dialog_transparent_bg_color">@color/dialog_transparent_bg_color_light</item>
<item name="dialog_title_color">@color/dialog_title_color_light</item> <item name="dialog_title_color">@color/dialog_title_color_light</item>
@ -228,6 +232,8 @@
<item name="bottom_nav_shadow">@drawable/bg_bottom_bar_shadow_with_line_day</item> <item name="bottom_nav_shadow">@drawable/bg_bottom_bar_shadow_with_line_day</item>
<item name="text_rounded_bg_active">@drawable/text_rounded_bg_active_light</item>
<item name="text_rounded_bg_regular">@drawable/text_rounded_bg_regular_light</item>
</style> </style>
<style name="OverflowMenuButton" parent="@style/Widget.AppCompat.ActionButton.Overflow"> <style name="OverflowMenuButton" parent="@style/Widget.AppCompat.ActionButton.Overflow">
@ -358,6 +364,7 @@
<item name="actionBarStyle">@style/Widget.Styled.ActionBarDark</item> <item name="actionBarStyle">@style/Widget.Styled.ActionBarDark</item>
<item name="bg_color">@color/bg_color_dark</item> <item name="bg_color">@color/bg_color_dark</item>
<item name="btn_round_border">@drawable/btn_round_border_dark</item> <item name="btn_round_border">@drawable/btn_round_border_dark</item>
<item name="btn_round_border_2">@drawable/btn_round_border_dark_2</item>
<item name="bg_card">@drawable/bg_card_dark</item> <item name="bg_card">@drawable/bg_card_dark</item>
<item name="context_menu_card">@drawable/context_menu_card_dark</item> <item name="context_menu_card">@drawable/context_menu_card_dark</item>
<item name="bg_map_context_menu">@drawable/bg_map_context_menu_dark</item> <item name="bg_map_context_menu">@drawable/bg_map_context_menu_dark</item>
@ -375,8 +382,7 @@
<item name="switch_ex_background">@drawable/switch_ex_background_dark</item> <item name="switch_ex_background">@drawable/switch_ex_background_dark</item>
<item name="switch_ex_text_color">@color/switch_ex_button_text_dark</item> <item name="switch_ex_text_color">@color/switch_ex_button_text_dark</item>
<item name="bg_plugin_logo_disabled">@drawable/bg_plugin_logo_disabled_dark</item> <item name="bg_plugin_logo_disabled">@drawable/bg_plugin_logo_disabled_dark</item>
<item name="plugin_details_install_header_bg">@color/plugin_details_install_header_bg_dark <item name="plugin_details_install_header_bg">@color/plugin_details_install_header_bg_dark</item>
</item>
<item name="expandable_list_item_background"> <item name="expandable_list_item_background">
@drawable/expandable_list_item_background_dark @drawable/expandable_list_item_background_dark
</item> </item>
@ -384,8 +390,7 @@
<item name="size_progress_bar">@drawable/size_progressbar_dark</item> <item name="size_progress_bar">@drawable/size_progressbar_dark</item>
<item name="dash_parking_bg">@drawable/dash_parking_dark</item> <item name="dash_parking_bg">@drawable/dash_parking_dark</item>
<item name="dashboard_subheader_text_color">@color/dashboard_subheader_text_dark</item> <item name="dashboard_subheader_text_color">@color/dashboard_subheader_text_dark</item>
<item name="dashboard_general_button_text_color">@color/dashboard_general_button_text_dark <item name="dashboard_general_button_text_color">@color/dashboard_general_button_text_dark</item>
</item>
<item name="android:listChoiceIndicatorMultiple">@drawable/check_dark</item> <item name="android:listChoiceIndicatorMultiple">@drawable/check_dark</item>
<item name="android:textColorPrimary">@color/color_white</item> <item name="android:textColorPrimary">@color/color_white</item>
<item name="spinnerItemTextColor">@color/color_white</item> <item name="spinnerItemTextColor">@color/color_white</item>
@ -414,6 +419,9 @@
<item name="coordinate_input_edit_text_normal">@color/coordinate_input_edit_text_normal_dark</item> <item name="coordinate_input_edit_text_normal">@color/coordinate_input_edit_text_normal_dark</item>
<item name="subscription_active_bg_color">@color/subscription_active_bg_color_dark</item>
<item name="subscription_active_div_color">@color/subscription_active_div_color_dark</item>
<item name="circle_dialog_bg">@drawable/circle_dialog_bg_night</item> <item name="circle_dialog_bg">@drawable/circle_dialog_bg_night</item>
<item name="dialog_bg_color">@color/dialog_bg_color_night</item> <item name="dialog_bg_color">@color/dialog_bg_color_night</item>
<item name="dialog_transparent_bg_color">@color/dialog_transparent_bg_color_night</item> <item name="dialog_transparent_bg_color">@color/dialog_transparent_bg_color_night</item>
@ -444,6 +452,8 @@
<item name="bottom_nav_shadow">@drawable/bg_bottom_bar_shadow_with_line_night</item> <item name="bottom_nav_shadow">@drawable/bg_bottom_bar_shadow_with_line_night</item>
<item name="text_rounded_bg_active">@drawable/text_rounded_bg_active_dark</item>
<item name="text_rounded_bg_regular">@drawable/text_rounded_bg_regular_dark</item>
</style> </style>
<style name="FreeVersionBanner" parent="OsmandDarkTheme"> <style name="FreeVersionBanner" parent="OsmandDarkTheme">

View file

@ -68,10 +68,6 @@
<!-- <!--
<CheckBoxPreference android:title="@string/show_zoom_buttons_navigation" android:summary="@string/show_zoom_buttons_navigation_descr" android:key="show_zoom_buttons_navigation" /> <CheckBoxPreference android:title="@string/show_zoom_buttons_navigation" android:summary="@string/show_zoom_buttons_navigation_descr" android:key="show_zoom_buttons_navigation" />
--> -->
<ListPreference
android:key="wake_on_voice_int"
android:summary="@string/wake_on_voice_descr"
android:title="@string/wake_on_voice"/>
<!-- <!--
<ListPreference <ListPreference
android:key="delay_to_start_navigation" android:key="delay_to_start_navigation"

View file

@ -7,9 +7,7 @@ import android.os.AsyncTask;
import net.osmand.osm.io.NetworkUtils; import net.osmand.osm.io.NetworkUtils;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.SQLiteTileSource;
import net.osmand.plus.Version; import net.osmand.plus.Version;
import net.osmand.plus.resources.ResourceManager;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -17,8 +15,6 @@ import org.apache.commons.logging.Log;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -29,6 +25,7 @@ import java.net.URLConnection;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.List;
import java.util.Map; import java.util.Map;
public class AndroidNetworkUtils { public class AndroidNetworkUtils {
@ -40,6 +37,35 @@ public class AndroidNetworkUtils {
void onResult(String result); void onResult(String result);
} }
public static void sendRequestsAsync(final OsmandApplication ctx,
final List<Request> requests,
final OnRequestResultListener listener) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
for (Request request : requests) {
try {
return sendRequest(ctx, request.getUrl(), request.getParameters(),
request.getUserOperation(), request.isToastAllowed(), request.isPost());
} catch (Exception e) {
// ignore
}
}
return null;
}
@Override
protected void onPostExecute(String response) {
if (listener != null) {
listener.onResult(response);
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}
public static void sendRequestAsync(final OsmandApplication ctx, public static void sendRequestAsync(final OsmandApplication ctx,
final String url, final String url,
final Map<String, String> parameters, final Map<String, String> parameters,
@ -193,4 +219,39 @@ public class AndroidNetworkUtils {
ctx.showToastMessage(message); ctx.showToastMessage(message);
} }
public static class Request {
private String url;
private Map<String, String> parameters;
private String userOperation;
private boolean toastAllowed;
private boolean post;
public Request(String url, Map<String, String> parameters, String userOperation, boolean toastAllowed, boolean post) {
this.url = url;
this.parameters = parameters;
this.userOperation = userOperation;
this.toastAllowed = toastAllowed;
this.post = post;
}
public String getUrl() {
return url;
}
public Map<String, String> getParameters() {
return parameters;
}
public String getUserOperation() {
return userOperation;
}
public boolean isToastAllowed() {
return toastAllowed;
}
public boolean isPost() {
return post;
}
}
} }

View file

@ -5,7 +5,6 @@ import android.content.res.Configuration;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@ -18,18 +17,15 @@ import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.Version; import net.osmand.plus.Version;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.base.BaseOsmAndFragment;
import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
public class SecondSplashScreenFragment extends Fragment { public class SecondSplashScreenFragment extends BaseOsmAndFragment {
public static final String TAG = "SecondSplashScreenFragment"; public static final String TAG = "SecondSplashScreenFragment";
public static boolean SHOW = true; public static boolean SHOW = true;
public static boolean VISIBLE = false; public static boolean VISIBLE = false;
public OsmandApplication getMyApplication() {
return ((OsmandApplication) getActivity().getApplication());
}
public MapActivity getMapActivity() { public MapActivity getMapActivity() {
return (MapActivity) getActivity(); return (MapActivity) getActivity();
} }
@ -161,4 +157,9 @@ public class SecondSplashScreenFragment extends Fragment {
super.onPause(); super.onPause();
getMapActivity().enableDrawer(); getMapActivity().enableDrawer();
} }
@Override
public int getStatusBarColorId() {
return R.color.status_bar_transparent_light;
}
} }

View file

@ -180,7 +180,7 @@ public class AppInitializer implements IProgress {
if(prevAppVersion < VERSION_2_3) { if(prevAppVersion < VERSION_2_3) {
startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_2_3).commit(); startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_2_3).commit();
} else if (prevAppVersion < VERSION_3_2) { } else if (prevAppVersion < VERSION_3_2) {
app.getSettings().BILLING_PURCHASE_TOKEN_SENT.set(false); app.getSettings().BILLING_PURCHASE_TOKENS_SENT.set("");
startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_3_2).commit(); startPrefs.edit().putInt(VERSION_INSTALLED_NUMBER, VERSION_3_2).commit();
} }
startPrefs.edit().putString(VERSION_INSTALLED, Version.getFullVersion(app)).commit(); startPrefs.edit().putString(VERSION_INSTALLED, Version.getFullVersion(app)).commit();

View file

@ -1,24 +0,0 @@
package net.osmand.plus;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class DeviceAdminRecv extends DeviceAdminReceiver {
private static final String TAG = "DeviceAdminReceiver";
public void onEnabled(Context context, Intent intent) {
Log.d(TAG, "permission disabled");
}
public CharSequence onDisableRequested(Context context, Intent intent) {
return null;
}
public void onDisabled(Context context, Intent intent) {
Log.d(TAG, "permission enabled");
}
}

View file

@ -709,15 +709,16 @@ public class FavouritesDbHelper {
private SQLiteConnection openConnection(boolean readonly) { private SQLiteConnection openConnection(boolean readonly) {
conn = context.getSQLiteAPI().getOrCreateDatabase(FAVOURITE_DB_NAME, readonly); conn = context.getSQLiteAPI().getOrCreateDatabase(FAVOURITE_DB_NAME, readonly);
if (conn.getVersion() == 0 || DATABASE_VERSION != conn.getVersion()) { if (conn.getVersion() < DATABASE_VERSION) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = context.getSQLiteAPI().getOrCreateDatabase(FAVOURITE_DB_NAME, false); conn = context.getSQLiteAPI().getOrCreateDatabase(FAVOURITE_DB_NAME, false);
} }
if (conn.getVersion() == 0) { int version = conn.getVersion();
if (version == 0) {
onCreate(conn); onCreate(conn);
} else { } else {
onUpgrade(conn, conn.getVersion(), DATABASE_VERSION); onUpgrade(conn, version, DATABASE_VERSION);
} }
conn.setVersion(DATABASE_VERSION); conn.setVersion(DATABASE_VERSION);
} }

View file

@ -170,13 +170,12 @@ public class GPXDatabase {
private SQLiteConnection openConnection(boolean readonly) { private SQLiteConnection openConnection(boolean readonly) {
SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly); SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly);
int version = conn.getVersion(); if (conn.getVersion() < DB_VERSION) {
if (version == 0 || DB_VERSION != version) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false);
} }
version = conn.getVersion(); int version = conn.getVersion();
conn.setVersion(DB_VERSION); conn.setVersion(DB_VERSION);
if (version == 0) { if (version == 0) {
onCreate(conn); onCreate(conn);

View file

@ -744,7 +744,7 @@ public class OsmandSettings {
public final CommonPreference<Boolean> SHOW_DASHBOARD_ON_MAP_SCREEN = new BooleanPreference("show_dashboard_on_map_screen", false).makeGlobal(); public final CommonPreference<Boolean> SHOW_DASHBOARD_ON_MAP_SCREEN = new BooleanPreference("show_dashboard_on_map_screen", false).makeGlobal();
public final CommonPreference<String> API_NAV_DRAWER_ITEMS_JSON = new StringPreference("api_nav_drawer_items_json", "{}").makeGlobal(); public final CommonPreference<String> API_NAV_DRAWER_ITEMS_JSON = new StringPreference("api_nav_drawer_items_json", "{}").makeGlobal();
public final CommonPreference<String> API_CONNECTED_APPS_JSON = new StringPreference("api_connected_apps_json", "{}").makeGlobal(); public final CommonPreference<String> API_CONNECTED_APPS_JSON = new StringPreference("api_connected_apps_json", "[]").makeGlobal();
public final CommonPreference<Integer> NUMBER_OF_STARTS_FIRST_XMAS_SHOWN = new IntPreference("number_of_starts_first_xmas_shown", 0).makeGlobal(); public final CommonPreference<Integer> NUMBER_OF_STARTS_FIRST_XMAS_SHOWN = new IntPreference("number_of_starts_first_xmas_shown", 0).makeGlobal();
@ -970,6 +970,7 @@ public class OsmandSettings {
public final OsmandPreference<String> BILLING_USER_COUNTRY_DOWNLOAD_NAME = new StringPreference("billing_user_country_download_name", BILLING_USER_DONATION_NONE_PARAMETER).makeGlobal(); public final OsmandPreference<String> BILLING_USER_COUNTRY_DOWNLOAD_NAME = new StringPreference("billing_user_country_download_name", BILLING_USER_DONATION_NONE_PARAMETER).makeGlobal();
public final OsmandPreference<Boolean> BILLING_HIDE_USER_NAME = new BooleanPreference("billing_hide_user_name", false).makeGlobal(); public final OsmandPreference<Boolean> BILLING_HIDE_USER_NAME = new BooleanPreference("billing_hide_user_name", false).makeGlobal();
public final OsmandPreference<Boolean> BILLING_PURCHASE_TOKEN_SENT = new BooleanPreference("billing_purchase_token_sent", false).makeGlobal(); public final OsmandPreference<Boolean> BILLING_PURCHASE_TOKEN_SENT = new BooleanPreference("billing_purchase_token_sent", false).makeGlobal();
public final OsmandPreference<String> BILLING_PURCHASE_TOKENS_SENT = new StringPreference("billing_purchase_tokens_sent", "").makeGlobal();
public final OsmandPreference<Boolean> LIVE_UPDATES_PURCHASED = new BooleanPreference("billing_live_updates_purchased", false).makeGlobal(); public final OsmandPreference<Boolean> LIVE_UPDATES_PURCHASED = new BooleanPreference("billing_live_updates_purchased", false).makeGlobal();
public final OsmandPreference<Long> LIVE_UPDATES_PURCHASE_CANCELLED_TIME = new LongPreference("live_updates_purchase_cancelled_time", 0).makeGlobal(); public final OsmandPreference<Long> LIVE_UPDATES_PURCHASE_CANCELLED_TIME = new LongPreference("live_updates_purchase_cancelled_time", 0).makeGlobal();
public final OsmandPreference<Boolean> LIVE_UPDATES_PURCHASE_CANCELLED_FIRST_DLG_SHOWN = new BooleanPreference("live_updates_purchase_cancelled_first_dlg_shown", false).makeGlobal(); public final OsmandPreference<Boolean> LIVE_UPDATES_PURCHASE_CANCELLED_FIRST_DLG_SHOWN = new BooleanPreference("live_updates_purchase_cancelled_first_dlg_shown", false).makeGlobal();
@ -1241,16 +1242,6 @@ public class OsmandSettings {
KEEP_INFORMING.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0); KEEP_INFORMING.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0);
} }
// screen power save
public final CommonPreference<Integer> WAKE_ON_VOICE_INT = new IntPreference("wake_on_voice_int", 0).makeProfile();
{
// 0 means never
WAKE_ON_VOICE_INT.setModeDefaultValue(ApplicationMode.CAR, 0);
WAKE_ON_VOICE_INT.setModeDefaultValue(ApplicationMode.BICYCLE, 0);
WAKE_ON_VOICE_INT.setModeDefaultValue(ApplicationMode.PEDESTRIAN, 0);
}
// this value string is synchronized with settings_pref.xml preference name // this value string is synchronized with settings_pref.xml preference name
// try without AUTO_FOLLOW_ROUTE_NAV (see forum discussion 'Simplify our navigation preference menu') // try without AUTO_FOLLOW_ROUTE_NAV (see forum discussion 'Simplify our navigation preference menu')
//public final CommonPreference<Boolean> AUTO_FOLLOW_ROUTE_NAV = new BooleanPreference("auto_follow_route_navigation", true, false); //public final CommonPreference<Boolean> AUTO_FOLLOW_ROUTE_NAV = new BooleanPreference("auto_follow_route_navigation", true, false);

View file

@ -93,10 +93,8 @@ import net.osmand.plus.helpers.DiscountHelper;
import net.osmand.plus.helpers.ExternalApiHelper; import net.osmand.plus.helpers.ExternalApiHelper;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.helpers.ImportHelper;
import net.osmand.plus.helpers.ImportHelper.ImportGpxBottomSheetDialogFragment; import net.osmand.plus.helpers.ImportHelper.ImportGpxBottomSheetDialogFragment;
import net.osmand.plus.helpers.WakeLockHelper;
import net.osmand.plus.mapcontextmenu.AdditionalActionsBottomSheetDialogFragment; import net.osmand.plus.mapcontextmenu.AdditionalActionsBottomSheetDialogFragment;
import net.osmand.plus.mapcontextmenu.MapContextMenu; import net.osmand.plus.mapcontextmenu.MapContextMenu;
import net.osmand.plus.mapcontextmenu.MenuController;
import net.osmand.plus.mapcontextmenu.MenuController.MenuState; import net.osmand.plus.mapcontextmenu.MenuController.MenuState;
import net.osmand.plus.mapcontextmenu.builders.cards.dialogs.ContextMenuCardDialogFragment; import net.osmand.plus.mapcontextmenu.builders.cards.dialogs.ContextMenuCardDialogFragment;
import net.osmand.plus.mapcontextmenu.other.DestinationReachedMenu; import net.osmand.plus.mapcontextmenu.other.DestinationReachedMenu;
@ -192,7 +190,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
private List<DialogProvider> dialogProviders = new ArrayList<>(2); private List<DialogProvider> dialogProviders = new ArrayList<>(2);
private StateChangedListener<ApplicationMode> applicationModeListener; private StateChangedListener<ApplicationMode> applicationModeListener;
private ImportHelper importHelper; private ImportHelper importHelper;
private WakeLockHelper wakeLockHelper;
private boolean intentLocation = false; private boolean intentLocation = false;
private DashboardOnMap dashboardOnMap = new DashboardOnMap(this); private DashboardOnMap dashboardOnMap = new DashboardOnMap(this);
@ -312,7 +309,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
addDialogProvider(mapActions); addDialogProvider(mapActions);
OsmandPlugin.onMapActivityCreate(this); OsmandPlugin.onMapActivityCreate(this);
importHelper = new ImportHelper(this, getMyApplication(), getMapView()); importHelper = new ImportHelper(this, getMyApplication(), getMapView());
wakeLockHelper = new WakeLockHelper(getMyApplication());
if (System.currentTimeMillis() - tm > 50) { if (System.currentTimeMillis() - tm > 50) {
System.err.println("OnCreate for MapActivity took " + (System.currentTimeMillis() - tm) + " ms"); System.err.println("OnCreate for MapActivity took " + (System.currentTimeMillis() - tm) + " ms");
} }
@ -518,15 +514,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
pb.setProgressDrawable(AndroidUtils.createProgressDrawable(bgColor, progressColor)); pb.setProgressDrawable(AndroidUtils.createProgressDrawable(bgColor, progressColor));
} }
private void changeKeyguardFlags() {
if (settings.WAKE_ON_VOICE_INT.get() > 0) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
}
public ImportHelper getImportHelper() { public ImportHelper getImportHelper() {
return importHelper; return importHelper;
} }
@ -673,8 +660,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
setVolumeControlStream(AudioManager.STREAM_MUSIC); setVolumeControlStream(AudioManager.STREAM_MUSIC);
} }
changeKeyguardFlags();
applicationModeListener = new StateChangedListener<ApplicationMode>() { applicationModeListener = new StateChangedListener<ApplicationMode>() {
@Override @Override
public void stateChanged(ApplicationMode change) { public void stateChanged(ApplicationMode change) {
@ -808,14 +793,9 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
getSupportFragmentManager().beginTransaction() getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentContainer, new FirstUsageWelcomeFragment(), .add(R.id.fragmentContainer, new FirstUsageWelcomeFragment(),
FirstUsageWelcomeFragment.TAG).commitAllowingStateLoss(); FirstUsageWelcomeFragment.TAG).commitAllowingStateLoss();
} else if (!isFirstScreenShowing()) { } else if (!isFirstScreenShowing() && OsmLiveCancelledDialog.shouldShowDialog(app)) {
if (XMasDialogFragment.shouldShowXmasDialog(app)) {
SecondSplashScreenFragment.SHOW = false;
new XMasDialogFragment().show(getSupportFragmentManager(), XMasDialogFragment.TAG);
} else if (OsmLiveCancelledDialog.shouldShowDialog(app)) {
OsmLiveCancelledDialog.showInstance(getSupportFragmentManager()); OsmLiveCancelledDialog.showInstance(getSupportFragmentManager());
} }
}
FirstUsageWelcomeFragment.SHOW = false; FirstUsageWelcomeFragment.SHOW = false;
if (SecondSplashScreenFragment.SHOW) { if (SecondSplashScreenFragment.SHOW) {
@ -864,20 +844,26 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
getWindow().setStatusBarColor(ContextCompat.getColor(this, colorId)); getWindow().setStatusBarColor(ContextCompat.getColor(this, colorId));
return; return;
} }
int color = TopToolbarController.NO_COLOR;
boolean mapControlsVisible = findViewById(R.id.MapHudButtonsOverlay).getVisibility() == View.VISIBLE; boolean mapControlsVisible = findViewById(R.id.MapHudButtonsOverlay).getVisibility() == View.VISIBLE;
boolean night = app.getDaynightHelper().isNightModeForMapControls(); boolean night = app.getDaynightHelper().isNightModeForMapControls();
boolean quickSearchTopBar = getTopToolbarController(TopToolbarControllerType.QUICK_SEARCH) != null; TopToolbarController toolbarController = getMapLayers().getMapInfoLayer().getTopToolbarController();
boolean contextMenuTopBar = getTopToolbarController(TopToolbarControllerType.CONTEXT_MENU) != null; if (toolbarController != null && mapControlsVisible) {
color = toolbarController.getStatusBarColor(this, night);
}
if (color == TopToolbarController.NO_COLOR) {
boolean mapTopBar = findViewById(R.id.map_top_bar).getVisibility() == View.VISIBLE; boolean mapTopBar = findViewById(R.id.map_top_bar).getVisibility() == View.VISIBLE;
boolean markerTopBar = findViewById(R.id.map_markers_top_bar).getVisibility() == View.VISIBLE; boolean markerTopBar = findViewById(R.id.map_markers_top_bar).getVisibility() == View.VISIBLE;
if (((quickSearchTopBar || mapTopBar) && mapControlsVisible) || contextMenuTopBar) { if (mapTopBar && mapControlsVisible) {
colorId = night ? R.color.status_bar_route_dark : R.color.status_bar_route_light; colorId = night ? R.color.status_bar_route_dark : R.color.status_bar_route_light;
} else if (markerTopBar && mapControlsVisible) { } else if (markerTopBar && mapControlsVisible) {
colorId = R.color.status_bar_dark; colorId = R.color.status_bar_dark;
} else { } else {
colorId = night ? R.color.status_bar_transparent_dark : R.color.status_bar_transparent_light; colorId = night ? R.color.status_bar_transparent_dark : R.color.status_bar_transparent_light;
} }
getWindow().setStatusBarColor(ContextCompat.getColor(this, colorId)); color = ContextCompat.getColor(this, colorId);
}
getWindow().setStatusBarColor(color);
} }
} }
@ -896,6 +882,12 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
return true; return true;
} }
public void showXMasDialog() {
SecondSplashScreenFragment.SHOW = false;
dismissSecondSplashScreen();
new XMasDialogFragment().show(getSupportFragmentManager(), XMasDialogFragment.TAG);
}
private void dismissSecondSplashScreen() { private void dismissSecondSplashScreen() {
if (SecondSplashScreenFragment.VISIBLE) { if (SecondSplashScreenFragment.VISIBLE) {
SecondSplashScreenFragment.VISIBLE = false; SecondSplashScreenFragment.VISIBLE = false;
@ -1206,7 +1198,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
wakeLockHelper.onStart(this);
getMyApplication().getNotificationHelper().showNotifications(); getMyApplication().getNotificationHelper().showNotifications();
} }
@ -1220,7 +1211,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
@Override @Override
protected void onStop() { protected void onStop() {
wakeLockHelper.onStop(this);
getMyApplication().getNotificationHelper().removeNotifications(); getMyApplication().getNotificationHelper().removeNotifications();
if(pendingPause) { if(pendingPause) {
onPauseActivity(); onPauseActivity();
@ -1305,7 +1295,6 @@ public class MapActivity extends OsmandActionBarActivity implements DownloadEven
} }
public void updateApplicationModeSettings() { public void updateApplicationModeSettings() {
changeKeyguardFlags();
updateMapSettings(); updateMapSettings();
mapViewTrackingUtilities.updateSettings(); mapViewTrackingUtilities.updateSettings();
//app.getRoutingHelper().setAppMode(settings.getApplicationMode()); //app.getRoutingHelper().setAppMode(settings.getApplicationMode());

View file

@ -176,7 +176,7 @@ public class OsmandInAppPurchaseActivity extends AppCompatActivity implements In
@Override @Override
public void onItemPurchased(String sku, boolean active) { public void onItemPurchased(String sku, boolean active) {
if (purchaseHelper != null && purchaseHelper.getSkuLiveUpdates().equals(sku)) { if (purchaseHelper != null && purchaseHelper.getLiveUpdates().containsSku(sku)) {
getMyApplication().logEvent(this, "live_osm_subscription_purchased"); getMyApplication().logEvent(this, "live_osm_subscription_purchased");
if (!active) { if (!active) {

View file

@ -1,7 +1,6 @@
package net.osmand.plus.activities; package net.osmand.plus.activities;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
@ -23,11 +22,9 @@ import android.view.ViewGroup;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.TextView; import android.widget.TextView;
import net.osmand.IndexConstants;
import net.osmand.plus.ApplicationMode; import net.osmand.plus.ApplicationMode;
import net.osmand.plus.ContextMenuAdapter; import net.osmand.plus.ContextMenuAdapter;
import net.osmand.plus.ContextMenuItem; import net.osmand.plus.ContextMenuItem;
import net.osmand.plus.DeviceAdminRecv;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings; import net.osmand.plus.OsmandSettings;
import net.osmand.plus.OsmandSettings.AutoZoomMap; import net.osmand.plus.OsmandSettings.AutoZoomMap;
@ -45,9 +42,7 @@ import net.osmand.router.GeneralRouter.RoutingParameter;
import net.osmand.router.GeneralRouter.RoutingParameterType; import net.osmand.router.GeneralRouter.RoutingParameterType;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -67,9 +62,6 @@ public class SettingsNavigationActivity extends SettingsBaseActivity {
private ListPreference routerServicePreference; private ListPreference routerServicePreference;
private ListPreference speedLimitExceed; private ListPreference speedLimitExceed;
private ComponentName mDeviceAdmin;
private static final int DEVICE_ADMIN_REQUEST = 5;
private List<RoutingParameter> avoidParameters = new ArrayList<RoutingParameter>(); private List<RoutingParameter> avoidParameters = new ArrayList<RoutingParameter>();
private List<RoutingParameter> preferParameters = new ArrayList<RoutingParameter>(); private List<RoutingParameter> preferParameters = new ArrayList<RoutingParameter>();
private List<RoutingParameter> reliefFactorParameters = new ArrayList<RoutingParameter>(); private List<RoutingParameter> reliefFactorParameters = new ArrayList<RoutingParameter>();
@ -88,41 +80,6 @@ public class SettingsNavigationActivity extends SettingsBaseActivity {
createUI(); createUI();
} }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == DEVICE_ADMIN_REQUEST) {
if (resultCode == RESULT_OK) {
// Log.d("DeviceAdmin", "Lock screen permission approved.");
} else {
settings.WAKE_ON_VOICE_INT.set(0);
// Log.d("DeviceAdmin", "Lock screen permission refused.");
}
return;
}
}
private void requestLockScreenAdmin() {
mDeviceAdmin = new ComponentName(getApplicationContext(),
DeviceAdminRecv.class);
DevicePolicyManager mDevicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
if (!mDevicePolicyManager.isAdminActive(mDeviceAdmin)) {
// request permission from user
Intent intent = new Intent(
DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
mDeviceAdmin);
intent.putExtra(
DevicePolicyManager.EXTRA_ADD_EXPLANATION,
getString(R.string.lock_screen_request_explanation,
Version.getAppName(getMyApplication())));
startActivityForResult(intent, DEVICE_ADMIN_REQUEST);
}
};
private void createUI() { private void createUI() {
addPreferencesFromResource(R.xml.navigation_settings); addPreferencesFromResource(R.xml.navigation_settings);
PreferenceScreen screen = getPreferenceScreen(); PreferenceScreen screen = getPreferenceScreen();
@ -176,8 +133,6 @@ public class SettingsNavigationActivity extends SettingsBaseActivity {
screenPowerSaveNames[i] = screenPowerSaveValues[i] + " " screenPowerSaveNames[i] = screenPowerSaveValues[i] + " "
+ getString(R.string.int_seconds); + getString(R.string.int_seconds);
} }
registerListPreference(settings.WAKE_ON_VOICE_INT, screen, screenPowerSaveNames, screenPowerSaveValues);
// registerBooleanPreference(settings.SHOW_ZOOM_BUTTONS_NAVIGATION, screen); // registerBooleanPreference(settings.SHOW_ZOOM_BUTTONS_NAVIGATION, screen);
showAlarms = (Preference) screen.findPreference("show_routing_alarms"); showAlarms = (Preference) screen.findPreference("show_routing_alarms");
@ -449,16 +404,6 @@ public class SettingsNavigationActivity extends SettingsBaseActivity {
+ settings.ROUTER_SERVICE.get() + "]"); + settings.ROUTER_SERVICE.get() + "]");
prepareRoutingPrefs(getPreferenceScreen()); prepareRoutingPrefs(getPreferenceScreen());
super.updateAllSettings(); super.updateAllSettings();
} else if (id.equals(settings.WAKE_ON_VOICE_INT.getId())) {
Integer value;
try {
value = Integer.parseInt(newValue.toString());
} catch (NumberFormatException e) {
value = 0;
}
if (value > 0) {
requestLockScreenAdmin();
}
} }
return true; return true;
} }

View file

@ -203,8 +203,7 @@ public class MapViewTrackingUtilities implements OsmAndLocationListener, IMapLoc
showViewAngle = routePlanningMode; // disable compass rotation in that mode showViewAngle = routePlanningMode; // disable compass rotation in that mode
} }
registerUnregisterSensor(location, smallSpeedForDirectionOfMovement); registerUnregisterSensor(location, smallSpeedForDirectionOfMovement);
if (settings.ANIMATE_MY_LOCATION.get() && !smallSpeedForAnimation && !movingToMyLocation && if (settings.ANIMATE_MY_LOCATION.get() && !smallSpeedForAnimation && !movingToMyLocation) {
settings.WAKE_ON_VOICE_INT.get() == 0) {
mapView.getAnimatedDraggingThread().startMoving( mapView.getAnimatedDraggingThread().startMoving(
location.getLatitude(), location.getLongitude(), zoom, rotation, false); location.getLatitude(), location.getLongitude(), zoom, rotation, false);
} else { } else {

View file

@ -1,9 +1,12 @@
package net.osmand.plus.chooseplan; package net.osmand.plus.chooseplan;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.Dialog; import android.app.Dialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.ColorRes; import android.support.annotation.ColorRes;
@ -25,6 +28,7 @@ import android.view.Window;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import net.osmand.AndroidUtils; import net.osmand.AndroidUtils;
import net.osmand.PlatformUtil; import net.osmand.PlatformUtil;
@ -39,11 +43,17 @@ import net.osmand.plus.download.DownloadValidationManager;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseListener; import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseListener;
import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseTaskType; import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseTaskType;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase;
import net.osmand.plus.inapp.InAppPurchases.InAppSubscription;
import net.osmand.plus.liveupdates.SubscriptionFragment;
import net.osmand.plus.srtmplugin.SRTMPlugin; import net.osmand.plus.srtmplugin.SRTMPlugin;
import net.osmand.plus.widgets.TextViewEx; import net.osmand.plus.widgets.TextViewEx;
import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import java.util.List;
public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment implements InAppPurchaseListener { public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment implements InAppPurchaseListener {
public static final String TAG = ChoosePlanDialogFragment.class.getSimpleName(); public static final String TAG = ChoosePlanDialogFragment.class.getSimpleName();
private static final Log LOG = PlatformUtil.getLog(ChoosePlanDialogFragment.class); private static final Log LOG = PlatformUtil.getLog(ChoosePlanDialogFragment.class);
@ -53,34 +63,42 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
private boolean nightMode; private boolean nightMode;
private View osmLiveCardButton; private ViewGroup osmLiveCardButtonsContainer;
private ProgressBar osmLiveCardProgress;
private View planTypeCardButton; private View planTypeCardButton;
private View planTypeCardButtonDisabled;
public interface ChoosePlanDialogListener { public interface ChoosePlanDialogListener {
void onChoosePlanDialogDismiss(); void onChoosePlanDialogDismiss();
} }
public enum OsmAndFeature { public enum OsmAndFeature {
WIKIVOYAGE_OFFLINE(R.string.wikivoyage_offline), WIKIVOYAGE_OFFLINE(R.string.wikivoyage_offline, R.drawable.ic_action_explore),
DAILY_MAP_UPDATES(R.string.daily_map_updates), DAILY_MAP_UPDATES(R.string.daily_map_updates, R.drawable.ic_action_time_span),
MONTHLY_MAP_UPDATES(R.string.monthly_map_updates), MONTHLY_MAP_UPDATES(R.string.monthly_map_updates, R.drawable.ic_action_sand_clock),
UNLIMITED_DOWNLOADS(R.string.unlimited_downloads), UNLIMITED_DOWNLOADS(R.string.unlimited_downloads, R.drawable.ic_action_unlimited_download),
WIKIPEDIA_OFFLINE(R.string.wikipedia_offline), WIKIPEDIA_OFFLINE(R.string.wikipedia_offline, R.drawable.ic_plugin_wikipedia),
CONTOUR_LINES_HILLSHADE_MAPS(R.string.contour_lines_hillshade_maps), CONTOUR_LINES_HILLSHADE_MAPS(R.string.contour_lines_hillshade_maps, R.drawable.ic_plugin_srtm),
SEA_DEPTH_MAPS(R.string.index_item_depth_contours_osmand_ext), SEA_DEPTH_MAPS(R.string.index_item_depth_contours_osmand_ext, R.drawable.ic_action_nautical_depth),
UNLOCK_ALL_FEATURES(R.string.unlock_all_features), UNLOCK_ALL_FEATURES(R.string.unlock_all_features, R.drawable.ic_action_osmand_logo),
DONATION_TO_OSM(R.string.donation_to_osm); DONATION_TO_OSM(R.string.donation_to_osm, 0);
private final int key; private final int key;
private final int iconId;
OsmAndFeature(int key) { OsmAndFeature(int key, int iconId) {
this.key = key; this.key = key;
this.iconId = iconId;
} }
public String toHumanString(Context ctx) { public String toHumanString(Context ctx) {
return ctx.getString(key); return ctx.getString(key);
} }
public int getIconId() {
return iconId;
}
public boolean isFeaturePurchased(OsmandApplication ctx) { public boolean isFeaturePurchased(OsmandApplication ctx) {
if (InAppPurchaseHelper.isSubscribedToLiveUpdates(ctx)) { if (InAppPurchaseHelper.isSubscribedToLiveUpdates(ctx)) {
return true; return true;
@ -205,7 +223,7 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog); super.onDismiss(dialog);
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null && activity instanceof ChoosePlanDialogListener) { if (activity instanceof ChoosePlanDialogListener) {
((ChoosePlanDialogListener) activity).onChoosePlanDialogDismiss(); ((ChoosePlanDialogListener) activity).onChoosePlanDialogDismiss();
} }
} }
@ -239,12 +257,25 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
public abstract String getPlanTypeHeaderDescription(); public abstract String getPlanTypeHeaderDescription();
public abstract String getPlanTypeButtonTitle(); public String getPlanTypeButtonTitle() {
InAppPurchase purchase = getPlanTypePurchase();
if (purchase != null) {
if (purchase.isPurchased()) {
return purchase.getPrice(getContext());
} else {
return getString(R.string.purchase_unlim_title, purchase.getPrice(getContext()));
}
}
return "";
}
public abstract String getPlanTypeButtonDescription(); public abstract String getPlanTypeButtonDescription();
public abstract void setPlanTypeButtonClickListener(View button); public abstract void setPlanTypeButtonClickListener(View button);
@Nullable
public abstract InAppPurchase getPlanTypePurchase();
private View inflate(@LayoutRes int layoutId, @Nullable ViewGroup container) { private View inflate(@LayoutRes int layoutId, @Nullable ViewGroup container) {
int themeRes = nightMode ? R.style.OsmandDarkTheme_DarkActionbar : R.style.OsmandLightTheme_DarkActionbar_LightStatusBar; int themeRes = nightMode ? R.style.OsmandDarkTheme_DarkActionbar : R.style.OsmandLightTheme_DarkActionbar_LightStatusBar;
return LayoutInflater.from(new ContextThemeWrapper(getContext(), themeRes)) return LayoutInflater.from(new ContextThemeWrapper(getContext(), themeRes))
@ -252,7 +283,7 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
} }
private ViewGroup buildOsmLiveCard(@NonNull Context ctx, ViewGroup container) { private ViewGroup buildOsmLiveCard(@NonNull Context ctx, ViewGroup container) {
ViewGroup cardView = (ViewGroup) inflate(R.layout.purchase_dialog_active_card, container); ViewGroup cardView = (ViewGroup) inflate(R.layout.purchase_dialog_osm_live_card, container);
TextView headerTitle = (TextView) cardView.findViewById(R.id.header_title); TextView headerTitle = (TextView) cardView.findViewById(R.id.header_title);
TextView headerDescr = (TextView) cardView.findViewById(R.id.header_descr); TextView headerDescr = (TextView) cardView.findViewById(R.id.header_descr);
headerTitle.setText(R.string.osm_live); headerTitle.setText(R.string.osm_live);
@ -269,6 +300,7 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
imgView.setVisibility(View.GONE); imgView.setVisibility(View.GONE);
imgPurchasedView.setVisibility(View.VISIBLE); imgPurchasedView.setVisibility(View.VISIBLE);
} else { } else {
imgView.setImageResource(feature.getIconId());
imgView.setVisibility(View.VISIBLE); imgView.setVisibility(View.VISIBLE);
imgPurchasedView.setVisibility(View.GONE); imgPurchasedView.setVisibility(View.GONE);
} }
@ -283,55 +315,229 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
if (featureRowDiv != null) { if (featureRowDiv != null) {
featureRowDiv.setVisibility(View.GONE); featureRowDiv.setVisibility(View.GONE);
} }
TextViewEx cardDescription = (TextViewEx) cardView.findViewById(R.id.card_descr);
cardDescription.setText(R.string.osm_live_payment_desc);
osmLiveCardButton = cardView.findViewById(R.id.card_button);
osmLiveCardButtonsContainer = (ViewGroup) cardView.findViewById(R.id.card_buttons_container);
osmLiveCardProgress = (ProgressBar) cardView.findViewById(R.id.card_progress);
if (osmLiveCardProgress != null) {
int color = ContextCompat.getColor(ctx, nightMode ? R.color.wikivoyage_active_dark : R.color.wikivoyage_active_light);
osmLiveCardProgress.getIndeterminateDrawable().setColorFilter(color, android.graphics.PorterDuff.Mode.MULTIPLY);
}
return cardView; return cardView;
} }
private void setupOsmLiveCardButton(boolean progress) { @SuppressLint("CutPasteId")
if (osmLiveCardButton != null) { private void setupOsmLiveCardButtons(boolean progress) {
ProgressBar progressBar = (ProgressBar) osmLiveCardButton.findViewById(R.id.card_button_progress); final Context ctx = getContext();
TextViewEx buttonTitle = (TextViewEx) osmLiveCardButton.findViewById(R.id.card_button_title); if (ctx == null) {
TextViewEx buttonSubtitle = (TextViewEx) osmLiveCardButton.findViewById(R.id.card_button_subtitle); return;
if (purchaseHelper == null || !purchaseHelper.hasPrices()) {
buttonTitle.setText(getString(R.string.purchase_subscription_title, getString(R.string.osm_live_default_price)));
} else {
buttonTitle.setText(getString(R.string.purchase_subscription_title, purchaseHelper.getLiveUpdatesPrice()));
} }
buttonSubtitle.setText(R.string.osm_live_month_cost_desc);
if (progress) { if (progress) {
buttonTitle.setVisibility(View.GONE); if (osmLiveCardButtonsContainer != null) {
buttonSubtitle.setVisibility(View.GONE); osmLiveCardButtonsContainer.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE); }
osmLiveCardButton.setOnClickListener(null); if (osmLiveCardProgress != null) {
} else { osmLiveCardProgress.setVisibility(View.VISIBLE);
buttonTitle.setVisibility(View.VISIBLE); }
buttonSubtitle.setVisibility(View.VISIBLE); } else if (osmLiveCardButtonsContainer != null) {
progressBar.setVisibility(View.GONE); osmLiveCardButtonsContainer.removeAllViews();
osmLiveCardButton.setOnClickListener(new OnClickListener() { View lastBtn = null;
InAppSubscription monthlyLiveUpdates = purchaseHelper.getMonthlyLiveUpdates();
double regularMonthlyPrice = monthlyLiveUpdates.getPriceValue();
List<InAppSubscription> visibleSubscriptions = purchaseHelper.getLiveUpdates().getVisibleSubscriptions();
boolean anyPurchased = false;
for (final InAppSubscription s : visibleSubscriptions) {
if (s.isPurchased()) {
anyPurchased = true;
break;
}
}
for (final InAppSubscription s : visibleSubscriptions) {
if (s.isPurchased()) {
View buttonPurchased = inflate(R.layout.purchase_dialog_card_button_active_ex, osmLiveCardButtonsContainer);
View buttonContainer = buttonPurchased.findViewById(R.id.button_container);
TextViewEx title = (TextViewEx) buttonPurchased.findViewById(R.id.title);
TextViewEx description = (TextViewEx) buttonPurchased.findViewById(R.id.description);
TextViewEx buttonTitle = (TextViewEx) buttonPurchased.findViewById(R.id.button_title);
View buttonView = buttonPurchased.findViewById(R.id.button_view);
View buttonCancelView = buttonPurchased.findViewById(R.id.button_cancel_view);
View divTop = buttonPurchased.findViewById(R.id.div_top);
View divBottom = buttonPurchased.findViewById(R.id.div_bottom);
View div = buttonPurchased.findViewById(R.id.div);
title.setText(s.getTitle(ctx));
description.setText(s.getDescription(ctx));
buttonTitle.setText(s.getPrice(ctx));
buttonView.setVisibility(View.VISIBLE);
buttonCancelView.setVisibility(View.GONE);
buttonPurchased.setOnClickListener(null);
divTop.setVisibility(View.VISIBLE);
div.setVisibility(View.VISIBLE);
divBottom.setVisibility(View.GONE);
if (s.isDonationSupported()) {
buttonPurchased.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
subscript(); showDonationSettings();
dismiss();
}
});
} else {
buttonPurchased.setOnClickListener(null);
}
osmLiveCardButtonsContainer.addView(buttonPurchased);
View buttonCancel = inflate(R.layout.purchase_dialog_card_button_active_ex, osmLiveCardButtonsContainer);
buttonContainer = buttonCancel.findViewById(R.id.button_container);
title = (TextViewEx) buttonCancel.findViewById(R.id.title);
description = (TextViewEx) buttonCancel.findViewById(R.id.description);
buttonView = buttonCancel.findViewById(R.id.button_view);
buttonCancelView = buttonCancel.findViewById(R.id.button_cancel_view);
divTop = buttonCancel.findViewById(R.id.div_top);
divBottom = buttonCancel.findViewById(R.id.div_bottom);
div = buttonCancel.findViewById(R.id.div);
title.setText(getString(R.string.osm_live_payment_current_subscription));
description.setText(s.getRenewDescription(ctx));
buttonView.setVisibility(View.GONE);
buttonCancelView.setVisibility(View.VISIBLE);
buttonCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
manageSubscription(ctx, s.getSku());
}
});
divTop.setVisibility(View.GONE);
div.setVisibility(View.GONE);
divBottom.setVisibility(View.VISIBLE);
osmLiveCardButtonsContainer.addView(buttonCancel);
if (lastBtn != null) {
View lastBtnDiv = lastBtn.findViewById(R.id.div);
if (lastBtnDiv != null) {
lastBtnDiv.setVisibility(View.GONE);
}
View lastBtnDivBottom = lastBtn.findViewById(R.id.div_bottom);
if (lastBtnDivBottom != null) {
lastBtnDivBottom.setVisibility(View.GONE);
}
}
lastBtn = buttonCancel;
} else {
View button = inflate(R.layout.purchase_dialog_card_button_ex, osmLiveCardButtonsContainer);
TextViewEx title = (TextViewEx) button.findViewById(R.id.title);
TextViewEx description = (TextViewEx) button.findViewById(R.id.description);
View buttonView = button.findViewById(R.id.button_view);
View buttonExView = button.findViewById(R.id.button_ex_view);
TextViewEx buttonTitle = (TextViewEx) button.findViewById(R.id.button_title);
TextViewEx buttonExTitle = (TextViewEx) button.findViewById(R.id.button_ex_title);
buttonView.setVisibility(anyPurchased ? View.VISIBLE : View.GONE);
buttonExView.setVisibility(!anyPurchased ? View.VISIBLE : View.GONE);
TextViewEx discountRegular = (TextViewEx) button.findViewById(R.id.discount_banner_regular);
TextViewEx discountActive = (TextViewEx) button.findViewById(R.id.discount_banner_active);
View div = button.findViewById(R.id.div);
title.setText(s.getTitle(ctx));
description.setText(s.getDescription(ctx));
buttonTitle.setText(s.getPrice(ctx));
buttonExTitle.setText(s.getPrice(ctx));
if (regularMonthlyPrice > 0 && s.getMonthlyPriceValue() > 0 && s.getMonthlyPriceValue() < regularMonthlyPrice) {
int discount = (int) ((1 - s.getMonthlyPriceValue() / regularMonthlyPrice) * 100d);
String discountStr = discount + "%";
if (discount > 50) {
discountActive.setText(String.format(" %s ", getString(R.string.osm_live_payment_discount_descr, discountStr)));
discountActive.setVisibility(View.VISIBLE);
discountRegular.setVisibility(View.GONE);
} else if (discount > 0) {
discountActive.setVisibility(View.GONE);
discountRegular.setText(String.format(" %s ", getString(R.string.osm_live_payment_discount_descr, discountStr)));
discountRegular.setVisibility(View.VISIBLE);
} else {
discountActive.setVisibility(View.GONE);
discountRegular.setVisibility(View.GONE);
}
} else {
discountActive.setVisibility(View.GONE);
discountRegular.setVisibility(View.GONE);
}
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
subscribe(s.getSku());
}
});
if (anyPurchased) {
buttonView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
subscribe(s.getSku());
}
});
} else {
buttonExView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
subscribe(s.getSku());
} }
}); });
} }
div.setVisibility(View.VISIBLE);
osmLiveCardButtonsContainer.addView(button);
lastBtn = button;
}
}
if (lastBtn != null) {
View div = lastBtn.findViewById(R.id.div);
if (div != null) {
div.setVisibility(View.GONE);
}
View divBottom = lastBtn.findViewById(R.id.div_bottom);
if (divBottom != null) {
divBottom.setVisibility(View.GONE);
}
}
if (osmLiveCardProgress != null) {
osmLiveCardProgress.setVisibility(View.GONE);
}
osmLiveCardButtonsContainer.setVisibility(View.VISIBLE);
} }
} }
private void subscript() { private void showDonationSettings() {
FragmentActivity activity = getActivity();
if (activity != null) {
SubscriptionFragment subscriptionFragment = new SubscriptionFragment();
subscriptionFragment.show(activity.getSupportFragmentManager(), SubscriptionFragment.TAG);
}
}
private void subscribe(String sku) {
if (!app.getSettings().isInternetConnectionAvailable(true)) {
Toast.makeText(app, R.string.internet_not_available, Toast.LENGTH_LONG).show();
} else {
FragmentActivity ctx = getActivity(); FragmentActivity ctx = getActivity();
if (ctx != null && purchaseHelper != null) { if (ctx != null && purchaseHelper != null) {
OsmandSettings settings = app.getSettings(); OsmandSettings settings = app.getSettings();
purchaseHelper.purchaseLiveUpdates(ctx, purchaseHelper.purchaseLiveUpdates(ctx, sku,
settings.BILLING_USER_EMAIL.get(), settings.BILLING_USER_EMAIL.get(),
settings.BILLING_USER_NAME.get(), settings.BILLING_USER_NAME.get(),
settings.BILLING_USER_COUNTRY_DOWNLOAD_NAME.get(), settings.BILLING_USER_COUNTRY_DOWNLOAD_NAME.get(),
settings.BILLING_HIDE_USER_NAME.get()); settings.BILLING_HIDE_USER_NAME.get());
} }
} }
}
private void manageSubscription(@NonNull Context ctx, @Nullable String sku) {
String url = "https://play.google.com/store/account/subscriptions?package=" + ctx.getPackageName();
if (!Algorithms.isEmpty(sku)) {
url += "&sku=" + sku;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
private ViewGroup buildPlanTypeCard(@NonNull Context ctx, ViewGroup container) { private ViewGroup buildPlanTypeCard(@NonNull Context ctx, ViewGroup container) {
if (getPlanTypeFeatures().length == 0) { if (getPlanTypeFeatures().length == 0) {
@ -366,6 +572,7 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
imgView.setVisibility(View.GONE); imgView.setVisibility(View.GONE);
imgPurchasedView.setVisibility(View.VISIBLE); imgPurchasedView.setVisibility(View.VISIBLE);
} else { } else {
imgView.setImageResource(feature.getIconId());
imgView.setVisibility(View.VISIBLE); imgView.setVisibility(View.VISIBLE);
imgPurchasedView.setVisibility(View.GONE); imgPurchasedView.setVisibility(View.GONE);
} }
@ -380,27 +587,44 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
cardDescription.setText(R.string.in_app_purchase_desc_ex); cardDescription.setText(R.string.in_app_purchase_desc_ex);
planTypeCardButton = cardView.findViewById(R.id.card_button); planTypeCardButton = cardView.findViewById(R.id.card_button);
planTypeCardButtonDisabled = cardView.findViewById(R.id.card_button_disabled);
return cardView; return cardView;
} }
private void setupPlanTypeCardButton(boolean progress) { private void setupPlanTypeCardButtons(boolean progress) {
if (planTypeCardButton != null) { if (planTypeCardButton != null && planTypeCardButtonDisabled != null) {
InAppPurchase purchase = getPlanTypePurchase();
boolean purchased = purchase != null && purchase.isPurchased();
ProgressBar progressBar = (ProgressBar) planTypeCardButton.findViewById(R.id.card_button_progress); ProgressBar progressBar = (ProgressBar) planTypeCardButton.findViewById(R.id.card_button_progress);
TextViewEx buttonTitle = (TextViewEx) planTypeCardButton.findViewById(R.id.card_button_title); TextViewEx buttonTitle = (TextViewEx) planTypeCardButton.findViewById(R.id.card_button_title);
TextViewEx buttonSubtitle = (TextViewEx) planTypeCardButton.findViewById(R.id.card_button_subtitle); TextViewEx buttonSubtitle = (TextViewEx) planTypeCardButton.findViewById(R.id.card_button_subtitle);
buttonTitle.setText(getPlanTypeButtonTitle()); buttonTitle.setText(getPlanTypeButtonTitle());
buttonSubtitle.setText(getPlanTypeButtonDescription()); buttonSubtitle.setText(getPlanTypeButtonDescription());
if (progress) { if (progress) {
planTypeCardButton.setVisibility(View.VISIBLE);
planTypeCardButtonDisabled.setVisibility(View.GONE);
buttonTitle.setVisibility(View.GONE); buttonTitle.setVisibility(View.GONE);
buttonSubtitle.setVisibility(View.GONE); buttonSubtitle.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE);
planTypeCardButton.setOnClickListener(null); planTypeCardButton.setOnClickListener(null);
} else { } else {
if (!purchased) {
planTypeCardButton.setVisibility(View.VISIBLE);
planTypeCardButtonDisabled.setVisibility(View.GONE);
buttonTitle.setVisibility(View.VISIBLE); buttonTitle.setVisibility(View.VISIBLE);
buttonSubtitle.setVisibility(View.VISIBLE); buttonSubtitle.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE); progressBar.setVisibility(View.GONE);
setPlanTypeButtonClickListener(planTypeCardButton); setPlanTypeButtonClickListener(planTypeCardButton);
} else {
planTypeCardButton.setVisibility(View.GONE);
planTypeCardButtonDisabled.setVisibility(View.VISIBLE);
buttonTitle = (TextViewEx) planTypeCardButtonDisabled.findViewById(R.id.card_button_title);
buttonSubtitle = (TextViewEx) planTypeCardButtonDisabled.findViewById(R.id.card_button_subtitle);
buttonTitle.setText(getPlanTypeButtonTitle());
buttonSubtitle.setText(getPlanTypeButtonDescription());
}
} }
} }
} }
@ -408,7 +632,7 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
@Nullable @Nullable
public MapActivity getMapActivity() { public MapActivity getMapActivity() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null && activity instanceof MapActivity) { if (activity instanceof MapActivity) {
return (MapActivity) activity; return (MapActivity) activity;
} }
return null; return null;
@ -424,11 +648,11 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
} }
boolean requestingInventory = purchaseHelper != null && purchaseHelper.getActiveTask() == InAppPurchaseTaskType.REQUEST_INVENTORY; boolean requestingInventory = purchaseHelper != null && purchaseHelper.getActiveTask() == InAppPurchaseTaskType.REQUEST_INVENTORY;
if (osmLiveCardButton != null) { if (osmLiveCardButtonsContainer != null) {
setupOsmLiveCardButton(requestingInventory); setupOsmLiveCardButtons(requestingInventory);
} }
if (planTypeCardButton != null) { if (planTypeCardButton != null) {
setupPlanTypeCardButton(requestingInventory); setupPlanTypeCardButtons(requestingInventory);
} }
} }
@ -445,8 +669,8 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
@Override @Override
public void onError(InAppPurchaseTaskType taskType, String error) { public void onError(InAppPurchaseTaskType taskType, String error) {
if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) { if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) {
setupOsmLiveCardButton(false); setupOsmLiveCardButtons(false);
setupPlanTypeCardButton(false); setupPlanTypeCardButtons(false);
} }
} }
@ -456,22 +680,28 @@ public abstract class ChoosePlanDialogFragment extends BaseOsmAndDialogFragment
@Override @Override
public void onItemPurchased(String sku, boolean active) { public void onItemPurchased(String sku, boolean active) {
if (purchaseHelper != null) {
InAppSubscription s = purchaseHelper.getLiveUpdates().getSubscriptionBySku(sku);
if (s != null && s.isDonationSupported()) {
showDonationSettings();
}
}
dismiss(); dismiss();
} }
@Override @Override
public void showProgress(InAppPurchaseTaskType taskType) { public void showProgress(InAppPurchaseTaskType taskType) {
if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) { if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) {
setupOsmLiveCardButton(true); setupOsmLiveCardButtons(true);
setupPlanTypeCardButton(true); setupPlanTypeCardButtons(true);
} }
} }
@Override @Override
public void dismissProgress(InAppPurchaseTaskType taskType) { public void dismissProgress(InAppPurchaseTaskType taskType) {
if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) { if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) {
setupOsmLiveCardButton(false); setupOsmLiveCardButtons(false);
setupPlanTypeCardButton(false); setupPlanTypeCardButtons(false);
} }
} }

View file

@ -1,12 +1,14 @@
package net.osmand.plus.chooseplan; package net.osmand.plus.chooseplan;
import android.app.Activity; import android.app.Activity;
import android.support.annotation.Nullable;
import android.view.View; import android.view.View;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandInAppPurchaseActivity; import net.osmand.plus.activities.OsmandInAppPurchaseActivity;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase;
public class ChoosePlanFreeBannerDialogFragment extends ChoosePlanDialogFragment { public class ChoosePlanFreeBannerDialogFragment extends ChoosePlanDialogFragment {
public static final String TAG = ChoosePlanFreeBannerDialogFragment.class.getSimpleName(); public static final String TAG = ChoosePlanFreeBannerDialogFragment.class.getSimpleName();
@ -19,7 +21,6 @@ public class ChoosePlanFreeBannerDialogFragment extends ChoosePlanDialogFragment
OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS, OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS,
OsmAndFeature.SEA_DEPTH_MAPS, OsmAndFeature.SEA_DEPTH_MAPS,
OsmAndFeature.UNLOCK_ALL_FEATURES, OsmAndFeature.UNLOCK_ALL_FEATURES,
OsmAndFeature.DONATION_TO_OSM,
}; };
private final OsmAndFeature[] selectedOsmLiveFeatures = { private final OsmAndFeature[] selectedOsmLiveFeatures = {
OsmAndFeature.DAILY_MAP_UPDATES, OsmAndFeature.DAILY_MAP_UPDATES,
@ -73,16 +74,6 @@ public class ChoosePlanFreeBannerDialogFragment extends ChoosePlanDialogFragment
} }
} }
@Override
public String getPlanTypeButtonTitle() {
InAppPurchaseHelper purchaseHelper = getOsmandApplication().getInAppPurchaseHelper();
if (purchaseHelper == null || !purchaseHelper.hasPrices()) {
return getString(R.string.purchase_unlim_title, getString(R.string.full_version_price));
} else {
return getString(R.string.purchase_unlim_title, purchaseHelper.getFullVersionPrice());
}
}
@Override @Override
public String getPlanTypeButtonDescription() { public String getPlanTypeButtonDescription() {
return getString(R.string.in_app_purchase_desc); return getString(R.string.in_app_purchase_desc);
@ -107,4 +98,14 @@ public class ChoosePlanFreeBannerDialogFragment extends ChoosePlanDialogFragment
} }
}); });
} }
@Nullable
@Override
public InAppPurchase getPlanTypePurchase() {
InAppPurchaseHelper purchaseHelper = getOsmandApplication().getInAppPurchaseHelper();
if (purchaseHelper != null) {
return purchaseHelper.getFullVersion();
}
return null;
}
} }

View file

@ -1,11 +1,13 @@
package net.osmand.plus.chooseplan; package net.osmand.plus.chooseplan;
import android.app.Activity; import android.app.Activity;
import android.support.annotation.Nullable;
import android.view.View; import android.view.View;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandInAppPurchaseActivity; import net.osmand.plus.activities.OsmandInAppPurchaseActivity;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase;
public class ChoosePlanHillshadeSrtmDialogFragment extends ChoosePlanDialogFragment { public class ChoosePlanHillshadeSrtmDialogFragment extends ChoosePlanDialogFragment {
public static final String TAG = ChoosePlanHillshadeSrtmDialogFragment.class.getSimpleName(); public static final String TAG = ChoosePlanHillshadeSrtmDialogFragment.class.getSimpleName();
@ -18,7 +20,6 @@ public class ChoosePlanHillshadeSrtmDialogFragment extends ChoosePlanDialogFragm
OsmAndFeature.WIKIPEDIA_OFFLINE, OsmAndFeature.WIKIPEDIA_OFFLINE,
OsmAndFeature.WIKIVOYAGE_OFFLINE, OsmAndFeature.WIKIVOYAGE_OFFLINE,
OsmAndFeature.UNLOCK_ALL_FEATURES, OsmAndFeature.UNLOCK_ALL_FEATURES,
OsmAndFeature.DONATION_TO_OSM,
}; };
private final OsmAndFeature[] selectedOsmLiveFeatures = { private final OsmAndFeature[] selectedOsmLiveFeatures = {
OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS, OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS,
@ -65,16 +66,6 @@ public class ChoosePlanHillshadeSrtmDialogFragment extends ChoosePlanDialogFragm
return getString(R.string.paid_plugin); return getString(R.string.paid_plugin);
} }
@Override
public String getPlanTypeButtonTitle() {
InAppPurchaseHelper purchaseHelper = getOsmandApplication().getInAppPurchaseHelper();
if (purchaseHelper == null || !purchaseHelper.hasPrices()) {
return getString(R.string.purchase_unlim_title, getString(R.string.srtm_plugin_price));
} else {
return getString(R.string.purchase_unlim_title, purchaseHelper.getContourLinesPrice());
}
}
@Override @Override
public String getPlanTypeButtonDescription() { public String getPlanTypeButtonDescription() {
return getString(R.string.in_app_purchase_desc); return getString(R.string.in_app_purchase_desc);
@ -93,4 +84,14 @@ public class ChoosePlanHillshadeSrtmDialogFragment extends ChoosePlanDialogFragm
} }
}); });
} }
@Nullable
@Override
public InAppPurchase getPlanTypePurchase() {
InAppPurchaseHelper purchaseHelper = getOsmandApplication().getInAppPurchaseHelper();
if (purchaseHelper != null) {
return purchaseHelper.getContourLines();
}
return null;
}
} }

View file

@ -1,11 +1,13 @@
package net.osmand.plus.chooseplan; package net.osmand.plus.chooseplan;
import android.app.Activity; import android.app.Activity;
import android.support.annotation.Nullable;
import android.view.View; import android.view.View;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.OsmandInAppPurchaseActivity; import net.osmand.plus.activities.OsmandInAppPurchaseActivity;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase;
public class ChoosePlanSeaDepthMapsDialogFragment extends ChoosePlanDialogFragment { public class ChoosePlanSeaDepthMapsDialogFragment extends ChoosePlanDialogFragment {
public static final String TAG = ChoosePlanSeaDepthMapsDialogFragment.class.getSimpleName(); public static final String TAG = ChoosePlanSeaDepthMapsDialogFragment.class.getSimpleName();
@ -18,7 +20,6 @@ public class ChoosePlanSeaDepthMapsDialogFragment extends ChoosePlanDialogFragme
OsmAndFeature.DAILY_MAP_UPDATES, OsmAndFeature.DAILY_MAP_UPDATES,
OsmAndFeature.UNLIMITED_DOWNLOADS, OsmAndFeature.UNLIMITED_DOWNLOADS,
OsmAndFeature.UNLOCK_ALL_FEATURES, OsmAndFeature.UNLOCK_ALL_FEATURES,
OsmAndFeature.DONATION_TO_OSM,
}; };
private final OsmAndFeature[] selectedOsmLiveFeatures = { private final OsmAndFeature[] selectedOsmLiveFeatures = {
OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS, OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS,
@ -65,16 +66,6 @@ public class ChoosePlanSeaDepthMapsDialogFragment extends ChoosePlanDialogFragme
return getString(R.string.in_app_purchase); return getString(R.string.in_app_purchase);
} }
@Override
public String getPlanTypeButtonTitle() {
InAppPurchaseHelper purchaseHelper = getOsmandApplication().getInAppPurchaseHelper();
if (purchaseHelper == null || !purchaseHelper.hasPrices()) {
return getString(R.string.purchase_unlim_title, getString(R.string.sea_depth_maps_price));
} else {
return getString(R.string.purchase_unlim_title, purchaseHelper.getDepthContoursPrice());
}
}
@Override @Override
public String getPlanTypeButtonDescription() { public String getPlanTypeButtonDescription() {
return getString(R.string.in_app_purchase_desc); return getString(R.string.in_app_purchase_desc);
@ -92,4 +83,14 @@ public class ChoosePlanSeaDepthMapsDialogFragment extends ChoosePlanDialogFragme
} }
}); });
} }
@Nullable
@Override
public InAppPurchase getPlanTypePurchase() {
InAppPurchaseHelper purchaseHelper = getOsmandApplication().getInAppPurchaseHelper();
if (purchaseHelper != null) {
return purchaseHelper.getDepthContours();
}
return null;
}
} }

View file

@ -11,7 +11,6 @@ public class ChoosePlanWikipediaDialogFragment extends ChoosePlanFreeBannerDialo
OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS, OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS,
OsmAndFeature.SEA_DEPTH_MAPS, OsmAndFeature.SEA_DEPTH_MAPS,
OsmAndFeature.UNLOCK_ALL_FEATURES, OsmAndFeature.UNLOCK_ALL_FEATURES,
OsmAndFeature.DONATION_TO_OSM,
}; };
private final OsmAndFeature[] selectedOsmLiveFeatures = { private final OsmAndFeature[] selectedOsmLiveFeatures = {
OsmAndFeature.WIKIPEDIA_OFFLINE, OsmAndFeature.WIKIPEDIA_OFFLINE,

View file

@ -8,7 +8,6 @@ import android.graphics.drawable.ColorDrawable;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.ColorRes; import android.support.annotation.ColorRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentActivity;
@ -56,7 +55,6 @@ public class OsmLiveCancelledDialog extends BaseOsmAndDialogFragment implements
OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS, OsmAndFeature.CONTOUR_LINES_HILLSHADE_MAPS,
OsmAndFeature.SEA_DEPTH_MAPS, OsmAndFeature.SEA_DEPTH_MAPS,
OsmAndFeature.UNLOCK_ALL_FEATURES, OsmAndFeature.UNLOCK_ALL_FEATURES,
OsmAndFeature.DONATION_TO_OSM,
}; };
@Override @Override
@ -93,7 +91,9 @@ public class OsmLiveCancelledDialog extends BaseOsmAndDialogFragment implements
if (ctx == null) { if (ctx == null) {
return null; return null;
} }
View view = inflate(R.layout.osmlive_cancelled_dialog_fragment, container); int themeRes = nightMode ? R.style.OsmandDarkTheme_DarkActionbar : R.style.OsmandLightTheme_DarkActionbar_LightStatusBar;
View view = LayoutInflater.from(new ContextThemeWrapper(getContext(), themeRes))
.inflate(R.layout.osmlive_cancelled_dialog_fragment, container, false);
view.findViewById(R.id.button_close).setOnClickListener(new View.OnClickListener() { view.findViewById(R.id.button_close).setOnClickListener(new View.OnClickListener() {
@Override @Override
@ -118,7 +118,7 @@ public class OsmLiveCancelledDialog extends BaseOsmAndDialogFragment implements
@Nullable @Nullable
public MapActivity getMapActivity() { public MapActivity getMapActivity() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null && activity instanceof MapActivity) { if (activity instanceof MapActivity) {
return (MapActivity) activity; return (MapActivity) activity;
} }
return null; return null;
@ -194,50 +194,29 @@ public class OsmLiveCancelledDialog extends BaseOsmAndDialogFragment implements
ProgressBar progressBar = (ProgressBar) osmLiveButton.findViewById(R.id.card_button_progress); ProgressBar progressBar = (ProgressBar) osmLiveButton.findViewById(R.id.card_button_progress);
TextViewEx buttonTitle = (TextViewEx) osmLiveButton.findViewById(R.id.card_button_title); TextViewEx buttonTitle = (TextViewEx) osmLiveButton.findViewById(R.id.card_button_title);
TextViewEx buttonSubtitle = (TextViewEx) osmLiveButton.findViewById(R.id.card_button_subtitle); TextViewEx buttonSubtitle = (TextViewEx) osmLiveButton.findViewById(R.id.card_button_subtitle);
if (!purchaseHelper.hasPrices()) { buttonTitle.setText(getString(R.string.osm_live_plan_pricing));
buttonTitle.setText(getString(R.string.purchase_subscription_title, getString(R.string.osm_live_default_price))); buttonSubtitle.setVisibility(View.GONE);
} else {
buttonTitle.setText(getString(R.string.purchase_subscription_title, purchaseHelper.getLiveUpdatesPrice()));
}
buttonSubtitle.setText(R.string.osm_live_month_cost_desc);
if (progress) { if (progress) {
buttonTitle.setVisibility(View.GONE); buttonTitle.setVisibility(View.GONE);
buttonSubtitle.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE);
osmLiveButton.setOnClickListener(null); osmLiveButton.setOnClickListener(null);
} else { } else {
buttonTitle.setVisibility(View.VISIBLE); buttonTitle.setVisibility(View.VISIBLE);
buttonSubtitle.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE); progressBar.setVisibility(View.GONE);
osmLiveButton.setOnClickListener(new View.OnClickListener() { osmLiveButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
subscript();
dismiss(); dismiss();
FragmentActivity activity = getActivity();
if (activity != null) {
ChoosePlanDialogFragment.showOsmLiveInstance(activity.getSupportFragmentManager());
}
} }
}); });
} }
} }
} }
private void subscript() {
FragmentActivity ctx = getActivity();
if (ctx != null && purchaseHelper != null) {
OsmandSettings settings = app.getSettings();
purchaseHelper.purchaseLiveUpdates(ctx,
settings.BILLING_USER_EMAIL.get(),
settings.BILLING_USER_NAME.get(),
settings.BILLING_USER_COUNTRY_DOWNLOAD_NAME.get(),
settings.BILLING_HIDE_USER_NAME.get());
}
}
private View inflate(@LayoutRes int layoutId, @Nullable ViewGroup container) {
int themeRes = nightMode ? R.style.OsmandDarkTheme_DarkActionbar : R.style.OsmandLightTheme_DarkActionbar_LightStatusBar;
return LayoutInflater.from(new ContextThemeWrapper(getContext(), themeRes))
.inflate(layoutId, container, false);
}
public static boolean shouldShowDialog(OsmandApplication app) { public static boolean shouldShowDialog(OsmandApplication app) {
OsmandSettings settings = app.getSettings(); OsmandSettings settings = app.getSettings();
long cancelledTime = settings.LIVE_UPDATES_PURCHASE_CANCELLED_TIME.get(); long cancelledTime = settings.LIVE_UPDATES_PURCHASE_CANCELLED_TIME.get();

View file

@ -50,18 +50,18 @@ public class DatabaseHelper {
if (conn == null) { if (conn == null) {
return null; return null;
} }
if (conn.getVersion() == 0 || DB_VERSION != conn.getVersion()) { if (conn.getVersion() < DB_VERSION) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = app.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); conn = app.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false);
} }
if (conn.getVersion() == 0) { int version = conn.getVersion();
conn.setVersion(DB_VERSION); conn.setVersion(DB_VERSION);
if (version == 0) {
onCreate(conn); onCreate(conn);
} else { } else {
onUpgrade(conn, conn.getVersion(), DB_VERSION); onUpgrade(conn, version, DB_VERSION);
} }
} }
return conn; return conn;
} }

View file

@ -1,6 +1,8 @@
package net.osmand.plus.helpers; package net.osmand.plus.helpers;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
@ -11,10 +13,15 @@ import android.os.AsyncTask;
import android.provider.Settings.Secure; import android.provider.Settings.Secure;
import android.support.annotation.ColorInt; import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat; import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
import net.osmand.AndroidNetworkUtils; import net.osmand.AndroidNetworkUtils;
import net.osmand.osm.AbstractPoiType;
import net.osmand.osm.MapPoiTypes;
import net.osmand.osm.PoiCategory;
import net.osmand.osm.PoiType;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings; import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R; import net.osmand.plus.R;
@ -22,6 +29,9 @@ import net.osmand.plus.Version;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.chooseplan.ChoosePlanDialogFragment; import net.osmand.plus.chooseplan.ChoosePlanDialogFragment;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase;
import net.osmand.plus.poi.PoiUIFilter;
import net.osmand.plus.search.QuickSearchHelper;
import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarController; import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarController;
import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarControllerType; import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarControllerType;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
@ -31,7 +41,9 @@ import org.json.JSONObject;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map; import java.util.Map;
public class DiscountHelper { public class DiscountHelper {
@ -42,10 +54,15 @@ public class DiscountHelper {
private static long mLastCheckTime; private static long mLastCheckTime;
private static ControllerData mData; private static ControllerData mData;
private static boolean mBannerVisible; private static boolean mBannerVisible;
private static PoiUIFilter mFilter;
private static boolean mFilterVisible;
private static final String URL = "https://osmand.net/api/motd"; private static final String URL = "https://osmand.net/api/motd";
private static final String INAPP_PREFIX = "osmand-in-app:"; private static final String INAPP_PREFIX = "osmand-in-app:";
private static final String SEARCH_QUERY_PREFIX = "osmand-search-query:";
private static final String SHOW_POI_PREFIX = "osmand-show-poi:";
private static final String OPEN_ACTIVITY = "open_activity";
@SuppressLint("HardwareIds")
public static void checkAndDisplay(final MapActivity mapActivity) { public static void checkAndDisplay(final MapActivity mapActivity) {
OsmandApplication app = mapActivity.getMyApplication(); OsmandApplication app = mapActivity.getMyApplication();
OsmandSettings settings = app.getSettings(); OsmandSettings settings = app.getSettings();
@ -54,6 +71,8 @@ public class DiscountHelper {
} }
if (mBannerVisible) { if (mBannerVisible) {
showDiscountBanner(mapActivity, mData); showDiscountBanner(mapActivity, mData);
} else if (mFilterVisible) {
showPoiFilter(mapActivity, mFilter);
} }
if (System.currentTimeMillis() - mLastCheckTime < 1000 * 60 * 60 * 24 if (System.currentTimeMillis() - mLastCheckTime < 1000 * 60 * 60 * 24
|| !settings.isInternetConnectionAvailable()) { || !settings.isInternetConnectionAvailable()) {
@ -106,12 +125,13 @@ public class DiscountHelper {
double showDayFrequency = obj.getDouble("show_day_frequency"); double showDayFrequency = obj.getDouble("show_day_frequency");
int maxTotalShow = obj.getInt("max_total_show"); int maxTotalShow = obj.getInt("max_total_show");
JSONObject application = obj.getJSONObject("application"); JSONObject application = obj.getJSONObject("application");
boolean showChristmasDialog = obj.optBoolean("show_christmas_dialog", false);
if (data.url.startsWith(INAPP_PREFIX) && data.url.length() > INAPP_PREFIX.length()) { if (data.url.startsWith(INAPP_PREFIX) && data.url.length() > INAPP_PREFIX.length()) {
String inAppSku = data.url.substring(INAPP_PREFIX.length()); String inAppSku = data.url.substring(INAPP_PREFIX.length());
InAppPurchaseHelper purchaseHelper = app.getInAppPurchaseHelper(); InAppPurchaseHelper purchaseHelper = app.getInAppPurchaseHelper();
if (purchaseHelper != null if (purchaseHelper != null
&& (purchaseHelper.isPurchased(inAppSku) || InAppPurchaseHelper.isSubscribedToLiveUpdates(app))) { && purchaseHelper.isPurchased(inAppSku) || InAppPurchaseHelper.isSubscribedToLiveUpdates(app)) {
return; return;
} }
} }
@ -136,10 +156,14 @@ public class DiscountHelper {
settings.DISCOUNT_TOTAL_SHOW.set(settings.DISCOUNT_TOTAL_SHOW.get() + 1); settings.DISCOUNT_TOTAL_SHOW.set(settings.DISCOUNT_TOTAL_SHOW.get() + 1);
settings.DISCOUNT_SHOW_NUMBER_OF_STARTS.set(app.getAppInitializer().getNumberOfStarts()); settings.DISCOUNT_SHOW_NUMBER_OF_STARTS.set(app.getAppInitializer().getNumberOfStarts());
settings.DISCOUNT_SHOW_DATETIME_MS.set(System.currentTimeMillis()); settings.DISCOUNT_SHOW_DATETIME_MS.set(System.currentTimeMillis());
if (showChristmasDialog) {
mapActivity.showXMasDialog();
} else {
showDiscountBanner(mapActivity, data); showDiscountBanner(mapActivity, data);
} }
} }
} }
}
} catch (Exception e) { } catch (Exception e) {
logError("JSON parsing error: ", e); logError("JSON parsing error: ", e);
} }
@ -181,6 +205,12 @@ public class DiscountHelper {
toolbarController.setDescrTextClrs(data.descrColor, data.descrColor); toolbarController.setDescrTextClrs(data.descrColor, data.descrColor);
toolbarController.setBackBtnIconIds(iconId, iconId); toolbarController.setBackBtnIconIds(iconId, iconId);
toolbarController.setBackBtnIconClrs(data.iconColor, data.iconColor); toolbarController.setBackBtnIconClrs(data.iconColor, data.iconColor);
toolbarController.setStatusBarColor(data.statusBarColor);
if (!TextUtils.isEmpty(data.textBtnTitle)) {
toolbarController.setTextBtnVisible(true);
toolbarController.setTextBtnTitle(data.textBtnTitle);
toolbarController.setTextBtnTitleClrs(data.textBtnTitleColor, data.textBtnTitleColor);
}
if (!Algorithms.isEmpty(data.url)) { if (!Algorithms.isEmpty(data.url)) {
View.OnClickListener clickListener = new View.OnClickListener() { View.OnClickListener clickListener = new View.OnClickListener() {
@Override @Override
@ -193,6 +223,7 @@ public class DiscountHelper {
}; };
toolbarController.setOnBackButtonClickListener(clickListener); toolbarController.setOnBackButtonClickListener(clickListener);
toolbarController.setOnTitleClickListener(clickListener); toolbarController.setOnTitleClickListener(clickListener);
toolbarController.setOnTextBtnClickListener(clickListener);
} }
toolbarController.setOnCloseButtonClickListener(new View.OnClickListener() { toolbarController.setOnCloseButtonClickListener(new View.OnClickListener() {
@Override @Override
@ -209,17 +240,69 @@ public class DiscountHelper {
mapActivity.showTopToolbar(toolbarController); mapActivity.showTopToolbar(toolbarController);
} }
private static void showPoiFilter(final MapActivity mapActivity, final PoiUIFilter poiFilter) {
QuickSearchHelper.showPoiFilterOnMap(mapActivity, poiFilter, new Runnable() {
@Override
public void run() {
mFilterVisible = false;
}
});
mFilter = poiFilter;
mFilterVisible = true;
}
private static void openUrl(final MapActivity mapActivity, String url) { private static void openUrl(final MapActivity mapActivity, String url) {
if (url.startsWith(INAPP_PREFIX)) { if (url.startsWith(INAPP_PREFIX)) {
if (url.contains(InAppPurchaseHelper.SKU_FULL_VERSION_PRICE)) {
OsmandApplication app = mapActivity.getMyApplication(); OsmandApplication app = mapActivity.getMyApplication();
app.logEvent(mapActivity, "in_app_purchase_redirect");
InAppPurchaseHelper purchaseHelper = app.getInAppPurchaseHelper(); InAppPurchaseHelper purchaseHelper = app.getInAppPurchaseHelper();
if (purchaseHelper != null) { if (purchaseHelper != null) {
if (url.contains(purchaseHelper.getFullVersion().getSku())) {
app.logEvent(mapActivity, "in_app_purchase_redirect");
purchaseHelper.purchaseFullVersion(mapActivity); purchaseHelper.purchaseFullVersion(mapActivity);
} } else {
} else if (url.contains(InAppPurchaseHelper.SKU_LIVE_UPDATES)) { for (InAppPurchase p : purchaseHelper.getLiveUpdates().getAllSubscriptions()) {
if (url.contains(p.getSku())) {
ChoosePlanDialogFragment.showOsmLiveInstance(mapActivity.getSupportFragmentManager()); ChoosePlanDialogFragment.showOsmLiveInstance(mapActivity.getSupportFragmentManager());
break;
}
}
}
}
} else if (url.startsWith(SEARCH_QUERY_PREFIX)) {
String query = url.substring(SEARCH_QUERY_PREFIX.length());
if (!query.isEmpty()) {
mapActivity.showQuickSearch(query);
}
} else if (url.startsWith(SHOW_POI_PREFIX)) {
String names = url.substring(SHOW_POI_PREFIX.length());
if (!names.isEmpty()) {
OsmandApplication app = mapActivity.getMyApplication();
MapPoiTypes poiTypes = app.getPoiTypes();
Map<PoiCategory, LinkedHashSet<String>> acceptedTypes = new LinkedHashMap<>();
for (String name : names.split(",")) {
AbstractPoiType abstractType = poiTypes.getAnyPoiTypeByKey(name);
if (abstractType instanceof PoiCategory) {
acceptedTypes.put((PoiCategory) abstractType, null);
} else if (abstractType instanceof PoiType) {
PoiType type = (PoiType) abstractType;
PoiCategory category = type.getCategory();
LinkedHashSet<String> set = acceptedTypes.get(category);
if (set == null) {
set = new LinkedHashSet<>();
acceptedTypes.put(category, set);
}
set.add(type.getKeyName());
}
}
if (!acceptedTypes.isEmpty()) {
PoiUIFilter filter = new PoiUIFilter("", null, acceptedTypes, app);
filter.setName(filter.getTypesName());
showPoiFilter(mapActivity, filter);
}
}
} else if (url.equals(OPEN_ACTIVITY)) {
if (mData.activityJson != null) {
openActivity(mapActivity, mData.activityJson);
} }
} else { } else {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
@ -228,12 +311,51 @@ public class DiscountHelper {
} }
} }
private static void openActivity(Context context, JSONObject activityObject) {
boolean successful = false;
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
for (Iterator<String> it = activityObject.keys(); it.hasNext(); ) {
String key = it.next();
if (key.equals("activity_name")) {
intent.setClassName(context, activityObject.getString(key));
successful = true;
continue;
}
Object obj = activityObject.get(key);
if (obj instanceof Integer) {
intent.putExtra(key, (Integer) obj);
} else if (obj instanceof Long) {
intent.putExtra(key, (Long) obj);
} else if (obj instanceof Boolean) {
intent.putExtra(key, (Boolean) obj);
} else if (obj instanceof Float) {
intent.putExtra(key, (Float) obj);
} else if (obj instanceof Double) {
intent.putExtra(key, (Double) obj);
} else if (obj instanceof String) {
intent.putExtra(key, (String) obj);
}
}
} catch (JSONException e) {
successful = false;
}
if (successful) {
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
// ignore
}
}
}
private static class ControllerData { private static class ControllerData {
String message; String message;
String description; String description;
String iconId; String iconId;
String url; String url;
String textBtnTitle;
@ColorInt @ColorInt
int iconColor = -1; int iconColor = -1;
@ -243,6 +365,12 @@ public class DiscountHelper {
int titleColor = -1; int titleColor = -1;
@ColorInt @ColorInt
int descrColor = -1; int descrColor = -1;
@ColorInt
int statusBarColor = -1;
@ColorInt
int textBtnTitleColor = -1;
JSONObject activityJson;
static ControllerData parse(OsmandApplication app, JSONObject obj) throws JSONException { static ControllerData parse(OsmandApplication app, JSONObject obj) throws JSONException {
ControllerData res = new ControllerData(); ControllerData res = new ControllerData();
@ -250,10 +378,14 @@ public class DiscountHelper {
res.description = obj.getString("description"); res.description = obj.getString("description");
res.iconId = obj.getString("icon"); res.iconId = obj.getString("icon");
res.url = parseUrl(app, obj.getString("url")); res.url = parseUrl(app, obj.getString("url"));
res.textBtnTitle = obj.optString("button_title");
res.iconColor = parseColor("icon_color", obj); res.iconColor = parseColor("icon_color", obj);
res.bgColor = parseColor("bg_color", obj); res.bgColor = parseColor("bg_color", obj);
res.titleColor = parseColor("title_color", obj); res.titleColor = parseColor("title_color", obj);
res.descrColor = parseColor("description_color", obj); res.descrColor = parseColor("description_color", obj);
res.statusBarColor = parseColor("status_bar_color", obj);
res.textBtnTitleColor = parseColor("button_title_color", obj);
res.activityJson = obj.optJSONObject("activity");
return res; return res;
} }
@ -266,7 +398,9 @@ public class DiscountHelper {
} }
} }
private static class DiscountBarController extends TopToolbarController { public static class DiscountBarController extends TopToolbarController {
private int statusBarColor = NO_COLOR;
DiscountBarController() { DiscountBarController() {
super(TopToolbarControllerType.DISCOUNT); super(TopToolbarControllerType.DISCOUNT);
@ -278,6 +412,15 @@ public class DiscountHelper {
setBgIds(R.color.discount_bar_bg, R.color.discount_bar_bg, setBgIds(R.color.discount_bar_bg, R.color.discount_bar_bg,
R.drawable.discount_bar_bg_land, R.drawable.discount_bar_bg_land); R.drawable.discount_bar_bg_land, R.drawable.discount_bar_bg_land);
} }
@Override
public int getStatusBarColor(Context context, boolean night) {
return statusBarColor;
}
void setStatusBarColor(int statusBarColor) {
this.statusBarColor = statusBarColor;
}
} }
private static void logError(String msg, Throwable e) { private static void logError(String msg, Throwable e) {

View file

@ -316,15 +316,16 @@ public class SearchHistoryHelper {
private SQLiteConnection openConnection(boolean readonly) { private SQLiteConnection openConnection(boolean readonly) {
SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly); SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly);
if (conn.getVersion() == 0 || DB_VERSION != conn.getVersion()) { if (conn.getVersion() < DB_VERSION) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false);
} }
if (conn.getVersion() == 0) { int version = conn.getVersion();
if (version == 0) {
onCreate(conn); onCreate(conn);
} else { } else {
onUpgrade(conn, conn.getVersion(), DB_VERSION); onUpgrade(conn, version, DB_VERSION);
} }
conn.setVersion(DB_VERSION); conn.setVersion(DB_VERSION);
} }

View file

@ -1,103 +0,0 @@
package net.osmand.plus.helpers;
import net.osmand.plus.DeviceAdminRecv;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.routing.VoiceRouter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.os.PowerManager;
@SuppressLint("NewApi")
public class WakeLockHelper implements VoiceRouter.VoiceMessageListener {
private PowerManager.WakeLock wakeLock = null;
private ReleaseWakeLocksRunnable releaseWakeLocksRunnable = new ReleaseWakeLocksRunnable();
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mDeviceAdmin;
private Handler uiHandler;
private OsmandApplication app;
private boolean active;
public WakeLockHelper(OsmandApplication app){
uiHandler = new Handler();
this.app = app;
mDeviceAdmin = new ComponentName(app, DeviceAdminRecv.class);
mDevicePolicyManager = (DevicePolicyManager) app.getSystemService(Context.DEVICE_POLICY_SERVICE);
}
private void releaseWakeLocks() {
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
if (mDevicePolicyManager != null && mDeviceAdmin != null) {
OsmandSettings settings = app.getSettings();
final Integer screenPowerSave = settings.WAKE_ON_VOICE_INT.get();
if (screenPowerSave > 0 && settings.MAP_ACTIVITY_ENABLED.get()) {
if (mDevicePolicyManager.isAdminActive(mDeviceAdmin)) {
try {
mDevicePolicyManager.lockNow();
} catch (SecurityException e) {
// Log.d(TAG,
// "SecurityException: No device admin permission to lock the screen!");
}
} else {
// Log.d(TAG,
// "No device admin permission to lock the screen!");
}
}
}
}
private class ReleaseWakeLocksRunnable implements Runnable {
@Override
public void run() {
releaseWakeLocks();
}
}
public void onStart(Activity a) {
this.active = true;
if (wakeLock == null) {
VoiceRouter voiceRouter = app.getRoutingHelper().getVoiceRouter();
voiceRouter.removeVoiceMessageListener(this);
}
}
public void onStop(Activity a) {
this.active = false;
OsmandSettings settings = app.getSettings();
if (!a.isFinishing() && (settings.WAKE_ON_VOICE_INT.get() > 0)) {
VoiceRouter voiceRouter = app.getRoutingHelper().getVoiceRouter();
voiceRouter.addVoiceMessageListener(this);
}
}
@Override
public void onVoiceMessage() {
OsmandSettings settings = app.getSettings();
final Integer screenPowerSave = settings.WAKE_ON_VOICE_INT.get();
if (screenPowerSave > 0) {
uiHandler.removeCallbacks(releaseWakeLocksRunnable);
if (!active && wakeLock == null) {
PowerManager pm = (PowerManager) app.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP,
"OsmAndOnVoiceWakeupTag");
wakeLock.acquire();
}
uiHandler.postDelayed(releaseWakeLocksRunnable,
screenPowerSave * 1000L);
}
}
}

View file

@ -5,6 +5,8 @@ import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import net.osmand.AndroidNetworkUtils; import net.osmand.AndroidNetworkUtils;
@ -14,6 +16,11 @@ import net.osmand.plus.OsmandSettings;
import net.osmand.plus.OsmandSettings.OsmandPreference; import net.osmand.plus.OsmandSettings.OsmandPreference;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.Version; import net.osmand.plus.Version;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchase.PurchaseState;
import net.osmand.plus.inapp.InAppPurchases.InAppPurchaseLiveUpdatesOldSubscription;
import net.osmand.plus.inapp.InAppPurchases.InAppSubscription;
import net.osmand.plus.inapp.InAppPurchases.InAppSubscriptionList;
import net.osmand.plus.inapp.util.IabHelper; import net.osmand.plus.inapp.util.IabHelper;
import net.osmand.plus.inapp.util.IabHelper.OnIabPurchaseFinishedListener; import net.osmand.plus.inapp.util.IabHelper.OnIabPurchaseFinishedListener;
import net.osmand.plus.inapp.util.IabHelper.QueryInventoryFinishedListener; import net.osmand.plus.inapp.util.IabHelper.QueryInventoryFinishedListener;
@ -25,40 +32,31 @@ import net.osmand.plus.liveupdates.CountrySelectionFragment;
import net.osmand.plus.liveupdates.CountrySelectionFragment.CountryItem; import net.osmand.plus.liveupdates.CountrySelectionFragment.CountryItem;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import static net.osmand.plus.inapp.util.IabHelper.ITEM_TYPE_SUBS;
public class InAppPurchaseHelper { public class InAppPurchaseHelper {
// Debug tag, for logging // Debug tag, for logging
private static final String TAG = InAppPurchaseHelper.class.getSimpleName(); private static final String TAG = InAppPurchaseHelper.class.getSimpleName();
boolean mDebugLog = true; private boolean mDebugLog = true;
public static final long SUBSCRIPTION_HOLDING_TIME_MSEC = 1000 * 60 * 60 * 24 * 3; // 3 days public static final long SUBSCRIPTION_HOLDING_TIME_MSEC = 1000 * 60 * 60 * 24 * 3; // 3 days
private InAppPurchases purchases;
private long lastValidationCheckTime; private long lastValidationCheckTime;
private String liveUpdatesPrice;
private String fullVersionPrice;
private String depthContoursPrice;
private String contourLinesPrice;
public static final String SKU_FULL_VERSION_PRICE = "osmand_full_version_price";
private static final String SKU_LIVE_UPDATES_FULL = "osm_live_subscription_2";
private static final String SKU_LIVE_UPDATES_FREE = "osm_free_live_subscription_2";
private static final String SKU_DEPTH_CONTOURS_FULL = "net.osmand.seadepth_plus";
private static final String SKU_DEPTH_CONTOURS_FREE = "net.osmand.seadepth";
private static final String SKU_CONTOUR_LINES_FULL = "net.osmand.contourlines_plus";
private static final String SKU_CONTOUR_LINES_FREE = "net.osmand.contourlines";
public static String SKU_LIVE_UPDATES;
public static String SKU_DEPTH_CONTOURS;
public static String SKU_CONTOUR_LINES;
private static final long PURCHASE_VALIDATION_PERIOD_MSEC = 1000 * 60 * 60 * 24; // daily private static final long PURCHASE_VALIDATION_PERIOD_MSEC = 1000 * 60 * 60 * 24; // daily
// (arbitrary) request code for the purchase flow // (arbitrary) request code for the purchase flow
@ -70,6 +68,7 @@ public class InAppPurchaseHelper {
private String token = ""; private String token = "";
private InAppPurchaseTaskType activeTask; private InAppPurchaseTaskType activeTask;
private boolean processingTask = false; private boolean processingTask = false;
private boolean inventoryRequestPending = false;
private OsmandApplication ctx; private OsmandApplication ctx;
private InAppPurchaseListener uiActivity = null; private InAppPurchaseListener uiActivity = null;
@ -136,59 +135,35 @@ public class InAppPurchaseHelper {
return Version.isDeveloperBuild(ctx) || ctx.getSettings().DEPTH_CONTOURS_PURCHASED.get(); return Version.isDeveloperBuild(ctx) || ctx.getSettings().DEPTH_CONTOURS_PURCHASED.get();
} }
public String getLiveUpdatesPrice() { public InAppSubscriptionList getLiveUpdates() {
return liveUpdatesPrice; return purchases.getLiveUpdates();
} }
public String getFullVersionPrice() { public InAppPurchase getFullVersion() {
return fullVersionPrice; return purchases.getFullVersion();
} }
public String getDepthContoursPrice() { public InAppPurchase getDepthContours() {
return depthContoursPrice; return purchases.getDepthContours();
} }
public String getContourLinesPrice() { public InAppPurchase getContourLines() {
return contourLinesPrice; return purchases.getContourLines();
} }
public String getSkuLiveUpdates() { public InAppSubscription getMonthlyLiveUpdates() {
return SKU_LIVE_UPDATES; return purchases.getMonthlyLiveUpdates();
} }
public boolean hasPrices() { @Nullable
return !Algorithms.isEmpty(liveUpdatesPrice) public InAppSubscription getPurchasedMonthlyLiveUpdates() {
&& (!Version.isFreeVersion(ctx) || !Algorithms.isEmpty(fullVersionPrice)); return purchases.getPurchasedMonthlyLiveUpdates();
}
private void initialize() {
if (SKU_LIVE_UPDATES == null) {
if (Version.isFreeVersion(ctx)) {
SKU_LIVE_UPDATES = SKU_LIVE_UPDATES_FREE;
} else {
SKU_LIVE_UPDATES = SKU_LIVE_UPDATES_FULL;
}
}
if (SKU_DEPTH_CONTOURS == null) {
if (Version.isFreeVersion(ctx)) {
SKU_DEPTH_CONTOURS = SKU_DEPTH_CONTOURS_FREE;
} else {
SKU_DEPTH_CONTOURS = SKU_DEPTH_CONTOURS_FULL;
}
}
if (SKU_CONTOUR_LINES == null) {
if (Version.isFreeVersion(ctx)) {
SKU_CONTOUR_LINES = SKU_CONTOUR_LINES_FREE;
} else {
SKU_CONTOUR_LINES = SKU_CONTOUR_LINES_FULL;
}
}
} }
public InAppPurchaseHelper(OsmandApplication ctx) { public InAppPurchaseHelper(OsmandApplication ctx) {
this.ctx = ctx; this.ctx = ctx;
isDeveloperVersion = Version.isDeveloperVersion(ctx); isDeveloperVersion = Version.isDeveloperVersion(ctx);
initialize(); purchases = new InAppPurchases(ctx);
} }
public boolean hasInventory() { public boolean hasInventory() {
@ -196,11 +171,11 @@ public class InAppPurchaseHelper {
} }
public boolean isPurchased(String inAppSku) { public boolean isPurchased(String inAppSku) {
if (inAppSku.equals(SKU_FULL_VERSION_PRICE)) { if (purchases.isFullVersion(inAppSku)) {
return isFullVersionPurchased(ctx); return isFullVersionPurchased(ctx);
} else if (inAppSku.equals(SKU_LIVE_UPDATES_FULL) || inAppSku.equals(SKU_LIVE_UPDATES_FREE)) { } else if (purchases.isLiveUpdates(inAppSku)) {
return isSubscribedToLiveUpdates(ctx); return isSubscribedToLiveUpdates(ctx);
} else if (inAppSku.equals(SKU_DEPTH_CONTOURS_FULL) || inAppSku.equals(SKU_DEPTH_CONTOURS_FREE)) { } else if (purchases.isDepthContours(inAppSku)) {
return isDepthContoursPurchased(ctx); return isDepthContoursPurchased(ctx);
} }
return false; return false;
@ -212,7 +187,10 @@ public class InAppPurchaseHelper {
} }
if (processingTask) { if (processingTask) {
logError("Already processing task: " + taskType + ". Exit."); if (taskType == InAppPurchaseTaskType.REQUEST_INVENTORY) {
inventoryRequestPending = true;
}
logError("Already processing task: " + activeTask + ". Exit.");
return; return;
} }
@ -257,32 +235,13 @@ public class InAppPurchaseHelper {
} }
public boolean needRequestInventory() { public boolean needRequestInventory() {
return (isSubscribedToLiveUpdates(ctx) && !ctx.getSettings().BILLING_PURCHASE_TOKEN_SENT.get()) return (isSubscribedToLiveUpdates(ctx) && Algorithms.isEmpty(ctx.getSettings().BILLING_PURCHASE_TOKENS_SENT.get()))
|| System.currentTimeMillis() - lastValidationCheckTime > PURCHASE_VALIDATION_PERIOD_MSEC; || System.currentTimeMillis() - lastValidationCheckTime > PURCHASE_VALIDATION_PERIOD_MSEC;
} }
public void requestInventory() { public void requestInventory() {
notifyShowProgress(InAppPurchaseTaskType.REQUEST_INVENTORY); notifyShowProgress(InAppPurchaseTaskType.REQUEST_INVENTORY);
exec(InAppPurchaseTaskType.REQUEST_INVENTORY, new InAppRunnable() { new RequestInventoryTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
@Override
public boolean run(InAppPurchaseHelper helper) {
logDebug("Setup successful. Querying inventory.");
List<String> skus = new ArrayList<>();
skus.add(SKU_LIVE_UPDATES);
skus.add(SKU_DEPTH_CONTOURS);
skus.add(SKU_CONTOUR_LINES);
skus.add(SKU_FULL_VERSION_PRICE);
try {
mHelper.queryInventoryAsync(true, skus, mGotInventoryListener);
return false;
} catch (Exception e) {
logError("queryInventoryAsync Error", e);
notifyDismissProgress(InAppPurchaseTaskType.REQUEST_INVENTORY);
stop(true);
}
return true;
}
});
} }
public void purchaseFullVersion(final Activity activity) { public void purchaseFullVersion(final Activity activity) {
@ -292,7 +251,7 @@ public class InAppPurchaseHelper {
public boolean run(InAppPurchaseHelper helper) { public boolean run(InAppPurchaseHelper helper) {
try { try {
mHelper.launchPurchaseFlow(activity, mHelper.launchPurchaseFlow(activity,
SKU_FULL_VERSION_PRICE, RC_REQUEST, mPurchaseFinishedListener); getFullVersion().getSku(), RC_REQUEST, mPurchaseFinishedListener);
return false; return false;
} catch (Exception e) { } catch (Exception e) {
complain("Cannot launch full version purchase!"); complain("Cannot launch full version purchase!");
@ -304,10 +263,10 @@ public class InAppPurchaseHelper {
}); });
} }
public void purchaseLiveUpdates(Activity activity, String email, String userName, public void purchaseLiveUpdates(Activity activity, String sku, String email, String userName,
String countryDownloadName, boolean hideUserName) { String countryDownloadName, boolean hideUserName) {
notifyShowProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES); notifyShowProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES);
new LiveUpdatesPurchaseTask(activity, email, userName, countryDownloadName, hideUserName) new LiveUpdatesPurchaseTask(activity, sku, email, userName, countryDownloadName, hideUserName)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null); .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
} }
@ -318,7 +277,7 @@ public class InAppPurchaseHelper {
public boolean run(InAppPurchaseHelper helper) { public boolean run(InAppPurchaseHelper helper) {
try { try {
mHelper.launchPurchaseFlow(activity, mHelper.launchPurchaseFlow(activity,
SKU_DEPTH_CONTOURS, RC_REQUEST, mPurchaseFinishedListener); getDepthContours().getSku(), RC_REQUEST, mPurchaseFinishedListener);
return false; return false;
} catch (Exception e) { } catch (Exception e) {
complain("Cannot launch depth contours purchase!"); complain("Cannot launch depth contours purchase!");
@ -358,8 +317,17 @@ public class InAppPurchaseHelper {
*/ */
// Do we have the live updates? // Do we have the live updates?
Purchase liveUpdatesPurchase = inventory.getPurchase(SKU_LIVE_UPDATES); boolean subscribedToLiveUpdates = false;
boolean subscribedToLiveUpdates = (liveUpdatesPurchase != null && liveUpdatesPurchase.getPurchaseState() == 0); List<Purchase> liveUpdatesPurchases = new ArrayList<>();
for (InAppPurchase p : getLiveUpdates().getAllSubscriptions()) {
Purchase purchase = inventory.getPurchase(p.getSku());
if (purchase != null) {
liveUpdatesPurchases.add(purchase);
if (!subscribedToLiveUpdates && purchase.getPurchaseState() == 0) {
subscribedToLiveUpdates = true;
}
}
}
OsmandPreference<Long> subscriptionCancelledTime = ctx.getSettings().LIVE_UPDATES_PURCHASE_CANCELLED_TIME; OsmandPreference<Long> subscriptionCancelledTime = ctx.getSettings().LIVE_UPDATES_PURCHASE_CANCELLED_TIME;
if (!subscribedToLiveUpdates && ctx.getSettings().LIVE_UPDATES_PURCHASED.get()) { if (!subscribedToLiveUpdates && ctx.getSettings().LIVE_UPDATES_PURCHASED.get()) {
if (subscriptionCancelledTime.get() == 0) { if (subscriptionCancelledTime.get() == 0) {
@ -377,13 +345,15 @@ public class InAppPurchaseHelper {
ctx.getSettings().LIVE_UPDATES_PURCHASED.set(true); ctx.getSettings().LIVE_UPDATES_PURCHASED.set(true);
} }
Purchase fullVersionPurchase = inventory.getPurchase(SKU_FULL_VERSION_PRICE); InAppPurchase fullVersion = getFullVersion();
Purchase fullVersionPurchase = inventory.getPurchase(fullVersion.getSku());
boolean fullVersionPurchased = (fullVersionPurchase != null && fullVersionPurchase.getPurchaseState() == 0); boolean fullVersionPurchased = (fullVersionPurchase != null && fullVersionPurchase.getPurchaseState() == 0);
if (fullVersionPurchased) { if (fullVersionPurchased) {
ctx.getSettings().FULL_VERSION_PURCHASED.set(true); ctx.getSettings().FULL_VERSION_PURCHASED.set(true);
} }
Purchase depthContoursPurchase = inventory.getPurchase(SKU_DEPTH_CONTOURS); InAppPurchase depthContours = getDepthContours();
Purchase depthContoursPurchase = inventory.getPurchase(depthContours.getSku());
boolean depthContoursPurchased = (depthContoursPurchase != null && depthContoursPurchase.getPurchaseState() == 0); boolean depthContoursPurchased = (depthContoursPurchase != null && depthContoursPurchase.getPurchaseState() == 0);
if (depthContoursPurchased) { if (depthContoursPurchased) {
ctx.getSettings().DEPTH_CONTOURS_PURCHASED.set(true); ctx.getSettings().DEPTH_CONTOURS_PURCHASED.set(true);
@ -393,30 +363,50 @@ public class InAppPurchaseHelper {
logDebug("User " + (subscribedToLiveUpdates ? "HAS" : "DOES NOT HAVE") logDebug("User " + (subscribedToLiveUpdates ? "HAS" : "DOES NOT HAVE")
+ " live updates purchased."); + " live updates purchased.");
if (inventory.hasDetails(SKU_LIVE_UPDATES)) { List<String> allOwnedSubscriptionSkus = inventory.getAllOwnedSkus(ITEM_TYPE_SUBS);
SkuDetails liveUpdatesDetails = inventory.getSkuDetails(SKU_LIVE_UPDATES); for (InAppPurchase p : getLiveUpdates().getAllSubscriptions()) {
liveUpdatesPrice = liveUpdatesDetails.getPrice(); if (inventory.hasDetails(p.getSku())) {
Purchase purchase = inventory.getPurchase(p.getSku());
SkuDetails liveUpdatesDetails = inventory.getSkuDetails(p.getSku());
fetchInAppPurchase(p, liveUpdatesDetails, purchase);
allOwnedSubscriptionSkus.remove(p.getSku());
} }
if (inventory.hasDetails(SKU_FULL_VERSION_PRICE)) {
SkuDetails fullPriceDetails = inventory.getSkuDetails(SKU_FULL_VERSION_PRICE);
fullVersionPrice = fullPriceDetails.getPrice();
} }
if (inventory.hasDetails(SKU_DEPTH_CONTOURS)) { for (String sku : allOwnedSubscriptionSkus) {
SkuDetails depthContoursDetails = inventory.getSkuDetails(SKU_DEPTH_CONTOURS); Purchase purchase = inventory.getPurchase(sku);
depthContoursPrice = depthContoursDetails.getPrice(); SkuDetails liveUpdatesDetails = inventory.getSkuDetails(sku);
InAppSubscription s = getLiveUpdates().upgradeSubscription(sku);
if (s == null) {
s = new InAppPurchaseLiveUpdatesOldSubscription(liveUpdatesDetails);
} }
if (inventory.hasDetails(SKU_CONTOUR_LINES)) { fetchInAppPurchase(s, liveUpdatesDetails, purchase);
SkuDetails contourLinesDetails = inventory.getSkuDetails(SKU_CONTOUR_LINES); }
contourLinesPrice = contourLinesDetails.getPrice(); if (inventory.hasDetails(fullVersion.getSku())) {
Purchase purchase = inventory.getPurchase(fullVersion.getSku());
SkuDetails fullPriceDetails = inventory.getSkuDetails(fullVersion.getSku());
fetchInAppPurchase(fullVersion, fullPriceDetails, purchase);
}
if (inventory.hasDetails(depthContours.getSku())) {
Purchase purchase = inventory.getPurchase(depthContours.getSku());
SkuDetails depthContoursDetails = inventory.getSkuDetails(depthContours.getSku());
fetchInAppPurchase(depthContours, depthContoursDetails, purchase);
}
InAppPurchase contourLines = getContourLines();
if (inventory.hasDetails(contourLines.getSku())) {
Purchase purchase = inventory.getPurchase(contourLines.getSku());
SkuDetails contourLinesDetails = inventory.getSkuDetails(contourLines.getSku());
fetchInAppPurchase(contourLines, contourLinesDetails, purchase);
} }
OsmandSettings settings = ctx.getSettings(); OsmandSettings settings = ctx.getSettings();
settings.INAPPS_READ.set(true); settings.INAPPS_READ.set(true);
boolean needSendToken = false; List<Purchase> tokensToSend = new ArrayList<>();
if (liveUpdatesPurchase != null) { if (liveUpdatesPurchases.size() > 0) {
List<String> tokensSent = Arrays.asList(settings.BILLING_PURCHASE_TOKENS_SENT.get().split(";"));
for (Purchase purchase : liveUpdatesPurchases) {
if ((Algorithms.isEmpty(settings.BILLING_USER_ID.get()) || Algorithms.isEmpty(settings.BILLING_USER_TOKEN.get())) if ((Algorithms.isEmpty(settings.BILLING_USER_ID.get()) || Algorithms.isEmpty(settings.BILLING_USER_TOKEN.get()))
&& !Algorithms.isEmpty(liveUpdatesPurchase.getDeveloperPayload())) { && !Algorithms.isEmpty(purchase.getDeveloperPayload())) {
String payload = liveUpdatesPurchase.getDeveloperPayload(); String payload = purchase.getDeveloperPayload();
if (!Algorithms.isEmpty(payload)) { if (!Algorithms.isEmpty(payload)) {
String[] arr = payload.split(" "); String[] arr = payload.split(" ");
if (arr.length > 0) { if (arr.length > 0) {
@ -428,8 +418,9 @@ public class InAppPurchaseHelper {
} }
} }
} }
if (!settings.BILLING_PURCHASE_TOKEN_SENT.get()) { if (!tokensSent.contains(purchase.getSku())) {
needSendToken = true; tokensToSend.add(purchase);
}
} }
} }
@ -443,19 +434,41 @@ public class InAppPurchaseHelper {
} }
}; };
if (needSendToken) { if (tokensToSend.size() > 0) {
sendToken(liveUpdatesPurchase.getToken(), listener); sendTokens(tokensToSend, listener);
} else { } else {
listener.onResult("OK"); listener.onResult("OK");
} }
} }
}; };
private void fetchInAppPurchase(@NonNull InAppPurchase inAppPurchase, @NonNull SkuDetails skuDetails, @Nullable Purchase purchase) {
if (purchase != null) {
inAppPurchase.setPurchaseState(purchase.getPurchaseState() == 0
? PurchaseState.PURCHASED : PurchaseState.NOT_PURCHASED);
inAppPurchase.setPurchaseTime(purchase.getPurchaseTime());
} else {
inAppPurchase.setPurchaseState(PurchaseState.NOT_PURCHASED);
}
inAppPurchase.setPrice(skuDetails.getPrice());
inAppPurchase.setPriceCurrencyCode(skuDetails.getPriceCurrencyCode());
if (skuDetails.getPriceAmountMicros() > 0) {
inAppPurchase.setPriceValue(skuDetails.getPriceAmountMicros() / 1000000d);
}
String subscriptionPeriod = skuDetails.getSubscriptionPeriod();
if (!Algorithms.isEmpty(subscriptionPeriod)) {
if (inAppPurchase instanceof InAppSubscription) {
((InAppSubscription) inAppPurchase).setSubscriptionPeriod(subscriptionPeriod);
}
}
}
@SuppressLint("StaticFieldLeak") @SuppressLint("StaticFieldLeak")
private class LiveUpdatesPurchaseTask extends AsyncTask<Void, Void, String> { private class LiveUpdatesPurchaseTask extends AsyncTask<Void, Void, String> {
private WeakReference<Activity> activity; private WeakReference<Activity> activity;
private String sku;
private String email; private String email;
private String userName; private String userName;
private String countryDownloadName; private String countryDownloadName;
@ -463,10 +476,11 @@ public class InAppPurchaseHelper {
private String userId; private String userId;
LiveUpdatesPurchaseTask(Activity activity, String email, String userName, LiveUpdatesPurchaseTask(Activity activity, String sku, String email, String userName,
String countryDownloadName, boolean hideUserName) { String countryDownloadName, boolean hideUserName) {
this.activity = new WeakReference<>(activity); this.activity = new WeakReference<>(activity);
this.sku = sku;
this.email = email; this.email = email;
this.userName = userName; this.userName = userName;
this.countryDownloadName = countryDownloadName; this.countryDownloadName = countryDownloadName;
@ -476,14 +490,12 @@ public class InAppPurchaseHelper {
@Override @Override
protected String doInBackground(Void... params) { protected String doInBackground(Void... params) {
userId = ctx.getSettings().BILLING_USER_ID.get(); userId = ctx.getSettings().BILLING_USER_ID.get();
if (Algorithms.isEmpty(userId) || Algorithms.isEmpty(token)) {
try { try {
Map<String, String> parameters = new HashMap<>(); Map<String, String> parameters = new HashMap<>();
parameters.put("visibleName", hideUserName ? "" : userName); parameters.put("visibleName", hideUserName ? "" : userName);
parameters.put("preferredCountry", countryDownloadName); parameters.put("preferredCountry", countryDownloadName);
parameters.put("email", email); parameters.put("email", email);
if (Algorithms.isEmpty(userId)) {
parameters.put("status", "new");
}
return AndroidNetworkUtils.sendRequest(ctx, return AndroidNetworkUtils.sendRequest(ctx,
"https://osmand.net/subscription/register", "https://osmand.net/subscription/register",
@ -491,20 +503,30 @@ public class InAppPurchaseHelper {
} catch (Exception e) { } catch (Exception e) {
logError("sendRequest Error", e); logError("sendRequest Error", e);
return null;
} }
} }
return null;
}
@Override @Override
protected void onPostExecute(String response) { protected void onPostExecute(String response) {
logDebug("Response=" + response); logDebug("Response=" + response);
if (response == null) { if (response == null) {
if (!Algorithms.isEmpty(userId)) {
if (Algorithms.isEmpty(token)) {
complain("User token is empty.");
notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES);
notifyError(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES, "User token is empty.");
stop(true);
return;
}
} else {
complain("Cannot retrieve userId from server."); complain("Cannot retrieve userId from server.");
notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES); notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES);
notifyError(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES, "Cannot retrieve userId from server."); notifyError(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES, "Cannot retrieve userId from server.");
stop(true); stop(true);
return; return;
}
} else { } else {
try { try {
JSONObject obj = new JSONObject(response); JSONObject obj = new JSONObject(response);
@ -524,7 +546,7 @@ public class InAppPurchaseHelper {
} }
notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES); notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES);
if (!Algorithms.isEmpty(userId)) { if (!Algorithms.isEmpty(userId) && !Algorithms.isEmpty(token)) {
logDebug("Launching purchase flow for live updates subscription for userId=" + userId); logDebug("Launching purchase flow for live updates subscription for userId=" + userId);
final String payload = userId + " " + token; final String payload = userId + " " + token;
exec(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES, new InAppRunnable() { exec(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES, new InAppRunnable() {
@ -534,7 +556,7 @@ public class InAppPurchaseHelper {
Activity a = activity.get(); Activity a = activity.get();
if (a != null) { if (a != null) {
mHelper.launchPurchaseFlow(a, mHelper.launchPurchaseFlow(a,
SKU_LIVE_UPDATES, IabHelper.ITEM_TYPE_SUBS, sku, ITEM_TYPE_SUBS,
RC_REQUEST, mPurchaseFinishedListener, payload); RC_REQUEST, mPurchaseFinishedListener, payload);
return false; return false;
} else { } else {
@ -548,7 +570,7 @@ public class InAppPurchaseHelper {
} }
}); });
} else { } else {
notifyError(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES,"Empty userId"); notifyError(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES, "Empty userId");
stop(true); stop(true);
} }
} }
@ -576,6 +598,71 @@ public class InAppPurchaseHelper {
} }
} }
@SuppressLint("StaticFieldLeak")
private class RequestInventoryTask extends AsyncTask<Void, Void, String> {
RequestInventoryTask() {
}
@Override
protected String doInBackground(Void... params) {
try {
Map<String, String> parameters = new HashMap<>();
parameters.put("androidPackage", ctx.getPackageName());
parameters.put("version", Version.getFullVersion(ctx));
parameters.put("lang", ctx.getLanguage() + "");
return AndroidNetworkUtils.sendRequest(ctx,
"https://osmand.net/api/subscriptions/active",
parameters, "Requesting active subscriptions...", false, false);
} catch (Exception e) {
logError("sendRequest Error", e);
}
return null;
}
@Override
protected void onPostExecute(String response) {
logDebug("Response=" + response);
if (response != null) {
try {
JSONObject obj = new JSONObject(response);
JSONArray names = obj.names();
for (int i = 0; i < names.length(); i++) {
String skuType = names.getString(i);
JSONObject subObj = obj.getJSONObject(skuType);
String sku = subObj.getString("sku");
if (!Algorithms.isEmpty(sku)) {
getLiveUpdates().upgradeSubscription(sku);
}
}
} catch (JSONException e) {
logError("Json parsing error", e);
}
}
exec(InAppPurchaseTaskType.REQUEST_INVENTORY, new InAppRunnable() {
@Override
public boolean run(InAppPurchaseHelper helper) {
logDebug("Setup successful. Querying inventory.");
Set<String> skus = new HashSet<>();
for (InAppPurchase purchase : purchases.getAllInAppPurchases()) {
skus.add(purchase.getSku());
}
try {
mHelper.queryInventoryAsync(true, new ArrayList<>(skus), mGotInventoryListener);
return false;
} catch (Exception e) {
logError("queryInventoryAsync Error", e);
notifyDismissProgress(InAppPurchaseTaskType.REQUEST_INVENTORY);
stop(true);
}
return true;
}
});
}
}
// Callback for when a purchase is finished // Callback for when a purchase is finished
private OnIabPurchaseFinishedListener mPurchaseFinishedListener = new OnIabPurchaseFinishedListener() { private OnIabPurchaseFinishedListener mPurchaseFinishedListener = new OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) { public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
@ -597,10 +684,13 @@ public class InAppPurchaseHelper {
logDebug("Purchase successful."); logDebug("Purchase successful.");
if (purchase.getSku().equals(SKU_LIVE_UPDATES)) { InAppPurchase liveUpdatesPurchase = getLiveUpdates().getSubscriptionBySku(purchase.getSku());
if (liveUpdatesPurchase != null) {
// bought live updates // bought live updates
logDebug("Live updates subscription purchased."); logDebug("Live updates subscription purchased.");
sendToken(purchase.getToken(), new OnRequestResultListener() { final String sku = liveUpdatesPurchase.getSku();
liveUpdatesPurchase.setPurchaseState(purchase.getPurchaseState() == 0 ? PurchaseState.PURCHASED : PurchaseState.NOT_PURCHASED);
sendTokens(Collections.singletonList(purchase), new OnRequestResultListener() {
@Override @Override
public void onResult(String result) { public void onResult(String result) {
boolean active = ctx.getSettings().LIVE_UPDATES_PURCHASED.get(); boolean active = ctx.getSettings().LIVE_UPDATES_PURCHASED.get();
@ -612,30 +702,32 @@ public class InAppPurchaseHelper {
ctx.getSettings().LIVE_UPDATES_PURCHASE_CANCELLED_SECOND_DLG_SHOWN.set(false); ctx.getSettings().LIVE_UPDATES_PURCHASE_CANCELLED_SECOND_DLG_SHOWN.set(false);
notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES); notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_LIVE_UPDATES);
notifyItemPurchased(SKU_LIVE_UPDATES, active); notifyItemPurchased(sku, active);
stop(true); stop(true);
} }
}); });
} else if (purchase.getSku().equals(SKU_FULL_VERSION_PRICE)) { } else if (purchase.getSku().equals(getFullVersion().getSku())) {
// bought full version // bought full version
getFullVersion().setPurchaseState(purchase.getPurchaseState() == 0 ? PurchaseState.PURCHASED : PurchaseState.NOT_PURCHASED);
logDebug("Full version purchased."); logDebug("Full version purchased.");
showToast(ctx.getString(R.string.full_version_thanks)); showToast(ctx.getString(R.string.full_version_thanks));
ctx.getSettings().FULL_VERSION_PURCHASED.set(true); ctx.getSettings().FULL_VERSION_PURCHASED.set(true);
notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_FULL_VERSION); notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_FULL_VERSION);
notifyItemPurchased(SKU_FULL_VERSION_PRICE, false); notifyItemPurchased(getFullVersion().getSku(), false);
stop(true); stop(true);
} else if (purchase.getSku().equals(SKU_DEPTH_CONTOURS)) { } else if (purchase.getSku().equals(getDepthContours().getSku())) {
// bought sea depth contours // bought sea depth contours
getDepthContours().setPurchaseState(purchase.getPurchaseState() == 0 ? PurchaseState.PURCHASED : PurchaseState.NOT_PURCHASED);
logDebug("Sea depth contours purchased."); logDebug("Sea depth contours purchased.");
showToast(ctx.getString(R.string.sea_depth_thanks)); showToast(ctx.getString(R.string.sea_depth_thanks));
ctx.getSettings().DEPTH_CONTOURS_PURCHASED.set(true); ctx.getSettings().DEPTH_CONTOURS_PURCHASED.set(true);
ctx.getSettings().getCustomRenderBooleanProperty("depthContours").set(true); ctx.getSettings().getCustomRenderBooleanProperty("depthContours").set(true);
notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_DEPTH_CONTOURS); notifyDismissProgress(InAppPurchaseTaskType.PURCHASE_DEPTH_CONTOURS);
notifyItemPurchased(SKU_DEPTH_CONTOURS, false); notifyItemPurchased(getDepthContours().getSku(), false);
stop(true); stop(true);
} else { } else {
@ -665,30 +757,43 @@ public class InAppPurchaseHelper {
processingTask = false; processingTask = false;
activeTask = null; activeTask = null;
} }
if (inventoryRequestPending) {
inventoryRequestPending = false;
requestInventory();
}
} }
private void sendToken(String purchaseToken, final OnRequestResultListener listener) { private void sendTokens(@NonNull final List<Purchase> purchases, final OnRequestResultListener listener) {
final String userId = ctx.getSettings().BILLING_USER_ID.get(); final String userId = ctx.getSettings().BILLING_USER_ID.get();
final String token = ctx.getSettings().BILLING_USER_TOKEN.get(); final String token = ctx.getSettings().BILLING_USER_TOKEN.get();
final String email = ctx.getSettings().BILLING_USER_EMAIL.get(); final String email = ctx.getSettings().BILLING_USER_EMAIL.get();
try { try {
String url = "https://osmand.net/subscription/purchased";
String userOperation = "Sending purchase info...";
final List<AndroidNetworkUtils.Request> requests = new ArrayList<>();
for (Purchase purchase : purchases) {
Map<String, String> parameters = new HashMap<>(); Map<String, String> parameters = new HashMap<>();
parameters.put("userid", userId); parameters.put("userid", userId);
parameters.put("sku", SKU_LIVE_UPDATES); parameters.put("sku", purchase.getSku());
parameters.put("purchaseToken", purchaseToken); parameters.put("purchaseToken", purchase.getToken());
parameters.put("email", email); parameters.put("email", email);
parameters.put("token", token); parameters.put("token", token);
requests.add(new AndroidNetworkUtils.Request(url, parameters, userOperation, true, true));
AndroidNetworkUtils.sendRequestAsync(ctx, }
"https://osmand.net/subscription/purchased", AndroidNetworkUtils.sendRequestsAsync(ctx, requests, new OnRequestResultListener() {
parameters, "Sending purchase info...", true, true, new OnRequestResultListener() {
@Override @Override
public void onResult(String result) { public void onResult(String result) {
if (result != null) { if (result != null) {
try { try {
JSONObject obj = new JSONObject(result); JSONObject obj = new JSONObject(result);
if (!obj.has("error")) { if (!obj.has("error")) {
ctx.getSettings().BILLING_PURCHASE_TOKEN_SENT.set(true); String tokensSentStr = ctx.getSettings().BILLING_PURCHASE_TOKENS_SENT.get();
Set<String> tokensSent = new HashSet<>(Arrays.asList(tokensSentStr.split(";")));
for (Purchase purchase : purchases) {
tokensSent.add(purchase.getSku());
}
ctx.getSettings().BILLING_PURCHASE_TOKENS_SENT.set(TextUtils.join(";", tokensSent));
if (obj.has("visibleName") && !Algorithms.isEmpty(obj.getString("visibleName"))) { if (obj.has("visibleName") && !Algorithms.isEmpty(obj.getString("visibleName"))) {
ctx.getSettings().BILLING_USER_NAME.set(obj.getString("visibleName")); ctx.getSettings().BILLING_USER_NAME.set(obj.getString("visibleName"));
ctx.getSettings().BILLING_HIDE_USER_NAME.set(false); ctx.getSettings().BILLING_HIDE_USER_NAME.set(false);

View file

@ -0,0 +1,879 @@
package net.osmand.plus.inapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.Version;
import net.osmand.plus.inapp.util.SkuDetails;
import net.osmand.util.Algorithms;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class InAppPurchases {
private static final InAppPurchase FULL_VERSION = new InAppPurchaseFullVersion();
private static final InAppPurchaseDepthContoursFull DEPTH_CONTOURS_FULL = new InAppPurchaseDepthContoursFull();
private static final InAppPurchaseDepthContoursFree DEPTH_CONTOURS_FREE = new InAppPurchaseDepthContoursFree();
private static final InAppPurchaseContourLinesFull CONTOUR_LINES_FULL = new InAppPurchaseContourLinesFull();
private static final InAppPurchaseContourLinesFree CONTOUR_LINES_FREE = new InAppPurchaseContourLinesFree();
private static final InAppSubscription[] LIVE_UPDATES_FULL = new InAppSubscription[]{
new InAppPurchaseLiveUpdatesOldMonthlyFull(),
new InAppPurchaseLiveUpdatesMonthlyFull(),
new InAppPurchaseLiveUpdates3MonthsFull(),
new InAppPurchaseLiveUpdatesAnnualFull()
};
private static final InAppSubscription[] LIVE_UPDATES_FREE = new InAppSubscription[]{
new InAppPurchaseLiveUpdatesOldMonthlyFree(),
new InAppPurchaseLiveUpdatesMonthlyFree(),
new InAppPurchaseLiveUpdates3MonthsFree(),
new InAppPurchaseLiveUpdatesAnnualFree()
};
private InAppPurchase fullVersion;
private InAppPurchase depthContours;
private InAppPurchase contourLines;
private InAppSubscription monthlyLiveUpdates;
private InAppSubscription discountedMonthlyLiveUpdates;
private InAppSubscriptionList liveUpdates;
InAppPurchases(OsmandApplication ctx) {
fullVersion = FULL_VERSION;
if (Version.isFreeVersion(ctx)) {
liveUpdates = new LiveUpdatesInAppPurchasesFree();
} else {
liveUpdates = new LiveUpdatesInAppPurchasesFull();
}
for (InAppSubscription s : liveUpdates.getAllSubscriptions()) {
if (s instanceof InAppPurchaseLiveUpdatesMonthly) {
if (s.isDiscounted()) {
discountedMonthlyLiveUpdates = s;
} else {
monthlyLiveUpdates = s;
}
}
}
if (Version.isFreeVersion(ctx)) {
depthContours = DEPTH_CONTOURS_FREE;
} else {
depthContours = DEPTH_CONTOURS_FULL;
}
if (Version.isFreeVersion(ctx)) {
contourLines = CONTOUR_LINES_FREE;
} else {
contourLines = CONTOUR_LINES_FULL;
}
}
public InAppPurchase getFullVersion() {
return fullVersion;
}
public InAppPurchase getDepthContours() {
return depthContours;
}
public InAppPurchase getContourLines() {
return contourLines;
}
public InAppSubscription getMonthlyLiveUpdates() {
return monthlyLiveUpdates;
}
@Nullable
public InAppSubscription getPurchasedMonthlyLiveUpdates() {
if (monthlyLiveUpdates.isAnyPurchased()) {
return monthlyLiveUpdates;
} else if (discountedMonthlyLiveUpdates.isAnyPurchased()) {
return discountedMonthlyLiveUpdates;
}
return null;
}
public InAppSubscriptionList getLiveUpdates() {
return liveUpdates;
}
public List<InAppPurchase> getAllInAppPurchases() {
List<InAppPurchase> purchases = new ArrayList<>();
purchases.add(fullVersion);
purchases.add(depthContours);
purchases.add(contourLines);
purchases.addAll(liveUpdates.getAllSubscriptions());
return purchases;
}
public boolean isFullVersion(String sku) {
return FULL_VERSION.getSku().equals(sku);
}
public boolean isDepthContours(String sku) {
return DEPTH_CONTOURS_FULL.getSku().equals(sku) || DEPTH_CONTOURS_FREE.getSku().equals(sku);
}
public boolean isContourLines(String sku) {
return CONTOUR_LINES_FULL.getSku().equals(sku) || CONTOUR_LINES_FREE.getSku().equals(sku);
}
public boolean isLiveUpdates(String sku) {
for (InAppPurchase p : LIVE_UPDATES_FULL) {
if (p.getSku().equals(sku)) {
return true;
}
}
for (InAppPurchase p : LIVE_UPDATES_FREE) {
if (p.getSku().equals(sku)) {
return true;
}
}
return false;
}
public abstract static class InAppSubscriptionList {
private List<InAppSubscription> subscriptions;
InAppSubscriptionList(@NonNull InAppSubscription[] subscriptionsArray) {
this.subscriptions = Arrays.asList(subscriptionsArray);;
}
private List<InAppSubscription> getSubscriptions() {
return new ArrayList<>(subscriptions);
}
public List<InAppSubscription> getAllSubscriptions() {
List<InAppSubscription> res = new ArrayList<>();
for (InAppSubscription s : getSubscriptions()) {
res.add(s);
res.addAll(s.getUpgrades());
}
return res;
}
public List<InAppSubscription> getVisibleSubscriptions() {
List<InAppSubscription> res = new ArrayList<>();
for (InAppSubscription s : getSubscriptions()) {
boolean added = false;
if (s.isPurchased()) {
res.add(s);
added = true;
} else {
for (InAppSubscription upgrade : s.getUpgrades()) {
if (upgrade.isPurchased()) {
res.add(upgrade);
added = true;
}
}
}
if (!added) {
for (InAppSubscription upgrade : s.getUpgrades()) {
res.add(upgrade);
added = true;
}
}
if (!added && !s.isDiscounted()) {
res.add(s);
}
}
return res;
}
@Nullable
public InAppSubscription getSubscriptionBySku(@NonNull String sku) {
for (InAppSubscription s : getAllSubscriptions()) {
if (s.getSku().equals(sku)) {
return s;
}
}
return null;
}
public boolean containsSku(@NonNull String sku) {
return getSubscriptionBySku(sku) != null;
}
@Nullable
public InAppSubscription upgradeSubscription(String sku) {
List<InAppSubscription> subscriptions = getAllSubscriptions();
for (InAppSubscription s : subscriptions) {
InAppSubscription upgrade = s.upgradeSubscription(sku);
if (upgrade != null) {
return upgrade;
}
}
return null;
}
}
public static class LiveUpdatesInAppPurchasesFree extends InAppSubscriptionList {
public LiveUpdatesInAppPurchasesFree() {
super(LIVE_UPDATES_FREE);
}
}
public static class LiveUpdatesInAppPurchasesFull extends InAppSubscriptionList {
public LiveUpdatesInAppPurchasesFull() {
super(LIVE_UPDATES_FULL);
}
}
public abstract static class InAppPurchase {
public enum PurchaseState {
UNKNOWN,
PURCHASED,
NOT_PURCHASED
}
private String sku;
private String price;
private double priceValue;
private String priceCurrencyCode;
private PurchaseState purchaseState = PurchaseState.UNKNOWN;
private long purchaseTime;
double monthlyPriceValue;
boolean donationSupported = false;
boolean discounted = false;
private NumberFormat currencyFormatter;
private InAppPurchase(String sku) {
this.sku = sku;
}
private InAppPurchase(String sku, boolean discounted) {
this(sku);
this.discounted = discounted;
}
public String getSku() {
return sku;
}
public String getPrice(Context ctx) {
if (!Algorithms.isEmpty(price)) {
return price;
} else {
return getDefaultPrice(ctx);
}
}
public void setPrice(String price) {
this.price = price;
}
public long getPurchaseTime() {
return purchaseTime;
}
public void setPurchaseTime(long purchaseTime) {
this.purchaseTime = purchaseTime;
}
public String getDefaultPrice(Context ctx) {
return "";
}
public String getDefaultMonthlyPrice(Context ctx) {
return "";
}
public PurchaseState getPurchaseState() {
return purchaseState;
}
public void setPurchaseState(PurchaseState purchaseState) {
this.purchaseState = purchaseState;
}
public boolean isPurchased() {
return purchaseState == PurchaseState.PURCHASED;
}
public boolean fetchRequired() {
return purchaseState == PurchaseState.UNKNOWN;
}
public boolean isDiscounted() {
return discounted;
}
public CharSequence getTitle(Context ctx) {
return "";
}
public CharSequence getDescription(@NonNull Context ctx) {
NumberFormat currencyFormatter = getCurrencyFormatter();
if (currencyFormatter != null) {
return currencyFormatter.format(getPriceValue());
} else {
return ctx.getString(R.string.default_price_currency_format, getPriceValue(), getPriceCurrencyCode());
}
}
public double getPriceValue() {
return priceValue;
}
public void setPriceValue(double priceValue) {
this.priceValue = priceValue;
}
public double getMonthlyPriceValue() {
return monthlyPriceValue;
}
public boolean isDonationSupported() {
return donationSupported;
}
public String getPriceCurrencyCode() {
return priceCurrencyCode;
}
public void setPriceCurrencyCode(String priceCurrencyCode) {
this.priceCurrencyCode = priceCurrencyCode;
Locale currencyLocale = null;
Locale defaultLocale = Locale.getDefault();
try {
Currency defaultCurrency = Currency.getInstance(defaultLocale);
if (defaultCurrency != null && defaultCurrency.getCurrencyCode().equals(priceCurrencyCode)) {
currencyLocale = defaultLocale;
}
} catch (Exception e) {
// ignore
}
if (currencyLocale == null) {
if ("USD".equals(priceCurrencyCode)) {
currencyLocale = Locale.US;
} else if ("EUR".equals(priceCurrencyCode)) {
currencyLocale = Locale.GERMANY;
} else if ("GBP".equals(priceCurrencyCode)) {
currencyLocale = Locale.UK;
} else if ("JPY".equals(priceCurrencyCode)) {
currencyLocale = Locale.JAPAN;
} else if ("CNY".equals(priceCurrencyCode)) {
currencyLocale = Locale.CHINA;
} else if ("UAH".equals(priceCurrencyCode)) {
currencyLocale = new Locale("ukr", "UA");
} else if ("RUB".equals(priceCurrencyCode)) {
currencyLocale = new Locale("rus", "RU");
}
}
if (currencyLocale != null) {
currencyFormatter = NumberFormat.getCurrencyInstance(currencyLocale);
}
}
NumberFormat getCurrencyFormatter() {
return currencyFormatter;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof InAppPurchase) {
InAppPurchase purchase = (InAppPurchase) obj;
return sku.equals(purchase.sku);
} else {
return false;
}
}
@Override
public int hashCode() {
return sku.hashCode();
}
}
public static abstract class InAppSubscription extends InAppPurchase {
private Map<String, InAppSubscription> upgrades = new ConcurrentHashMap<>();
private String skuNoVersion;
private String subscriptionPeriod;
private boolean upgrade = false;
InAppSubscription(@NonNull String skuNoVersion, int version) {
super(skuNoVersion + "_v" + version);
this.skuNoVersion = skuNoVersion;
}
InAppSubscription(@NonNull String sku, boolean discounted) {
super(sku, discounted);
this.skuNoVersion = sku;
}
@NonNull
private List<InAppSubscription> getUpgrades() {
return new ArrayList<>(upgrades.values());
}
@Nullable
InAppSubscription upgradeSubscription(@NonNull String sku) {
InAppSubscription s = null;
if (!upgrade) {
s = upgrades.get(sku);
if (s == null) {
s = newInstance(sku);
if (s != null) {
s.upgrade = true;
upgrades.put(sku, s);
}
}
}
return s;
}
public boolean isAnyPurchased() {
if (isPurchased()) {
return true;
} else {
for (InAppSubscription s : getUpgrades()) {
if (s.isPurchased()) {
return true;
}
}
}
return false;
}
public String getSkuNoVersion() {
return skuNoVersion;
}
public String getSubscriptionPeriod() {
return subscriptionPeriod;
}
public void setSubscriptionPeriod(String subscriptionPeriod) {
this.subscriptionPeriod = subscriptionPeriod;
}
@Override
public CharSequence getDescription(@NonNull Context ctx) {
if (getMonthlyPriceValue() == 0) {
return ctx.getString(R.string.osm_live_payment_month_cost_descr, getDefaultMonthlyPrice(ctx));
} else {
NumberFormat currencyFormatter = getCurrencyFormatter();
if (currencyFormatter != null) {
return ctx.getString(R.string.osm_live_payment_month_cost_descr, currencyFormatter.format(getMonthlyPriceValue()));
} else {
return ctx.getString(R.string.osm_live_payment_month_cost_descr_ex, getMonthlyPriceValue(), getPriceCurrencyCode());
}
}
}
public CharSequence getRenewDescription(@NonNull Context ctx) {
return "";
}
@Nullable
protected abstract InAppSubscription newInstance(@NonNull String sku);
}
public static class InAppPurchaseFullVersion extends InAppPurchase {
private static final String SKU_FULL_VERSION_PRICE = "osmand_full_version_price";
InAppPurchaseFullVersion() {
super(SKU_FULL_VERSION_PRICE);
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.full_version_price);
}
}
public static class InAppPurchaseDepthContours extends InAppPurchase {
private InAppPurchaseDepthContours(String sku) {
super(sku);
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.sea_depth_maps_price);
}
}
public static class InAppPurchaseDepthContoursFull extends InAppPurchaseDepthContours {
private static final String SKU_DEPTH_CONTOURS_FULL = "net.osmand.seadepth_plus";
InAppPurchaseDepthContoursFull() {
super(SKU_DEPTH_CONTOURS_FULL);
}
}
public static class InAppPurchaseDepthContoursFree extends InAppPurchaseDepthContours {
private static final String SKU_DEPTH_CONTOURS_FREE = "net.osmand.seadepth";
InAppPurchaseDepthContoursFree() {
super(SKU_DEPTH_CONTOURS_FREE);
}
}
public static class InAppPurchaseContourLines extends InAppPurchase {
private InAppPurchaseContourLines(String sku) {
super(sku);
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.srtm_plugin_price);
}
}
public static class InAppPurchaseContourLinesFull extends InAppPurchaseContourLines {
private static final String SKU_CONTOUR_LINES_FULL = "net.osmand.contourlines_plus";
InAppPurchaseContourLinesFull() {
super(SKU_CONTOUR_LINES_FULL);
}
}
public static class InAppPurchaseContourLinesFree extends InAppPurchaseContourLines {
private static final String SKU_CONTOUR_LINES_FREE = "net.osmand.contourlines";
InAppPurchaseContourLinesFree() {
super(SKU_CONTOUR_LINES_FREE);
}
}
public static abstract class InAppPurchaseLiveUpdatesMonthly extends InAppSubscription {
InAppPurchaseLiveUpdatesMonthly(String skuNoVersion, int version) {
super(skuNoVersion, version);
donationSupported = true;
}
InAppPurchaseLiveUpdatesMonthly(@NonNull String sku, boolean discounted) {
super(sku, discounted);
donationSupported = true;
}
InAppPurchaseLiveUpdatesMonthly(@NonNull String sku) {
this(sku, false);
}
@Override
public void setPriceValue(double priceValue) {
super.setPriceValue(priceValue);
monthlyPriceValue = priceValue;
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.osm_live_monthly_price);
}
@Override
public String getDefaultMonthlyPrice(Context ctx) {
return ctx.getString(R.string.osm_live_monthly_price);
}
@Override
public CharSequence getTitle(Context ctx) {
return ctx.getString(R.string.osm_live_payment_monthly_title);
}
@Override
public CharSequence getDescription(@NonNull Context ctx) {
CharSequence descr = super.getDescription(ctx);
SpannableStringBuilder text = new SpannableStringBuilder(descr).append(". ").append(ctx.getString(R.string.osm_live_payment_contribute_descr));
text.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), descr.length() + 1, text.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return text;
}
@Override
public CharSequence getRenewDescription(@NonNull Context ctx) {
return ctx.getString(R.string.osm_live_payment_renews_monthly);
}
}
public static class InAppPurchaseLiveUpdatesMonthlyFull extends InAppPurchaseLiveUpdatesMonthly {
private static final String SKU_LIVE_UPDATES_MONTHLY_FULL = "osm_live_subscription_monthly_full";
InAppPurchaseLiveUpdatesMonthlyFull() {
super(SKU_LIVE_UPDATES_MONTHLY_FULL, 1);
}
private InAppPurchaseLiveUpdatesMonthlyFull(@NonNull String sku) {
super(sku);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return sku.startsWith(getSkuNoVersion()) ? new InAppPurchaseLiveUpdatesMonthlyFull(sku) : null;
}
}
public static class InAppPurchaseLiveUpdatesMonthlyFree extends InAppPurchaseLiveUpdatesMonthly {
private static final String SKU_LIVE_UPDATES_MONTHLY_FREE = "osm_live_subscription_monthly_free";
InAppPurchaseLiveUpdatesMonthlyFree() {
super(SKU_LIVE_UPDATES_MONTHLY_FREE, 1);
}
private InAppPurchaseLiveUpdatesMonthlyFree(@NonNull String sku) {
super(sku);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return sku.startsWith(getSkuNoVersion()) ? new InAppPurchaseLiveUpdatesMonthlyFree(sku) : null;
}
}
public static abstract class InAppPurchaseLiveUpdates3Months extends InAppSubscription {
InAppPurchaseLiveUpdates3Months(String skuNoVersion, int version) {
super(skuNoVersion, version);
}
InAppPurchaseLiveUpdates3Months(@NonNull String sku) {
super(sku, false);
}
@Override
public void setPriceValue(double priceValue) {
super.setPriceValue(priceValue);
monthlyPriceValue = priceValue / 3d;
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.osm_live_3_months_price);
}
@Override
public String getDefaultMonthlyPrice(Context ctx) {
return ctx.getString(R.string.osm_live_3_months_monthly_price);
}
@Override
public CharSequence getTitle(Context ctx) {
return ctx.getString(R.string.osm_live_payment_3_months_title);
}
@Override
public CharSequence getRenewDescription(@NonNull Context ctx) {
return ctx.getString(R.string.osm_live_payment_renews_quarterly);
}
}
public static class InAppPurchaseLiveUpdates3MonthsFull extends InAppPurchaseLiveUpdates3Months {
private static final String SKU_LIVE_UPDATES_3_MONTHS_FULL = "osm_live_subscription_3_months_full";
InAppPurchaseLiveUpdates3MonthsFull() {
super(SKU_LIVE_UPDATES_3_MONTHS_FULL, 1);
}
private InAppPurchaseLiveUpdates3MonthsFull(@NonNull String sku) {
super(sku);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return sku.startsWith(getSkuNoVersion()) ? new InAppPurchaseLiveUpdates3MonthsFull(sku) : null;
}
}
public static class InAppPurchaseLiveUpdates3MonthsFree extends InAppPurchaseLiveUpdates3Months {
private static final String SKU_LIVE_UPDATES_3_MONTHS_FREE = "osm_live_subscription_3_months_free";
InAppPurchaseLiveUpdates3MonthsFree() {
super(SKU_LIVE_UPDATES_3_MONTHS_FREE, 1);
}
private InAppPurchaseLiveUpdates3MonthsFree(@NonNull String sku) {
super(sku);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return sku.startsWith(getSkuNoVersion()) ? new InAppPurchaseLiveUpdates3MonthsFree(sku) : null;
}
}
public static abstract class InAppPurchaseLiveUpdatesAnnual extends InAppSubscription {
InAppPurchaseLiveUpdatesAnnual(String skuNoVersion, int version) {
super(skuNoVersion, version);
}
InAppPurchaseLiveUpdatesAnnual(@NonNull String sku) {
super(sku, false);
}
@Override
public void setPriceValue(double priceValue) {
super.setPriceValue(priceValue);
monthlyPriceValue = priceValue / 12d;
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.osm_live_annual_price);
}
@Override
public String getDefaultMonthlyPrice(Context ctx) {
return ctx.getString(R.string.osm_live_annual_monthly_price);
}
@Override
public CharSequence getTitle(Context ctx) {
return ctx.getString(R.string.osm_live_payment_annual_title);
}
@Override
public CharSequence getRenewDescription(@NonNull Context ctx) {
return ctx.getString(R.string.osm_live_payment_renews_annually);
}
}
public static class InAppPurchaseLiveUpdatesAnnualFull extends InAppPurchaseLiveUpdatesAnnual {
private static final String SKU_LIVE_UPDATES_ANNUAL_FULL = "osm_live_subscription_annual_full";
InAppPurchaseLiveUpdatesAnnualFull() {
super(SKU_LIVE_UPDATES_ANNUAL_FULL, 1);
}
private InAppPurchaseLiveUpdatesAnnualFull(@NonNull String sku) {
super(sku);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return sku.startsWith(getSkuNoVersion()) ? new InAppPurchaseLiveUpdatesAnnualFull(sku) : null;
}
}
public static class InAppPurchaseLiveUpdatesAnnualFree extends InAppPurchaseLiveUpdatesAnnual {
private static final String SKU_LIVE_UPDATES_ANNUAL_FREE = "osm_live_subscription_annual_free";
InAppPurchaseLiveUpdatesAnnualFree() {
super(SKU_LIVE_UPDATES_ANNUAL_FREE, 1);
}
private InAppPurchaseLiveUpdatesAnnualFree(@NonNull String sku) {
super(sku);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return sku.startsWith(getSkuNoVersion()) ? new InAppPurchaseLiveUpdatesAnnualFree(sku) : null;
}
}
public static class InAppPurchaseLiveUpdatesOldMonthly extends InAppPurchaseLiveUpdatesMonthly {
InAppPurchaseLiveUpdatesOldMonthly(String sku) {
super(sku, true);
}
@Override
public String getDefaultPrice(Context ctx) {
return ctx.getString(R.string.osm_live_default_price);
}
@Override
public String getDefaultMonthlyPrice(Context ctx) {
return ctx.getString(R.string.osm_live_default_price);
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return null;
}
}
public static class InAppPurchaseLiveUpdatesOldMonthlyFull extends InAppPurchaseLiveUpdatesOldMonthly {
private static final String SKU_LIVE_UPDATES_OLD_MONTHLY_FULL = "osm_live_subscription_2";
InAppPurchaseLiveUpdatesOldMonthlyFull() {
super(SKU_LIVE_UPDATES_OLD_MONTHLY_FULL);
}
}
public static class InAppPurchaseLiveUpdatesOldMonthlyFree extends InAppPurchaseLiveUpdatesOldMonthly {
private static final String SKU_LIVE_UPDATES_OLD_MONTHLY_FREE = "osm_free_live_subscription_2";
InAppPurchaseLiveUpdatesOldMonthlyFree() {
super(SKU_LIVE_UPDATES_OLD_MONTHLY_FREE);
}
}
public static class InAppPurchaseLiveUpdatesOldSubscription extends InAppSubscription {
private SkuDetails details;
InAppPurchaseLiveUpdatesOldSubscription(@NonNull SkuDetails details) {
super(details.getSku(), true);
this.details = details;
}
@Override
public String getDefaultPrice(Context ctx) {
return "";
}
@Override
public CharSequence getTitle(Context ctx) {
return details.getTitle();
}
@Override
public CharSequence getDescription(@NonNull Context ctx) {
return details.getDescription();
}
@Nullable
@Override
protected InAppSubscription newInstance(@NonNull String sku) {
return null;
}
}
}

View file

@ -63,12 +63,12 @@ public class Inventory {
} }
/** Returns a list of all owned product IDs. */ /** Returns a list of all owned product IDs. */
List<String> getAllOwnedSkus() { public List<String> getAllOwnedSkus() {
return new ArrayList<String>(mPurchaseMap.keySet()); return new ArrayList<String>(mPurchaseMap.keySet());
} }
/** Returns a list of all owned product IDs of a given type */ /** Returns a list of all owned product IDs of a given type */
List<String> getAllOwnedSkus(String itemType) { public List<String> getAllOwnedSkus(String itemType) {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
for (Purchase p : mPurchaseMap.values()) { for (Purchase p : mPurchaseMap.values()) {
if (p.getItemType().equals(itemType)) result.add(p.getSku()); if (p.getItemType().equals(itemType)) result.add(p.getSku());

View file

@ -26,6 +26,9 @@ public class SkuDetails {
String mSku; String mSku;
String mType; String mType;
String mPrice; String mPrice;
long mPriceAmountMicros;
String mPriceCurrencyCode;
String mSubscriptionPeriod;
String mTitle; String mTitle;
String mDescription; String mDescription;
String mJson; String mJson;
@ -41,6 +44,9 @@ public class SkuDetails {
mSku = o.optString("productId"); mSku = o.optString("productId");
mType = o.optString("type"); mType = o.optString("type");
mPrice = o.optString("price"); mPrice = o.optString("price");
mPriceAmountMicros = o.optLong("price_amount_micros");
mPriceCurrencyCode = o.optString("price_currency_code");
mSubscriptionPeriod = o.optString("subscriptionPeriod");
mTitle = o.optString("title"); mTitle = o.optString("title");
mDescription = o.optString("description"); mDescription = o.optString("description");
} }
@ -48,6 +54,15 @@ public class SkuDetails {
public String getSku() { return mSku; } public String getSku() { return mSku; }
public String getType() { return mType; } public String getType() { return mType; }
public String getPrice() { return mPrice; } public String getPrice() { return mPrice; }
public long getPriceAmountMicros() {
return mPriceAmountMicros;
}
public String getPriceCurrencyCode() {
return mPriceCurrencyCode;
}
public String getSubscriptionPeriod() {
return mSubscriptionPeriod;
}
public String getTitle() { return mTitle; } public String getTitle() { return mTitle; }
public String getDescription() { return mDescription; } public String getDescription() { return mDescription; }

View file

@ -14,22 +14,16 @@ import android.os.Bundle;
import android.support.annotation.DrawableRes; import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.app.AlertDialog.Builder; import android.support.v7.app.AlertDialog.Builder;
import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.SwitchCompat;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AbsListView; import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button; import android.widget.Button;
import android.widget.CompoundButton; import android.widget.CompoundButton;
import android.widget.ExpandableListView; import android.widget.ExpandableListView;
@ -47,10 +41,12 @@ import net.osmand.plus.activities.LocalIndexInfo;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter; import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.OsmandInAppPurchaseActivity; import net.osmand.plus.activities.OsmandInAppPurchaseActivity;
import net.osmand.plus.base.BaseOsmAndFragment; import net.osmand.plus.base.BaseOsmAndFragment;
import net.osmand.plus.chooseplan.ChoosePlanDialogFragment;
import net.osmand.plus.download.ui.AbstractLoadLocalIndexTask; import net.osmand.plus.download.ui.AbstractLoadLocalIndexTask;
import net.osmand.plus.inapp.InAppPurchaseHelper; import net.osmand.plus.inapp.InAppPurchaseHelper;
import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseListener; import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseListener;
import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseTaskType; import net.osmand.plus.inapp.InAppPurchaseHelper.InAppPurchaseTaskType;
import net.osmand.plus.inapp.InAppPurchases.InAppSubscription;
import net.osmand.plus.resources.IncrementalChangesManager; import net.osmand.plus.resources.IncrementalChangesManager;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
@ -147,18 +143,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
if (!Version.isDeveloperVersion(getMyApplication())) { if (!Version.isDeveloperVersion(getMyApplication())) {
subscriptionHeader = inflater.inflate(R.layout.live_updates_header, listView, false); subscriptionHeader = inflater.inflate(R.layout.live_updates_header, listView, false);
updateSubscriptionHeader(); updateSubscriptionHeader();
listView.addHeaderView(subscriptionHeader, "subscriptionHeader", false);
listView.addHeaderView(subscriptionHeader);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0 && !processing && InAppPurchaseHelper.isSubscribedToLiveUpdates(getMyApplication())) {
SubscriptionFragment subscriptionFragment = new SubscriptionFragment();
subscriptionFragment.setEditMode(true);
subscriptionFragment.show(getChildFragmentManager(), SubscriptionFragment.TAG);
}
}
});
} }
listView.setAdapter(adapter); listView.setAdapter(adapter);
@ -179,8 +164,13 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
TextView regionNameTextView = (TextView) subscriptionHeader.findViewById(R.id.regionTextView); TextView regionNameTextView = (TextView) subscriptionHeader.findViewById(R.id.regionTextView);
statusTextView.setText(getString(R.string.osm_live_active)); statusTextView.setText(getString(R.string.osm_live_active));
statusIcon.setImageDrawable(getMyApplication().getUIUtilities().getThemedIcon(R.drawable.ic_action_done)); statusIcon.setImageDrawable(getMyApplication().getUIUtilities().getThemedIcon(R.drawable.ic_action_done));
regionNameHeaderTextView.setText(R.string.osm_live_support_region); regionNameHeaderTextView.setText(R.string.osm_live_support_region);
String countryName = getSettings().BILLING_USER_COUNTRY.get(); String countryName = getSettings().BILLING_USER_COUNTRY.get();
InAppPurchaseHelper purchaseHelper = getInAppPurchaseHelper();
if (purchaseHelper != null) {
InAppSubscription monthlyPurchased = purchaseHelper.getPurchasedMonthlyLiveUpdates();
if (monthlyPurchased != null && monthlyPurchased.isDonationSupported()) {
if (Algorithms.isEmpty(countryName)) { if (Algorithms.isEmpty(countryName)) {
if (getSettings().BILLING_USER_COUNTRY_DOWNLOAD_NAME.get().equals(OsmandSettings.BILLING_USER_DONATION_NONE_PARAMETER)) { if (getSettings().BILLING_USER_COUNTRY_DOWNLOAD_NAME.get().equals(OsmandSettings.BILLING_USER_DONATION_NONE_PARAMETER)) {
regionNameHeaderTextView.setText(R.string.default_buttons_support); regionNameHeaderTextView.setText(R.string.default_buttons_support);
@ -189,8 +179,38 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
countryName = getString(R.string.shared_string_world); countryName = getString(R.string.shared_string_world);
} }
} }
} else {
regionNameHeaderTextView.setText(R.string.default_buttons_support);
countryName = getString(R.string.osmand_team);
}
} else {
regionNameHeaderTextView.setText(R.string.default_buttons_support);
countryName = getString(R.string.osmand_team);
}
regionNameTextView.setText(countryName); regionNameTextView.setText(countryName);
View subscriptionsButton = subscriptionHeader.findViewById(R.id.button_subscriptions);
View settingsButtonContainer = subscriptionHeader.findViewById(R.id.button_settings_container);
View settingsButton = subscriptionHeader.findViewById(R.id.button_settings);
subscriptionsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ChoosePlanDialogFragment.showOsmLiveInstance(getActivity().getSupportFragmentManager());
}
});
if (isDonationSupported()) {
settingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDonationSettings();
}
});
settingsButtonContainer.setVisibility(View.VISIBLE);
} else {
settingsButton.setOnClickListener(null);
settingsButtonContainer.setVisibility(View.GONE);
}
subscriptionBanner.setVisibility(View.GONE); subscriptionBanner.setVisibility(View.GONE);
subscriptionInfo.setVisibility(View.VISIBLE); subscriptionInfo.setVisibility(View.VISIBLE);
} else { } else {
@ -209,8 +229,10 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
subscriptionButton.setOnClickListener(new View.OnClickListener() { subscriptionButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
SubscriptionFragment subscriptionFragment = new SubscriptionFragment(); FragmentActivity activity = getActivity();
subscriptionFragment.show(getChildFragmentManager(), SubscriptionFragment.TAG); if (activity != null) {
ChoosePlanDialogFragment.showOsmLiveInstance(activity.getSupportFragmentManager());
}
} }
}); });
@ -229,10 +251,6 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
enableProgress(); enableProgress();
} }
} }
if (((OsmLiveActivity) getActivity()).shouldOpenSubscription()) {
SubscriptionFragment subscriptionFragment = new SubscriptionFragment();
subscriptionFragment.show(getChildFragmentManager(), SubscriptionFragment.TAG);
}
} }
@Override @Override
@ -251,34 +269,18 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
} }
} }
@SuppressWarnings("deprecation") private boolean isDonationSupported() {
@Override InAppPurchaseHelper purchaseHelper = getInAppPurchaseHelper();
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (purchaseHelper != null) {
if (InAppPurchaseHelper.isSubscribedToLiveUpdates(getMyApplication()) InAppSubscription monthlyPurchased = purchaseHelper.getPurchasedMonthlyLiveUpdates();
&& !Version.isDeveloperVersion(getMyApplication())) { return monthlyPurchased != null && monthlyPurchased.isDonationSupported();
}
ActionBar actionBar = getMyActivity().getSupportActionBar(); return false;
if (actionBar != null) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
} }
SubMenu split = menu.addSubMenu(R.string.shared_string_more_actions); private void showDonationSettings() {
split.setIcon(R.drawable.ic_overflow_menu_white);
MenuItemCompat.setShowAsAction(split.getItem(), MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
MenuItem item = split.add(0, SUBSCRIPTION_SETTINGS, 0, R.string.osm_live_subscription_settings);
MenuItemCompat.setShowAsAction(item, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == SUBSCRIPTION_SETTINGS && !processing) {
SubscriptionFragment subscriptionFragment = new SubscriptionFragment(); SubscriptionFragment subscriptionFragment = new SubscriptionFragment();
subscriptionFragment.setEditMode(true);
subscriptionFragment.show(getChildFragmentManager(), SubscriptionFragment.TAG); subscriptionFragment.show(getChildFragmentManager(), SubscriptionFragment.TAG);
return true;
}
return super.onOptionsItemSelected(item);
} }
protected class LocalIndexesAdapter extends OsmandBaseExpandableListAdapter { protected class LocalIndexesAdapter extends OsmandBaseExpandableListAdapter {
@ -715,7 +717,7 @@ public class LiveUpdatesFragment extends BaseOsmAndFragment implements InAppPurc
@Override @Override
public void onItemPurchased(String sku, boolean active) { public void onItemPurchased(String sku, boolean active) {
InAppPurchaseHelper purchaseHelper = getInAppPurchaseHelper(); InAppPurchaseHelper purchaseHelper = getInAppPurchaseHelper();
if (purchaseHelper != null && purchaseHelper.getSkuLiveUpdates().equals(sku)) { if (purchaseHelper != null && purchaseHelper.getLiveUpdates().containsSku(sku)) {
updateSubscriptionHeader(); updateSubscriptionHeader();
} }

View file

@ -34,11 +34,9 @@ import java.util.TimeZone;
public class OsmLiveActivity extends AbstractDownloadActivity implements DownloadEvents, ChoosePlanDialogListener { public class OsmLiveActivity extends AbstractDownloadActivity implements DownloadEvents, ChoosePlanDialogListener {
private final static Log LOG = PlatformUtil.getLog(OsmLiveActivity.class); private final static Log LOG = PlatformUtil.getLog(OsmLiveActivity.class);
public final static String OPEN_SUBSCRIPTION_INTENT_PARAM = "open_subscription_intent_param";
public final static String SHOW_SETTINGS_ONLY_INTENT_PARAM = "show_settings_only_intent_param"; public final static String SHOW_SETTINGS_ONLY_INTENT_PARAM = "show_settings_only_intent_param";
private LiveUpdatesFragmentPagerAdapter pagerAdapter; private LiveUpdatesFragmentPagerAdapter pagerAdapter;
private boolean openSubscription;
private boolean showSettingOnly; private boolean showSettingOnly;
private GetLastUpdateDateTask getLastUpdateDateTask; private GetLastUpdateDateTask getLastUpdateDateTask;
private static final String URL = "https://osmand.net/api/osmlive_status"; private static final String URL = "https://osmand.net/api/osmlive_status";
@ -51,10 +49,8 @@ public class OsmLiveActivity extends AbstractDownloadActivity implements Downloa
Intent intent = getIntent(); Intent intent = getIntent();
if (intent != null && intent.getExtras() != null) { if (intent != null && intent.getExtras() != null) {
openSubscription = intent.getExtras().getBoolean(OPEN_SUBSCRIPTION_INTENT_PARAM, false);
showSettingOnly = intent.getExtras().getBoolean(SHOW_SETTINGS_ONLY_INTENT_PARAM, false); showSettingOnly = intent.getExtras().getBoolean(SHOW_SETTINGS_ONLY_INTENT_PARAM, false);
} else if (savedInstanceState != null) { } else if (savedInstanceState != null) {
openSubscription = savedInstanceState.getBoolean(OPEN_SUBSCRIPTION_INTENT_PARAM, false);
showSettingOnly = savedInstanceState.getBoolean(SHOW_SETTINGS_ONLY_INTENT_PARAM, false); showSettingOnly = savedInstanceState.getBoolean(SHOW_SETTINGS_ONLY_INTENT_PARAM, false);
} }
@ -109,13 +105,12 @@ public class OsmLiveActivity extends AbstractDownloadActivity implements Downloa
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
outState.putBoolean(OPEN_SUBSCRIPTION_INTENT_PARAM, openSubscription);
outState.putBoolean(SHOW_SETTINGS_ONLY_INTENT_PARAM, showSettingOnly); outState.putBoolean(SHOW_SETTINGS_ONLY_INTENT_PARAM, showSettingOnly);
} }
@Override @Override
public void onChoosePlanDialogDismiss() { public void onChoosePlanDialogDismiss() {
finish(); //finish();
} }
public boolean isShowSettingOnly() { public boolean isShowSettingOnly() {
@ -140,10 +135,6 @@ public class OsmLiveActivity extends AbstractDownloadActivity implements Downloa
((LiveUpdatesFragment) pagerAdapter.fragments[0]).notifyLiveUpdatesChanged(); ((LiveUpdatesFragment) pagerAdapter.fragments[0]).notifyLiveUpdatesChanged();
} }
public boolean shouldOpenSubscription() {
return openSubscription;
}
private static class GetLastUpdateDateTask extends AsyncTask<Void, Void, String> { private static class GetLastUpdateDateTask extends AsyncTask<Void, Void, String> {
private OsmandApplication app; private OsmandApplication app;

View file

@ -42,7 +42,6 @@ import java.util.Map;
public class SubscriptionFragment extends BaseOsmAndDialogFragment implements InAppPurchaseListener, OnFragmentInteractionListener { public class SubscriptionFragment extends BaseOsmAndDialogFragment implements InAppPurchaseListener, OnFragmentInteractionListener {
public static final String TAG = "SubscriptionFragment"; public static final String TAG = "SubscriptionFragment";
private static final String EDIT_MODE_ID = "edit_mode_id";
private static final String USER_NAME_ID = "user_name_id"; private static final String USER_NAME_ID = "user_name_id";
private static final String EMAIL_ID = "email_id"; private static final String EMAIL_ID = "email_id";
private static final String COUNTRY_ITEM_ID = "country_id"; private static final String COUNTRY_ITEM_ID = "country_id";
@ -51,7 +50,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
private OsmandSettings settings; private OsmandSettings settings;
private ProgressDialog dlg; private ProgressDialog dlg;
private boolean editMode;
private boolean donation; private boolean donation;
private String prevEmail; private String prevEmail;
@ -59,10 +57,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
private CountrySelectionFragment countrySelectionFragment = new CountrySelectionFragment(); private CountrySelectionFragment countrySelectionFragment = new CountrySelectionFragment();
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
@Nullable @Nullable
public InAppPurchaseHelper getInAppPurchaseHelper() { public InAppPurchaseHelper getInAppPurchaseHelper() {
Activity activity = getActivity(); Activity activity = getActivity();
@ -75,8 +69,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
@Override @Override
public void onSaveInstanceState(Bundle outState) { public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(EDIT_MODE_ID, editMode);
View view = getView(); View view = getView();
if (view != null) { if (view != null) {
EditText userNameEdit = (EditText) view.findViewById(R.id.userNameEdit); EditText userNameEdit = (EditText) view.findViewById(R.id.userNameEdit);
@ -91,7 +83,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
outState.putSerializable(COUNTRY_ITEM_ID, selectedCountryItem); outState.putSerializable(COUNTRY_ITEM_ID, selectedCountryItem);
} }
} }
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
} }
@ -99,10 +90,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
editMode = savedInstanceState.getBoolean(EDIT_MODE_ID);
}
settings = getMyApplication().getSettings(); settings = getMyApplication().getSettings();
prevEmail = settings.BILLING_USER_EMAIL.get(); prevEmail = settings.BILLING_USER_EMAIL.get();
} }
@ -134,11 +121,7 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
View view = inflater.inflate(R.layout.subscription_fragment, container, false); View view = inflater.inflate(R.layout.subscription_fragment, container, false);
ImageButton closeButton = (ImageButton) view.findViewById(R.id.closeButton); ImageButton closeButton = (ImageButton) view.findViewById(R.id.closeButton);
if (editMode) {
closeButton.setImageDrawable(getMyApplication().getUIUtilities().getIcon(R.drawable.ic_action_mode_back)); closeButton.setImageDrawable(getMyApplication().getUIUtilities().getIcon(R.drawable.ic_action_mode_back));
} else {
closeButton.setImageDrawable(getMyApplication().getUIUtilities().getIcon(R.drawable.ic_action_remove_dark));
}
closeButton.setOnClickListener(new View.OnClickListener() { closeButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
@ -147,11 +130,7 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
}); });
TextView title = (TextView) view.findViewById(R.id.titleTextView); TextView title = (TextView) view.findViewById(R.id.titleTextView);
if (editMode) {
title.setText(getString(R.string.osm_live_subscription_settings)); title.setText(getString(R.string.osm_live_subscription_settings));
} else {
title.setText(getString(R.string.osm_live_subscription));
}
final View headerLayout = view.findViewById(R.id.headerLayout); final View headerLayout = view.findViewById(R.id.headerLayout);
final View paramsLayout = view.findViewById(R.id.paramsLayout); final View paramsLayout = view.findViewById(R.id.paramsLayout);
@ -204,12 +183,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
final CheckBox hideUserNameCheckbox = (CheckBox) view.findViewById(R.id.hideUserNameCheckbox); final CheckBox hideUserNameCheckbox = (CheckBox) view.findViewById(R.id.hideUserNameCheckbox);
hideUserNameCheckbox.setChecked(hideUserName); hideUserNameCheckbox.setChecked(hideUserName);
View editModeBottomView = view.findViewById(R.id.editModeBottomView);
View purchaseCard = view.findViewById(R.id.purchaseCard);
if (editMode) {
editModeBottomView.setVisibility(View.VISIBLE);
purchaseCard.setVisibility(View.GONE);
Button saveChangesButton = (Button) view.findViewById(R.id.saveChangesButton); Button saveChangesButton = (Button) view.findViewById(R.id.saveChangesButton);
saveChangesButton.setOnClickListener(new View.OnClickListener() { saveChangesButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
@ -254,7 +227,7 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
app.getSettings().BILLING_USER_COUNTRY_DOWNLOAD_NAME.set(preferredCountry); app.getSettings().BILLING_USER_COUNTRY_DOWNLOAD_NAME.set(preferredCountry);
Fragment parent = getParentFragment(); Fragment parent = getParentFragment();
if (parent != null && parent instanceof LiveUpdatesFragment) { if (parent instanceof LiveUpdatesFragment) {
((LiveUpdatesFragment) parent).updateSubscriptionHeader(); ((LiveUpdatesFragment) parent).updateSubscriptionHeader();
} }
@ -274,31 +247,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
} }
}); });
} else {
editModeBottomView.setVisibility(View.GONE);
purchaseCard.setVisibility(View.VISIBLE);
updatePrice(view);
final Button subscribeButton = (Button) view.findViewById(R.id.subscribeButton);
subscribeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
InAppPurchaseHelper purchaseHelper = getInAppPurchaseHelper();
if (purchaseHelper != null) {
if (applySettings(userNameEdit.getText().toString().trim(),
emailEdit.getText().toString().trim(), hideUserNameCheckbox.isChecked())) {
purchaseHelper.purchaseLiveUpdates(getActivity(),
settings.BILLING_USER_EMAIL.get(),
settings.BILLING_USER_NAME.get(),
settings.BILLING_USER_COUNTRY_DOWNLOAD_NAME.get(),
settings.BILLING_HIDE_USER_NAME.get());
}
}
}
});
}
setThemedDrawable((ImageView) view.findViewById(R.id.userNameIcon), R.drawable.ic_person); setThemedDrawable((ImageView) view.findViewById(R.id.userNameIcon), R.drawable.ic_person);
setThemedDrawable((ImageView) view.findViewById(R.id.emailIcon), R.drawable.ic_action_message); setThemedDrawable((ImageView) view.findViewById(R.id.emailIcon), R.drawable.ic_action_message);
setThemedDrawable((ImageView) view.findViewById(R.id.countryIcon), R.drawable.ic_world_globe_dark); setThemedDrawable((ImageView) view.findViewById(R.id.countryIcon), R.drawable.ic_world_globe_dark);
@ -351,7 +299,6 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
@Override @Override
public void onGetItems() { public void onGetItems() {
updatePrice(getView());
} }
@Override @Override
@ -390,17 +337,4 @@ public class SubscriptionFragment extends BaseOsmAndDialogFragment implements In
} }
} }
} }
private void updatePrice(View view) {
if (view == null) {
view = getView();
}
if (view != null) {
TextView priceTextView = (TextView) view.findViewById(R.id.priceTextView);
InAppPurchaseHelper purchaseHelper = getInAppPurchaseHelper();
if (purchaseHelper.getLiveUpdatesPrice() != null) {
priceTextView.setText(purchaseHelper.getLiveUpdatesPrice());
}
}
}
} }

View file

@ -1,5 +1,6 @@
package net.osmand.plus.mapcontextmenu.other; package net.osmand.plus.mapcontextmenu.other;
import android.content.Context;
import android.graphics.Matrix; import android.graphics.Matrix;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
@ -24,14 +25,14 @@ import net.osmand.data.LatLon;
import net.osmand.data.QuadRect; import net.osmand.data.QuadRect;
import net.osmand.data.RotatedTileBox; import net.osmand.data.RotatedTileBox;
import net.osmand.plus.GPXUtilities; import net.osmand.plus.GPXUtilities;
import net.osmand.plus.GPXUtilities.GPXFile;
import net.osmand.plus.GPXUtilities.GPXTrackAnalysis; import net.osmand.plus.GPXUtilities.GPXTrackAnalysis;
import net.osmand.plus.GPXUtilities.TrkSegment; import net.osmand.plus.GPXUtilities.TrkSegment;
import net.osmand.plus.GPXUtilities.WptPt; import net.osmand.plus.GPXUtilities.WptPt;
import net.osmand.plus.GPXUtilities.GPXFile;
import net.osmand.plus.GpxSelectionHelper.GpxDisplayItem; import net.osmand.plus.GpxSelectionHelper.GpxDisplayItem;
import net.osmand.plus.UiUtilities;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.UiUtilities;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.dialogs.DirectionsDialogs; import net.osmand.plus.dialogs.DirectionsDialogs;
import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.AndroidUiHelper;
@ -630,6 +631,11 @@ public class TrackDetailsMenu {
super.updateToolbar(view); super.updateToolbar(view);
view.getShadowView().setVisibility(View.GONE); view.getShadowView().setVisibility(View.GONE);
} }
@Override
public int getStatusBarColor(Context context, boolean night) {
return NO_COLOR;
}
} }
public class TrackChartPoints { public class TrackChartPoints {

View file

@ -112,15 +112,14 @@ public class MapMarkersDbHelper {
private SQLiteConnection openConnection(boolean readonly) { private SQLiteConnection openConnection(boolean readonly) {
SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly); SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly);
if (conn == null) { if (conn == null) {
return conn; return null;
} }
int version = conn.getVersion(); if (conn.getVersion() < DB_VERSION) {
if (version == 0 || DB_VERSION != version) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false);
} }
version = conn.getVersion(); int version = conn.getVersion();
conn.setVersion(DB_VERSION); conn.setVersion(DB_VERSION);
if (version == 0) { if (version == 0) {
onCreate(conn); onCreate(conn);

View file

@ -1,6 +1,7 @@
package net.osmand.plus.mapmarkers; package net.osmand.plus.mapmarkers;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Build; import android.os.Build;
@ -965,5 +966,10 @@ public class PlanRouteFragment extends BaseOsmAndFragment implements OsmAndLocat
shadow.setVisibility(View.GONE); shadow.setVisibility(View.GONE);
} }
} }
@Override
public int getStatusBarColor(Context context, boolean night) {
return NO_COLOR;
}
} }
} }

View file

@ -1,6 +1,7 @@
package net.osmand.plus.measurementtool; package net.osmand.plus.measurementtool;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
@ -1579,5 +1580,10 @@ public class MeasurementToolFragment extends BaseOsmAndFragment {
shadow.setVisibility(View.GONE); shadow.setVisibility(View.GONE);
} }
} }
@Override
public int getStatusBarColor(Context context, boolean night) {
return NO_COLOR;
}
} }
} }

View file

@ -198,7 +198,7 @@ public class OsmEditingPlugin extends OsmandPlugin {
} else if (resId == R.string.context_menu_item_modify_note) { } else if (resId == R.string.context_menu_item_modify_note) {
modifyOsmNote(mapActivity, (OsmNotesPoint) selectedObj); modifyOsmNote(mapActivity, (OsmNotesPoint) selectedObj);
} else if (resId == R.string.poi_context_menu_modify) { } else if (resId == R.string.poi_context_menu_modify) {
if (selectedObj instanceof TransportStop) { if (selectedObj instanceof TransportStop && ((TransportStop) selectedObj).getAmenity() != null) {
EditPoiDialogFragment.showEditInstance(((TransportStop) selectedObj).getAmenity(), mapActivity); EditPoiDialogFragment.showEditInstance(((TransportStop) selectedObj).getAmenity(), mapActivity);
} else if (selectedObj instanceof MapObject) { } else if (selectedObj instanceof MapObject) {
EditPoiDialogFragment.showEditInstance((MapObject) selectedObj, mapActivity); EditPoiDialogFragment.showEditInstance((MapObject) selectedObj, mapActivity);

View file

@ -447,18 +447,18 @@ public class PoiFiltersHelper {
private SQLiteConnection openConnection(boolean readonly) { private SQLiteConnection openConnection(boolean readonly) {
conn = context.getSQLiteAPI().getOrCreateDatabase(DATABASE_NAME, readonly); conn = context.getSQLiteAPI().getOrCreateDatabase(DATABASE_NAME, readonly);
if (conn.getVersion() == 0 || DATABASE_VERSION != conn.getVersion()) { if (conn.getVersion() < DATABASE_VERSION) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = context.getSQLiteAPI().getOrCreateDatabase(DATABASE_NAME, false); conn = context.getSQLiteAPI().getOrCreateDatabase(DATABASE_NAME, false);
} }
if (conn.getVersion() == 0) { int version = conn.getVersion();
conn.setVersion(DATABASE_VERSION); conn.setVersion(DATABASE_VERSION);
if (version == 0) {
onCreate(conn); onCreate(conn);
} else { } else {
onUpgrade(conn, conn.getVersion(), DATABASE_VERSION); onUpgrade(conn, version, DATABASE_VERSION);
} }
} }
return conn; return conn;
} }
@ -477,7 +477,6 @@ public class PoiFiltersHelper {
conn.execSQL("ALTER TABLE " + FILTER_NAME + " ADD " + FILTER_COL_HISTORY + " int DEFAULT " + FALSE_INT); conn.execSQL("ALTER TABLE " + FILTER_NAME + " ADD " + FILTER_COL_HISTORY + " int DEFAULT " + FALSE_INT);
conn.execSQL("ALTER TABLE " + FILTER_NAME + " ADD " + FILTER_COL_DELETED + " int DEFAULT " + FALSE_INT); conn.execSQL("ALTER TABLE " + FILTER_NAME + " ADD " + FILTER_COL_DELETED + " int DEFAULT " + FALSE_INT);
} }
conn.setVersion(newVersion);
} }
private void deleteOldFilters(SQLiteConnection conn) { private void deleteOldFilters(SQLiteConnection conn) {

View file

@ -484,6 +484,10 @@ public class PoiUIFilter implements SearchPoiTypeFilter, Comparable<PoiUIFilter>
return name; return name;
} }
public void setName(String name) {
this.name = name;
}
public String getGeneratedName(int chars) { public String getGeneratedName(int chars) {
if (!filterId.equals(CUSTOM_FILTER_ID) || if (!filterId.equals(CUSTOM_FILTER_ID) ||
areAllTypesAccepted() || acceptedTypes.isEmpty()) { areAllTypesAccepted() || acceptedTypes.isEmpty()) {

View file

@ -936,15 +936,5 @@ public class VoiceRouter {
} }
public void notifyOnVoiceMessage() { public void notifyOnVoiceMessage() {
if (settings.WAKE_ON_VOICE_INT.get() > 0) {
router.getApplication().runInUIThread(new Runnable() {
@Override
public void run() {
for (VoiceMessageListener lnt : voiceMessageListeners.keySet()) {
lnt.onVoiceMessage();
}
}
});
}
} }
} }

View file

@ -22,6 +22,7 @@ import android.support.v7.widget.Toolbar;
import android.text.Editable; import android.text.Editable;
import android.text.Spannable; import android.text.Spannable;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan; import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent; import android.view.KeyEvent;
@ -178,6 +179,7 @@ public class QuickSearchDialogFragment extends DialogFragment implements OsmAndC
private boolean newSearch; private boolean newSearch;
private boolean interruptedSearch; private boolean interruptedSearch;
private boolean pausedSearch;
private long hideTimeMs; private long hideTimeMs;
private boolean expired; private boolean expired;
private boolean poiFilterApplied; private boolean poiFilterApplied;
@ -985,12 +987,17 @@ public class QuickSearchDialogFragment extends DialogFragment implements OsmAndC
} }
expired = false; expired = false;
paused = false; paused = false;
if (pausedSearch && !TextUtils.isEmpty(searchQuery)) {
runSearch();
}
pausedSearch = false;
} }
@Override @Override
public void onPause() { public void onPause() {
super.onPause(); super.onPause();
paused = true; paused = true;
pausedSearch = searching;
hideTimeMs = System.currentTimeMillis(); hideTimeMs = System.currentTimeMillis();
stopLocationUpdate(); stopLocationUpdate();
hideProgressBar(); hideProgressBar();

View file

@ -1,6 +1,8 @@
package net.osmand.plus.search; package net.osmand.plus.search;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import net.osmand.binary.BinaryMapIndexReader; import net.osmand.binary.BinaryMapIndexReader;
import net.osmand.binary.BinaryMapIndexReader.SearchPoiTypeFilter; import net.osmand.binary.BinaryMapIndexReader.SearchPoiTypeFilter;
@ -19,12 +21,15 @@ import net.osmand.plus.GpxSelectionHelper;
import net.osmand.plus.OsmAndFormatter; import net.osmand.plus.OsmAndFormatter;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.helpers.SearchHistoryHelper; import net.osmand.plus.helpers.SearchHistoryHelper;
import net.osmand.plus.helpers.SearchHistoryHelper.HistoryEntry; import net.osmand.plus.helpers.SearchHistoryHelper.HistoryEntry;
import net.osmand.plus.poi.NominatimPoiFilter; import net.osmand.plus.poi.NominatimPoiFilter;
import net.osmand.plus.poi.PoiFiltersHelper; import net.osmand.plus.poi.PoiFiltersHelper;
import net.osmand.plus.poi.PoiUIFilter; import net.osmand.plus.poi.PoiUIFilter;
import net.osmand.plus.resources.ResourceManager.ResourceListener; import net.osmand.plus.resources.ResourceManager.ResourceListener;
import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarController;
import net.osmand.plus.views.mapwidgets.MapInfoWidgetsFactory.TopToolbarControllerType;
import net.osmand.search.SearchUICore; import net.osmand.search.SearchUICore;
import net.osmand.search.SearchUICore.SearchResultCollection; import net.osmand.search.SearchUICore.SearchResultCollection;
import net.osmand.search.SearchUICore.SearchResultMatcher; import net.osmand.search.SearchUICore.SearchResultMatcher;
@ -468,4 +473,49 @@ public class QuickSearchHelper implements ResourceListener {
public void onMapsIndexed() { public void onMapsIndexed() {
mapsIndexed = true; mapsIndexed = true;
} }
public static void showPoiFilterOnMap(@NonNull final MapActivity mapActivity,
@NonNull final PoiUIFilter filter,
@Nullable final Runnable action) {
final TopToolbarController controller = new PoiFilterBarController();
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
hidePoiFilterOnMap(mapActivity, controller, action);
mapActivity.showQuickSearch(filter);
}
};
controller.setOnBackButtonClickListener(listener);
controller.setOnTitleClickListener(listener);
controller.setOnCloseButtonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hidePoiFilterOnMap(mapActivity, controller, action);
}
});
controller.setTitle(filter.getName());
PoiFiltersHelper helper = mapActivity.getMyApplication().getPoiFilters();
helper.clearSelectedPoiFilters();
helper.addSelectedPoiFilter(filter);
mapActivity.showTopToolbar(controller);
mapActivity.refreshMap();
}
private static void hidePoiFilterOnMap(@NonNull MapActivity mapActivity,
@NonNull TopToolbarController controller,
@Nullable Runnable action) {
mapActivity.hideTopToolbar(controller);
mapActivity.getMyApplication().getPoiFilters().clearSelectedPoiFilters();
mapActivity.refreshMap();
if (action != null) {
action.run();
}
}
private static class PoiFilterBarController extends TopToolbarController {
PoiFilterBarController() {
super(TopToolbarControllerType.POI_FILTER);
}
}
} }

View file

@ -126,6 +126,10 @@ public class MapInfoLayer extends OsmandMapLayer {
return topToolbarView.getTopController() != null; return topToolbarView.getTopController() != null;
} }
public TopToolbarController getTopToolbarController() {
return topToolbarView == null ? null : topToolbarView.getTopController();
}
public TopToolbarController getTopToolbarController(TopToolbarControllerType type) { public TopToolbarController getTopToolbarController(TopToolbarControllerType type) {
return topToolbarView == null ? null : topToolbarView.getController(type); return topToolbarView == null ? null : topToolbarView.getController(type);
} }

View file

@ -1,5 +1,6 @@
package net.osmand.plus.views.mapwidgets; package net.osmand.plus.views.mapwidgets;
import android.content.Context;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt; import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes; import android.support.annotation.ColorRes;
@ -55,7 +56,8 @@ public class MapInfoWidgetsFactory {
CONTEXT_MENU, CONTEXT_MENU,
TRACK_DETAILS, TRACK_DETAILS,
DISCOUNT, DISCOUNT,
MEASUREMENT_TOOL MEASUREMENT_TOOL,
POI_FILTER
} }
public TextInfoWidget createAltitudeControl(final MapActivity map) { public TextInfoWidget createAltitudeControl(final MapActivity map) {
@ -216,6 +218,9 @@ public class MapInfoWidgetsFactory {
} }
public static class TopToolbarController { public static class TopToolbarController {
public static final int NO_COLOR = -1;
private TopToolbarControllerType type; private TopToolbarControllerType type;
@ColorRes @ColorRes
@ -269,6 +274,7 @@ public class MapInfoWidgetsFactory {
boolean refreshBtnVisible = false; boolean refreshBtnVisible = false;
boolean saveViewVisible = false; boolean saveViewVisible = false;
boolean textBtnVisible = false;
protected boolean topBarSwitchVisible = false; protected boolean topBarSwitchVisible = false;
protected boolean topBarSwitchChecked = false; protected boolean topBarSwitchChecked = false;
@ -288,6 +294,10 @@ public class MapInfoWidgetsFactory {
int descrTextClrLight = -1; int descrTextClrLight = -1;
@ColorInt @ColorInt
int descrTextClrDark = -1; int descrTextClrDark = -1;
@ColorInt
int textBtnTitleClrLight = -1;
@ColorInt
int textBtnTitleClrDark = -1;
boolean singleLineTitle = true; boolean singleLineTitle = true;
@ -295,6 +305,7 @@ public class MapInfoWidgetsFactory {
String title = ""; String title = "";
String description = null; String description = null;
String textBtnTitle = null;
int saveViewTextId = -1; int saveViewTextId = -1;
@ -303,6 +314,7 @@ public class MapInfoWidgetsFactory {
OnClickListener onCloseButtonClickListener; OnClickListener onCloseButtonClickListener;
OnClickListener onRefreshButtonClickListener; OnClickListener onRefreshButtonClickListener;
OnClickListener onSaveViewClickListener; OnClickListener onSaveViewClickListener;
OnClickListener onTextBtnClickListener;
OnCheckedChangeListener onSwitchCheckedChangeListener; OnCheckedChangeListener onSwitchCheckedChangeListener;
Runnable onCloseToolbarListener; Runnable onCloseToolbarListener;
@ -317,6 +329,11 @@ public class MapInfoWidgetsFactory {
return type; return type;
} }
@ColorInt
public int getStatusBarColor(Context context, boolean night) {
return ContextCompat.getColor(context, night ? R.color.status_bar_route_dark : R.color.status_bar_route_light);
}
public void setTitle(String title) { public void setTitle(String title) {
this.title = title; this.title = title;
} }
@ -402,6 +419,14 @@ public class MapInfoWidgetsFactory {
this.saveViewTextId = id; this.saveViewTextId = id;
} }
public void setTextBtnVisible(boolean visible) {
this.textBtnVisible = visible;
}
public void setTextBtnTitle(String title) {
this.textBtnTitle = title;
}
public void setTopBarSwitchVisible(boolean visible) { public void setTopBarSwitchVisible(boolean visible) {
this.topBarSwitchVisible = visible; this.topBarSwitchVisible = visible;
} }
@ -430,6 +455,11 @@ public class MapInfoWidgetsFactory {
this.descrTextClrDark = descrTextClrDark; this.descrTextClrDark = descrTextClrDark;
} }
public void setTextBtnTitleClrs(int textBtnTitleClrLight, int textBtnTitleClrDark) {
this.textBtnTitleClrLight = textBtnTitleClrLight;
this.textBtnTitleClrDark = textBtnTitleClrDark;
}
public void setOnBackButtonClickListener(OnClickListener onBackButtonClickListener) { public void setOnBackButtonClickListener(OnClickListener onBackButtonClickListener) {
this.onBackButtonClickListener = onBackButtonClickListener; this.onBackButtonClickListener = onBackButtonClickListener;
} }
@ -446,6 +476,10 @@ public class MapInfoWidgetsFactory {
this.onSaveViewClickListener = onSaveViewClickListener; this.onSaveViewClickListener = onSaveViewClickListener;
} }
public void setOnTextBtnClickListener(OnClickListener onTextBtnClickListener) {
this.onTextBtnClickListener = onTextBtnClickListener;
}
public void setOnSwitchCheckedChangeListener(OnCheckedChangeListener onSwitchCheckedChangeListener) { public void setOnSwitchCheckedChangeListener(OnCheckedChangeListener onSwitchCheckedChangeListener) {
this.onSwitchCheckedChangeListener = onSwitchCheckedChangeListener; this.onSwitchCheckedChangeListener = onSwitchCheckedChangeListener;
} }
@ -509,6 +543,7 @@ public class MapInfoWidgetsFactory {
private ImageButton refreshButton; private ImageButton refreshButton;
private ImageButton closeButton; private ImageButton closeButton;
private TextView saveView; private TextView saveView;
private TextView textBtn;
private SwitchCompat topBarSwitch; private SwitchCompat topBarSwitch;
private View shadowView; private View shadowView;
private boolean nightMode; private boolean nightMode;
@ -525,6 +560,7 @@ public class MapInfoWidgetsFactory {
closeButton = (ImageButton) map.findViewById(R.id.widget_top_bar_close_button); closeButton = (ImageButton) map.findViewById(R.id.widget_top_bar_close_button);
titleView = (TextView) map.findViewById(R.id.widget_top_bar_title); titleView = (TextView) map.findViewById(R.id.widget_top_bar_title);
saveView = (TextView) map.findViewById(R.id.widget_top_bar_save); saveView = (TextView) map.findViewById(R.id.widget_top_bar_save);
textBtn = (TextView) map.findViewById(R.id.widget_top_bar_text_btn);
descrView = (TextView) map.findViewById(R.id.widget_top_bar_description); descrView = (TextView) map.findViewById(R.id.widget_top_bar_description);
topBarSwitch = (SwitchCompat) map.findViewById(R.id.widget_top_bar_switch); topBarSwitch = (SwitchCompat) map.findViewById(R.id.widget_top_bar_switch);
shadowView = map.findViewById(R.id.widget_top_bar_shadow); shadowView = map.findViewById(R.id.widget_top_bar_shadow);
@ -643,6 +679,7 @@ public class MapInfoWidgetsFactory {
closeButton.setOnClickListener(controller.onCloseButtonClickListener); closeButton.setOnClickListener(controller.onCloseButtonClickListener);
refreshButton.setOnClickListener(controller.onRefreshButtonClickListener); refreshButton.setOnClickListener(controller.onRefreshButtonClickListener);
saveView.setOnClickListener(controller.onSaveViewClickListener); saveView.setOnClickListener(controller.onSaveViewClickListener);
textBtn.setOnClickListener(controller.onTextBtnClickListener);
topBarSwitch.setOnCheckedChangeListener(controller.onSwitchCheckedChangeListener); topBarSwitch.setOnCheckedChangeListener(controller.onSwitchCheckedChangeListener);
} }
@ -680,6 +717,7 @@ public class MapInfoWidgetsFactory {
int titleTextClrId = nightMode ? controller.titleTextClrDarkId : controller.titleTextClrLightId; int titleTextClrId = nightMode ? controller.titleTextClrDarkId : controller.titleTextClrLightId;
int descrTextClr = nightMode ? controller.descrTextClrDark : controller.descrTextClrLight; int descrTextClr = nightMode ? controller.descrTextClrDark : controller.descrTextClrLight;
int descrTextClrId = nightMode ? controller.descrTextClrDarkId : controller.descrTextClrLightId; int descrTextClrId = nightMode ? controller.descrTextClrDarkId : controller.descrTextClrLightId;
int textBtnTitleClr = nightMode ? controller.textBtnTitleClrDark : controller.textBtnTitleClrLight;
if (bg != null) { if (bg != null) {
topBarLayout.setBackgroundDrawable(bg); topBarLayout.setBackgroundDrawable(bg);
@ -710,6 +748,9 @@ public class MapInfoWidgetsFactory {
titleView.setTextColor(titleColor); titleView.setTextColor(titleColor);
descrView.setTextColor(descrColor); descrView.setTextColor(descrColor);
saveView.setTextColor(titleColor); saveView.setTextColor(titleColor);
if (textBtnTitleClr != -1) {
textBtn.setTextColor(textBtnTitleClr);
}
titleView.setSingleLine(controller.singleLineTitle); titleView.setSingleLine(controller.singleLineTitle);
@ -738,6 +779,15 @@ public class MapInfoWidgetsFactory {
} else if (saveView.getVisibility() == View.VISIBLE) { } else if (saveView.getVisibility() == View.VISIBLE) {
saveView.setVisibility(View.GONE); saveView.setVisibility(View.GONE);
} }
if (controller.textBtnVisible) {
textBtn.setText(controller.textBtnTitle);
textBtn.setContentDescription(controller.textBtnTitle);
if (textBtn.getVisibility() == View.GONE) {
textBtn.setVisibility(View.VISIBLE);
}
} else if (textBtn.getVisibility() == View.VISIBLE) {
textBtn.setVisibility(View.GONE);
}
} }
public void updateColors() { public void updateColors() {

View file

@ -232,13 +232,12 @@ public class TravelLocalDataHelper {
private SQLiteConnection openConnection(boolean readonly) { private SQLiteConnection openConnection(boolean readonly) {
SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly); SQLiteConnection conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, readonly);
int version = conn.getVersion(); if (conn.getVersion() < DB_VERSION) {
if (version == 0 || DB_VERSION != version) {
if (readonly) { if (readonly) {
conn.close(); conn.close();
conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false); conn = context.getSQLiteAPI().getOrCreateDatabase(DB_NAME, false);
} }
version = conn.getVersion(); int version = conn.getVersion();
conn.setVersion(DB_VERSION); conn.setVersion(DB_VERSION);
if (version == 0) { if (version == 0) {
onCreate(conn); onCreate(conn);