1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
| package lu.visionitgroup.vsmobile;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import lu.visionitgroup.vsmobile.gcm.GcmServerUtilities;
import lu.visionitgroup.vsmobile.model.Dependency;
import lu.visionitgroup.vsmobile.model.NavigationInfos;
import lu.visionitgroup.vsmobile.model.Page;
import lu.visionitgroup.vsmobile.model.Step;
import lu.visionitgroup.vsmobile.model.ToolBarOptions;
import lu.visionitgroup.vsmobile.model.VsMobileApp;
import lu.visionitgroup.vsmobile.model.enums.GotoType;
import lu.visionitgroup.vsmobile.model.enums.ToolBarOption;
import lu.visionitgroup.vsmobile.model.jsobjets.Appointment;
import lu.visionitgroup.vsmobile.model.jsobjets.Contact;
import lu.visionitgroup.vsmobile.model.jsobjets.Coordinates;
import lu.visionitgroup.vsmobile.model.jsobjets.Notification;
import lu.visionitgroup.vsmobile.model.jsobjets.SharingInfos;
import lu.visionitgroup.vsmobile.services.Settings;
import lu.visionitgroup.vsmobile.tasks.Advertisement;
import lu.visionitgroup.vsmobile.tasks.VsMobileAppFetcher;
import lu.visionitgroup.vsmobile.util.ControlActivityInstance;
import lu.visionitgroup.vsmobile.util.Utilz;
import static android.provider.ContactsContract.CommonDataKinds;
import static android.provider.ContactsContract.Data;
import static android.provider.ContactsContract.RawContacts;
public class ZeActivity extends ActionBarActivity {
private static final Logger log = LoggerFactory.getLogger(ZeActivity.class);
// FIXME Directories management
private static final String BASE_URL = new File(VsMobile.getCachesDir(), VsMobileAppFetcher.CURRENT_CACHE_FOLDER_NAME).toURI().toString(); //VsMobileAppManager.getInstance().getCurrentCacheFolder().toURI().toString(); //"file:///data/data/lu.visionitgroup.vsmobile/app_" + VsMobile.CACHES_FOLDER_NAME + "/current/";
private static final String EXTRA_KEY_QUERY_PARAMS = "paramz";
private static final String EXTRA_KEY_GOTO_TYPE = "gotoType";
private static final String EXTRA_KEY_PAGE_ID = "currentPageId";
private static final SimpleDateFormat SDF = new SimpleDateFormat("dd/MM/yyyy à HH:mm");
GoogleCloudMessaging gcm;
private WebView zeWebView;
private File CURRENT_CACHE_APP_FILE;
private File APP_DIR_NAME;
private File App_DIR_json;
private String currentPageId;
private ToolBarOptions currentToolBarOptions;
private Advertisement adTask = null;
private Boolean appIsInCahe=false;
private RequestQueue mRequestQueue;
private ProgressDialog pDialog;
private Menu mOptionsMenu;
private static void dumpIntent(Intent intent) {
Bundle bundle = intent.getExtras();
StringBuilder sb = new StringBuilder();
if (bundle != null) {
Set<String> keys = bundle.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
sb.append("[" + key + "=" + bundle.get(key) + "]");
}
}
log.info("Intent: {}. Extras: {}", intent, sb.toString());
}
@Override
protected void onCreate(Bundle savedInstanceState){
log.info("onCreate({})", savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (isTablet(this)) {
setContentView(R.layout.sw600dp_main_activity);
} else {
setContentView(R.layout.activity_main);
}
super.onCreate(savedInstanceState);
ControlActivityInstance.getInstance().setZeActivity(this);
initActionBar();
checkStartApplicationCache();
initToolbar();
initNavigationButton();
initWebView();
appIsInCahe=APP_DIR_NAME.exists();
//this.checkIfAdvertisement();
goToIntent();
}
public boolean isTablet(Context context) {
boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
//TODO: Remove this and uncomment next, just for test purpose
Toast.makeText(this,Double.toString(Configuration.SCREENLAYOUT_SIZE_MASK),Toast.LENGTH_LONG).show();
//return (true);
return (xlarge || large);
}
private void initNavigationButton() {
View.OnClickListener onClickListener = new View.OnClickListener() {
public void onClick(View v) {
String direction;
switch (v.getId()) {
case R.id.btn_navigate_left: direction = "Previous"; break;
case R.id.btn_navigate_right: direction = "Next"; break;
default: return;
}
log.debug("Navigation to {} requested", direction);
log.debug("Enabled? {}, {}, {}",
findViewById(R.id.relative).isEnabled(),
findViewById(R.id.btn_navigate_left).isEnabled(),
findViewById(R.id.btn_navigate_right).isEnabled());
ZeActivity.this.zeWebView.loadUrl("javascript:view" + direction + "Details();androidBridge.setNavigationInfos(getPageNavigationInfo());");
}
};
ImageButton btnLeft = (ImageButton) findViewById(R.id.btn_navigate_left), btnRight = (ImageButton) findViewById(R.id.btn_navigate_right);
btnLeft.setOnClickListener(onClickListener);
btnRight.setOnClickListener(onClickListener);
}
private void initWebView() {
this.zeWebView = (WebView) findViewById(R.id.ze_web_view);
WebSettings webViewSettings = this.zeWebView.getSettings();
webViewSettings.setJavaScriptEnabled(true);
webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
webViewSettings.setAllowUniversalAccessFromFileURLs(true);
}
this.zeWebView.addJavascriptInterface(this, "androidBridge");
this.setWebViewClients();
}
private void initToolbar() {
Toolbar toolbar =(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.inflateMenu(R.menu.home);
}
private void checkStartApplicationCache() {
CURRENT_CACHE_APP_FILE= new File(VsMobile.getCachesDir(),"current");
APP_DIR_NAME=new File(CURRENT_CACHE_APP_FILE,"App");
App_DIR_json=new File(APP_DIR_NAME,"vsm_app.json");
VsMobile vsMobileApp= (VsMobile)getApplication();
mRequestQueue=vsMobileApp.getVolleyRequestQueue();
}
private void initActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (this.getActionBar() != null) {
this.getActionBar().hide();
}
}
}
private VsMobileAppFetcher initDownloader() {
final ProgressDialog pdg = new ProgressDialog(this);
pdg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdg.setTitle(R.string.app_downloading);
pdg.setCancelable(false);
VsMobileAppFetcher downloader = new VsMobileAppFetcher() {
@Override
protected void onPreExecute() {
log.debug("VsMobileAppDownloader.onPreExecute()");
if (!pdg.isShowing()) {
pdg.show();
}
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
log.trace("VsMobileAppDownloader.onProgressUpdate({}, {})", values[0], values[1]);
pdg.setMax(values[1]);
pdg.setProgress(values[0]);
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(VsMobileApp vsMobileApp) {
if (vsMobileApp != null) {
log.info("VsMobileAppDownloader.onPostExecute(v#{} of vsApp#{})", vsMobileApp.getVersionId(), vsMobileApp.getId());
VsMobile.CURRENT_APP = vsMobileApp;
}
else {
log.warn("Could't load VsApp");
//TODO use String Drawable
Toast.makeText(ZeActivity.this, "L'application n'a pas pu être récupérée,veuillez vérifier votre connexion", Toast.LENGTH_LONG).show();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
goTo(null, null, null);
}
});
pdg.dismiss();
super.onPostExecute(vsMobileApp);
}
};
return downloader;
}
private void goTo(GotoType gotoType, String gotoParamz, String fromPageId) {
log.debug("goTo({}, {}). Old currentPageId = {}", gotoType, gotoParamz, this.currentPageId);
//TODO don't forget login and remove hard coded variable
VsMobileApp currentApp;
if(appIsInCahe){
VsMobile.CURRENT_APP=Utilz.parseVsMobileAppInFile(App_DIR_json);
currentApp=VsMobile.getCurrentApp();
}else {
currentApp=VsMobile.getCurrentApp();
}
if (currentApp == null) {
//TODO changer the hard coded message to R.value
Toast.makeText(this, "L'application n'a pas pu être chargée", Toast.LENGTH_LONG).show();
return;
}
Page zePage;
Step zeStep = null;
String urlParamz = null;
if (gotoType == null) {
gotoType = GotoType.MENU;
}
switch(gotoType) {
case PAGE: // Go to another Page
zePage = currentApp.getPage(gotoParamz);
break;
case STEP: // Go to a step in the page
String[] paramzArray = gotoParamz.split("\\?");
zePage = currentApp.getPage(fromPageId);
if (zePage != null) {
zeStep = zePage.getStepByName(paramzArray[0]);
urlParamz = "#" + gotoParamz.substring(paramzArray[0].length()+1);
}
else {
log.warn("fromPage is null");
}
break;
case MENU: // Go to the default browser of device
zePage = currentApp.getPages().get(0);
break;
default:
log.error("Cannot go to type [{}]", gotoType);
return;
}
if (zePage != null) {
List<Dependency> pageDepz = zePage.getDependencies();
List<Dependency> allDeps = new ArrayList<Dependency>(currentApp.getDependencies().size() + pageDepz.size());
allDeps.addAll(currentApp.getDependencies());
allDeps.addAll(pageDepz);
if (zeStep == null) {
for(Step step: zePage.getSteps()){
if (step.isFirstStep()){
zeStep = step;
}
}
}
this.currentToolBarOptions = zeStep.getToolBarOptions();
if (this.currentToolBarOptions != null) {
findViewById(R.id.relative).setVisibility(this.currentToolBarOptions.isAllowPageNavigation() ? View.VISIBLE : View.GONE);
}
String content = this.buildHtmlWithDependenciesInHead(zeStep.getHtmlContent(), allDeps, zePage.getId());
String url = BASE_URL + File.separator + zePage.getId() + File.separator;
if (StringUtils.isNotBlank(urlParamz)) {
url += urlParamz;
}
if (log.isTraceEnabled()) {
log.trace("Loading content\nBaseUrl: {}\nContenu:\n{}", url, content, "", null, "");
}
else {
log.debug("Loading content. BaseUrl: {}", url);
}
this.zeWebView.loadDataWithBaseURL(url, content, "text/html", "utf-8", "");
this.currentPageId = zePage.getId();
log.info("Page n°{} loaded", currentPageId);
}
else {
log.error("Couldn't go to ({}, {}). Old currentPageId = {}", gotoType, gotoParamz, this.currentPageId);
}
}
private void backgroundFetchAppAndGotoHomeWhenDone(final Boolean... forceDownload) {
String versionUrl="http://" + VsMobile.SERVER_HOST_AND_PORT +"/api/VersionChecker";
if (VsMobile.getInstance().networkAllowed()) {
makeStringRequest(versionUrl, new VolleyCallback() {
@Override
public void onSuccess(Boolean appIsLastVersion) {
if (appIsLastVersion) {
try {
Thread.sleep(3000);
} catch (Exception e) {
}
VsMobileAppFetcher vsMobileAppFetcher = ZeActivity.this.initDownloader();
vsMobileAppFetcher.getCurrentCacheFolder();
vsMobileAppFetcher.execute(forceDownload);
} else {
AlertDialog alertDialog = new AlertDialog.Builder(ZeActivity.this).create();
alertDialog.setTitle("Information:");
//TODO USE R.Value (String)
alertDialog.setMessage("Votre version d'application n'est pas à jour !! ");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ZeActivity.this, "Veuillez mettre à jour votre application !", Toast.LENGTH_LONG).show();
ZeActivity.this.finish();
}
});
alertDialog.setIcon(R.drawable.app_logo);
alertDialog.show();
}
}
});
}
else {
Toast.makeText(this, R.string.no_update_because_no_connection, Toast.LENGTH_LONG).show();
goTo(null,null,null);
}
}
private void goToIntent() {
Intent intent = this.getIntent();
if (VsMobile.MODE_DEBUG) {
dumpIntent(intent);
}
log.debug("goToIntent({})", intent.getAction());
if (("android.intent.action.MAIN".equals(intent.getAction()) || VsMobile.getCurrentApp() == null ) && !appIsInCahe) {// App start
this.backgroundFetchAppAndGotoHomeWhenDone();
this.regiterToServer();
}
else if ("REFRESH".equals(intent.getAction())) {
this.backgroundFetchAppAndGotoHomeWhenDone(true);
}else if ("SIGNING".equals(intent.getAction())){
this.backgroundFetchAppAndGotoHomeWhenDone(true);
}else if ("LOGOUT".equals(intent.getAction())){
this.backgroundFetchAppAndGotoHomeWhenDone(true);
}
else {
goTo(
(GotoType) intent.getSerializableExtra(EXTRA_KEY_GOTO_TYPE),
intent.getStringExtra(EXTRA_KEY_QUERY_PARAMS),
intent.getStringExtra(EXTRA_KEY_PAGE_ID)
);
}
}
// Not use now it's must be complete
private void checkIfAdvertisement(){
log.info("CheckIfAdvertisment(): check if the application has a Advertisement");
Boolean isAppCacheExsiste=false;
adTask = new Advertisement();
File[] files=VsMobile.getCachesDir().listFiles();
for (File file : files){
if (file.getName().equalsIgnoreCase("current")){
File[] filesApp=file.listFiles();
for (File fileap:filesApp ){
if(fileap.getName().equalsIgnoreCase("App")){
isAppCacheExsiste=true;
break;
}
}
}
}
if (isAppCacheExsiste){
}
}
@Override
public void onBackPressed() {
if ("android.intent.action.MAIN".equals(this.getIntent().getAction()) || "REFRESH".equals(this.getIntent().getAction())|| "BACK_ACTION".equals(this.getIntent().getAction()) ) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Fermeture de "+VsMobile.getCurrentApp().getName())
.setMessage("Êtes-vous sûr de vouloir quitter l'application "+VsMobile.getCurrentApp().getName())
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ZeActivity.this.finish();
}
})
.setNegativeButton("No", null)
.show();
//zeWebView = (WebView) findViewById(R.id.ze_web_view);
}
else {
super.onBackPressed();
}
}
@JavascriptInterface
public void handleCheckFunctionExistsResponse(String what, final boolean response) {
log.info("CheckRetour: {} --> {}", what, response);
ToolBarOption tbo = ToolBarOption.valueOf(what);
if (ToolBarOption.PAGE_NAVIGATION.equals(tbo)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
findViewById(R.id.relative).setEnabled(response);
findViewById(R.id.btn_navigate_left).setEnabled(response);
findViewById(R.id.btn_navigate_right).setEnabled(response);
if (response) {
ZeActivity.this.zeWebView.loadUrl("javascript:androidBridge.setNavigationInfos(getPageNavigationInfo());");
}
}
});
}
else {
if (this.mOptionsMenu != null) {
this.mOptionsMenu.getItem(tbo.ordinal()).setEnabled(response);
}
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
this.mOptionsMenu = menu;
log.debug("onPrepareOptionsMenu()");
menu.clear();
if (currentToolBarOptions != null && VsMobile.getCurrentApp() != null) {
List<ToolBarOption> tboList = currentToolBarOptions.getTBOList();
log.debug("Preparing menu with options: {}", tboList);
for (int i = 0; i < tboList.size(); i++) {
MenuItem item;
ToolBarOption tbo = tboList.get(i);
switch (tbo) {
case LAST_UPDATE_DATE: // FIXME: Do not instanciate a downloader only to get Last Update
item = menu.add(0, tbo.ordinal(), 0, "Mise à jour le " + SDF.format(new VsMobileAppFetcher().getLastUpdate()));
break;
case PAGE_NAVIGATION: break;
default:
if (tbo.getLabelId() != 0) {
item = menu.add(0, tbo.ordinal(), 0, tbo.getLabelId()).setIcon(tbo.getIcoId());
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
if( prefs.getBoolean(Settings.MODE_CACHE.getPrefKey(), false) &&tboList.get(i).name().equalsIgnoreCase("DATA_REFRESH") ){
item.setVisible(false);
}
}
else {
item = menu.add(0, tbo.ordinal(), 0, tbo.name()).setIcon(tbo.getIcoId());
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
}
String func = null;
switch (tbo) {
case SORTING: func = "sort"; break;
case SEARCHING: func = "showSearch"; break;
case FILTERING: func = "showFilterForm"; break;
case SHARING: func = "getShareData"; break;
case GEOLOC: func = "getGeolocalisationData"; break;
case ADD_CONTACT: func = "getAddContactData"; break;
case ADD_CALENDAR: func = "getAddCalendarData"; break;
}
if (func != null) {
this.zeWebView.loadUrl("javascript:androidBridge.handleCheckFunctionExistsResponse('" + tbo.name() + "', typeof(" + func + ") == \"function\");");
}
}
}
else {
getMenuInflater().inflate(R.menu.home, menu);
}
return super.onCreateOptionsMenu(menu);
}
private void insertAppointment(Appointment appt) {
// + de rétro comp? --> https://coderwall.com/p/fnrdcq/add-calendar-event-in-android-before-ics
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Date dS,dE;
try {
dS = DateUtils.parseDate(appt.getStartDate(), new String[]{"yyyy-MM-dd'T'HH:mm:ssZZ"});
dE = DateUtils.parseDate(appt.getEndDate(),new String[]{"yyyy-MM-dd'T'HH:mm:ssZZ"});
}
catch (ParseException e) {
log.error("{}", e);
return;
}
log.debug("Adding appointment [{}] on [{}]", appt.getName(), dS);
final ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, dS.getTime());
values.put(CalendarContract.Events.DTEND, dE.getTime());
values.put(CalendarContract.Events.TITLE, appt.getTitle());
values.put(CalendarContract.Events.DESCRIPTION, appt.getTitle());
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1); // Default calendar
Uri apptUri = getContentResolver().insert(CalendarContract.Events.CONTENT_URI, values);
log.debug("Appointment inserted: {}", apptUri);
Toast.makeText(getBaseContext(), R.string.appt_added, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getBaseContext(), R.string.android_4_required, Toast.LENGTH_SHORT).show();
}
}
// FIXME Replace manual use of ObjectMapper
private <T> T parseJSonOrNull(String jSonStr, Class<T> clazz) {
try {
return new ObjectMapper().readValue(jSonStr, clazz);
}
catch (IOException e) {
log.error("Couldn't parse [{}] into [{}]", jSonStr, clazz, e);
}
return null;
}
@JavascriptInterface
public void handleToolbarClickResponse(String strTbo, String response) {
log.debug("Response received: {}, {}", strTbo, response);
ToolBarOption tbo = ToolBarOption.valueOf(strTbo);
//Toast.makeText(getApplicationContext(), "Now I should do [" + strTbo + "] with this [" + response + "]", Toast.LENGTH_SHORT).show();
switch(tbo) {
case SHARING:
SharingInfos si = this.parseJSonOrNull(response, SharingInfos.class);
if (si != null) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, si.getMessage());
sharingIntent.putExtra(Intent.EXTRA_TEXT, si.getUrl());
startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_via)));
}
break;
case GEOLOC:
Coordinates c = this.parseJSonOrNull(response, Coordinates.class);
if (c != null) {
log.debug("Starting Google Maps");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:" + c.getLatitude() + ',' + c.getLongitude()+"?q="+c.getLatitude()+","+c.getLongitude()+"("+c.getName()+")"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
log.trace("Google Maps started");
}
else {
Toast.makeText(getBaseContext(), R.string.google_maps_required, Toast.LENGTH_SHORT).show();
}
}
break;
case ADD_CONTACT:
insertContact(this.parseJSonOrNull(response, Contact.class));
/**
//Intent intent =new Intent(ZeActivity.this , ContactViewActivity.class);
//intent.putExtra("Contact",this.parseJSonOrNull(response, Contact.class));
//startActivity(intent);
//break;
Contact contact= this.parseJSonOrNull(response, Contact.class);
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.NAME,contact.getName());
intent.putExtra(ContactsContract.Intents.Insert.PHONE,contact.getPhoneNumber());
intent.putExtra(ContactsContract.Intents.Insert.COMPANY,contact.getOrganization());
intent.putExtra(ContactsContract.Intents.Insert.EMAIL,contact.getEmail());
intent.putExtra(ContactsContract.Intents.Insert.FAMILY_NAME,contact.get);
startActivity(intent);
**/
break;
case ADD_CALENDAR:
insertAppointment(this.parseJSonOrNull(response, Appointment.class));
break;
default:
log.warn("Cannot handle response {} of ToolbarOption#{}", response, strTbo);
break;
}
}
@JavascriptInterface
public void setNavigationInfos(String jSonString) {
log.error("setNavigationInfos({})", jSonString);
final NavigationInfos infos = this.parseJSonOrNull(jSonString, NavigationInfos.class);
if (infos != null) {
runOnUiThread(new Runnable() { // The thread executing this code can be the WebViewCoreThread which is not allowed to change stuff on ui.
@Override
public void run() {
((TextView) findViewById(R.id.txt_navigation_infos)).setText(infos.getText());
}
});
}
}
private void callToolbarJavascriptAndHandleResponse(ToolBarOption tbo, String jsFunction) {
zeWebView.loadUrl("javascript:androidBridge.handleToolbarClickResponse('" + tbo.name() + "', " + jsFunction + "());");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
log.info("Item selected: {}", item.getTitle());
int itemId = item.getItemId();
ToolBarOption tbo;
if (itemId == R.id.refresh_menu_item) {
tbo = ToolBarOption.DATA_REFRESH;
}
else if (itemId == R.id.setting_menu_item) {
tbo = ToolBarOption.APP_SETTINGS;
}
else {
tbo = ToolBarOption.values()[item.getItemId()];
}
if(itemId== R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
switch(tbo) {
case APP_SETTINGS:
log.debug("Application Settings");
Bundle bundle =new Bundle();
bundle.putInt("category", 1);
Intent done =new Intent(this,SettingsActivity.class);
done.putExtras(bundle);
startActivityForResult(done,1);
//startActivity(new Intent(this, SettingsActivity.class));
//finish();
return true;
case DATA_REFRESH:
finish();
log.debug("Application Refresh Required");
VsMobile.refreshAppInNewActivity(this);
log.debug("Application Refresh Started");
return true;
case SORTING:
zeWebView.loadUrl("javascript:sort();");
return true;
case SEARCHING:
zeWebView.loadUrl("javascript:showSearch();");
return true;
case FILTERING:
zeWebView.loadUrl("javascript:showFilterForm();");
return true;
case SHARING:
callToolbarJavascriptAndHandleResponse(tbo, "getShareData");
return true;
case GEOLOC:
callToolbarJavascriptAndHandleResponse(tbo, "getGeolocalisationData");
return true;
case ADD_CONTACT:
callToolbarJavascriptAndHandleResponse(tbo, "getAddContactData");
return true;
case ADD_CALENDAR:
callToolbarJavascriptAndHandleResponse(tbo, "getAddCalendarData");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setWebViewClients() {
zeWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String sUrl) {
log.trace("shouldOverrideUrlLoading({})", sUrl);
try {
GotoType gotoType = GotoType.findByUrl(sUrl);
URL url = new URL(sUrl);
log.trace("Request to go to [{}, {}]", gotoType, url.getQuery());
Intent intent;
switch (gotoType) {
case MENU: // Go to the default browser of device
case PAGE: // Go to another Page
intent = new Intent(ZeActivity.this, ZeActivity.class);
break;
case STEP: // Go to a step in the current page
intent = new Intent(ZeActivity.this, ZeActivity.class);
intent.putExtra(EXTRA_KEY_PAGE_ID, currentPageId);
break;
case EXTERNAL: // Go to a menu
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.getQuery())));
return true;
default:
log.error("Unknown url type: {}", sUrl);
return false;
}
intent.putExtra(EXTRA_KEY_GOTO_TYPE, gotoType);
intent.putExtra(EXTRA_KEY_QUERY_PARAMS, sUrl.substring(sUrl.indexOf('?') + 1));
startActivity(intent);
return true;
} catch (MalformedURLException e) {
log.error("Unknown url type: {}", sUrl, e);
}
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
log.info("onPageFinished({}, {})", view.getId(), url);
if (currentToolBarOptions != null && currentToolBarOptions.isAllowPageNavigation()) {
log.error("Page is loaded, calling setNavigationInfos");
zeWebView.loadUrl("javascript:androidBridge.handleCheckFunctionExistsResponse('" + ToolBarOption.PAGE_NAVIGATION.name() + "', typeof(getPageNavigationInfo) == \"function\" && typeof(viewPreviousDetails) == \"function\" && typeof(viewNextDetails) == \"function\");");
}
}
});
zeWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
log.debug("onConsoleMessage({}, {}, {})", message, lineNumber, sourceID);
super.onConsoleMessage(message, lineNumber, sourceID);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
//log.debug("onConsoleMessage({})", consoleMessage);
onConsoleMessage(consoleMessage.message(), consoleMessage.lineNumber(), consoleMessage.sourceId());
return true;
}
});
}
private void insertContact(Contact c) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
final int rawContactID = 0;
log.info("Adding {} {} in contacts", c.getFirstName(), c.getLastName());
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, c.getName())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.StructuredName.GIVEN_NAME, c.getFirstName())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.StructuredName.FAMILY_NAME, c.getLastName())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Phone.NUMBER, c.getPhoneNumber())
.withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Phone.NUMBER, c.getFaxNumber())
.withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_FAX_WORK)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Email.ADDRESS, c.getEmail())
.withValue(CommonDataKinds.Email.TYPE, CommonDataKinds.Email.TYPE_HOME)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Organization.COMPANY, c.getOrganization())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Organization.JOB_DESCRIPTION, c.getJobTitle())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Event.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Event.TYPE, CommonDataKinds.Event.TYPE_BIRTHDAY)
.withValue(CommonDataKinds.Event.START_DATE, c.getBirthday())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.StructuredPostal.TYPE, CommonDataKinds.StructuredPostal.TYPE_WORK)
.withValue(CommonDataKinds.StructuredPostal.STREET, c.getAddress())
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactID)
.withValue(Data.MIMETYPE, CommonDataKinds.Note.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.Note.NOTE, c.getNotes())
.build());
/**
try {
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
log.debug("Contact added");
Toast.makeText(getBaseContext(), R.string.contact_added, Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
log.error(null, e);
}
**/
final ContentResolver cr = getContentResolver();
try {
final ContentProviderResult[] res = cr.applyBatch(ContactsContract.AUTHORITY, ops);
final Uri uri = ContactsContract.RawContacts.getContactLookupUri(cr, res[0].uri);
final Intent intent = new Intent();
//intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
//intent.setData(uri);
//final Intent intent = new Intent();
// open un new intent using the Contact UI view
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
intent.putExtra(ContactsContract.Intents.Insert.NAME, c.getName());
intent.putExtra(ContactsContract.Intents.Insert.PHONE, c.getPhoneNumber());
intent.putExtra(ContactsContract.Intents.Insert.COMPANY,c.getOrganization());
intent.putExtra(ContactsContract.Intents.Insert.EMAIL, c.getEmail());
intent.putExtra(ContactsContract.Intents.Insert.POSTAL, c.getAddress());
intent.putExtra(ContactsContract.Intents.Insert.JOB_TITLE, c.getJobTitle());
//intent.setData(uri);
startActivity(intent);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
private String buildHtmlWithDependenciesInHead(String htmlContent, List<Dependency> dependencies, String pageId) {
StringBuilder sb = new StringBuilder();
sb.append("<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title></title>");
for (Dependency dependency: dependencies) {
String depType = dependency.getType();
if ("application/javascript".equals(depType)) {
sb.append("<script type=\"text/javascript\" src='" + BASE_URL + File.separator + pageId + File.separator + dependency.getFullPath() + "?cachId=" + Utilz.getCurrentDateTime() + "'></script>");
}
else if ("text/css".equals(depType)) {
sb.append("<link rel='stylesheet' href='" + BASE_URL + File.separator + pageId + File.separator + dependency.getFullPath() + "?cachId=" + Utilz.getCurrentDateTime() + "' />");
}
}
sb.append("</head><body>");
sb.append(htmlContent);
sb.append("</body></html>");
return sb.toString();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//matches the result code passed from ChildActivity
if(resultCode == 0)
{
//kill self
ZeActivity.this.finish();
}
}
public Long getLastUpdate() {
Long lastupdate = null;
if (CURRENT_CACHE_APP_FILE.exists()) {
lastupdate = CURRENT_CACHE_APP_FILE.lastModified();
}
return lastupdate;
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest(String url) {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// The following code is called when Volley failed to retrieve the query result
Toast.makeText(ZeActivity.this, "Error while getting JSON: " + volleyError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void makeStringRequest(String url, final VolleyCallback callBack) {
pDialog = new ProgressDialog(this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
//TODO Use R.VALUE
pDialog.setMessage("Vérification de la validité de la version...");
pDialog.show();
if (VsMobile.getInstance().networkAllowed()) {
StringRequest postRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// response
log.info("Response {}", response);
if (response.equalsIgnoreCase("true")) {
callBack.onSuccess(true);
pDialog.hide();
} else {
callBack.onSuccess(false);
pDialog.hide();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
log.info("ERROR", "error => " + error.toString());
// The following code is called when Volley failed to retrieve the query result
pDialog.hide();
Toast.makeText(ZeActivity.this, "Veuillez vérifier votre connexion !! ", Toast.LENGTH_SHORT).show();
}
}
) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Accept", "application/json");
params.put("API-Version", "2");
params.put("deviceId", UUID.randomUUID().toString());
params.put("deviceFormat", "Phone");
params.put("deviceType", "android");
params.put("osVersion", String.valueOf(Build.VERSION.SDK_INT));
params.put("AppId", VsMobile.APP_ID);
return params;
}
};
mRequestQueue.add(postRequest);
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
@Override
protected void onStop() {
mRequestQueue.cancelAll(this);
super.onStop();
}
public void regiterToServer(){
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String idRegFromGoogle = null;
String jNotification ="";
try {
if(gcm ==null){
gcm=GoogleCloudMessaging.getInstance(getApplicationContext());
}
idRegFromGoogle=gcm.register(VsMobile.PROJECT_NUMBER);
} catch (IOException e) {
log.info("gcm Instance Error ",e.getCause());
}
Notification not =new Notification();
not.setAction("Add");
not.setDeviceNotificationId(idRegFromGoogle);
ObjectMapper mapper = new ObjectMapper();
try {
jNotification=mapper.writeValueAsString(not);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
GcmServerUtilities.register(getApplicationContext(), jNotification);
return jNotification;
}
@Override
protected void onPostExecute(String msg) {
log.info("regId info {}",msg);
}
}.execute(null,null,null);
}
//Interface For CallBack use
public interface VolleyCallback {
void onSuccess(Boolean result);
}
} |
Partager