-
Notifications
You must be signed in to change notification settings - Fork 418
/
Copy pathAndroidImplementation.java
10676 lines (9368 loc) · 411 KB
/
AndroidImplementation.java
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
/*
* Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.impl.android;
import android.Manifest;
import android.annotation.TargetApi;
import com.codename1.location.AndroidLocationManager;
import android.app.*;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.AudioTimestamp;
import android.support.v4.content.ContextCompat;
import android.view.MotionEvent;
import com.codename1.codescan.ScanResult;
import com.codename1.media.Media;
import com.codename1.ui.geom.Dimension;
import android.webkit.CookieSyncManager;
import android.content.*;
import android.content.pm.*;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.codename1.ui.BrowserComponent;
import com.codename1.ui.Component;
import com.codename1.ui.Font;
import com.codename1.ui.Image;
import com.codename1.ui.PeerComponent;
import com.codename1.ui.events.ActionEvent;
import com.codename1.impl.CodenameOneImplementation;
import com.codename1.impl.VirtualKeyboardInterface;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.Vector;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.telephony.SmsManager;
import android.telephony.gsm.GsmCellLocation;
import android.text.Html;
import android.view.*;
import android.view.View.MeasureSpec;
import android.webkit.*;
import android.widget.*;
import com.codename1.background.BackgroundFetch;
import com.codename1.capture.VideoCaptureConstraints;
import com.codename1.codescan.CodeScanner;
import com.codename1.contacts.Contact;
import com.codename1.db.Database;
import com.codename1.impl.android.compat.app.NotificationCompatWrapper;
import com.codename1.impl.android.compat.app.NotificationCompatWrapper.ActionWrapper;
import com.codename1.impl.android.compat.app.RemoteInputWrapper;
import com.codename1.io.BufferedInputStream;
import com.codename1.io.BufferedOutputStream;
import com.codename1.io.*;
import com.codename1.l10n.L10NManager;
import com.codename1.location.LocationManager;
import com.codename1.media.AbstractMedia;
import com.codename1.media.AsyncMedia;
import com.codename1.media.AsyncMedia.MediaErrorType;
import com.codename1.media.AsyncMedia.MediaException;
import com.codename1.media.Audio;
import com.codename1.media.AudioService;
import com.codename1.media.BackgroundAudioService;
import com.codename1.media.MediaProxy;
import com.codename1.media.MediaRecorderBuilder;
import com.codename1.messaging.Message;
import com.codename1.notifications.LocalNotification;
import com.codename1.payment.Purchase;
import com.codename1.push.PushAction;
import com.codename1.push.PushActionCategory;
import com.codename1.push.PushActionsProvider;
import com.codename1.push.PushCallback;
import com.codename1.push.PushContent;
import com.codename1.ui.*;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.animations.Animation;
import com.codename1.ui.animations.CommonTransitions;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.GeneralPath;
import com.codename1.ui.geom.Rectangle;
import com.codename1.ui.geom.Shape;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.plaf.Style;
import com.codename1.ui.util.EventDispatcher;
import com.codename1.util.AsyncResource;
import com.codename1.util.Callback;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.codename1.util.StringUtil;
import com.codename1.util.SuccessCallback;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.CookieHandler;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.security.MessageDigest;
import java.text.ParseException;
import java.util.*;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.ParserConfigurationException;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.xml.sax.SAXException;
//import android.webkit.JavascriptInterface;
public class AndroidImplementation extends CodenameOneImplementation implements IntentResultListener {
public static final Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
if(com.codename1.io.Log.isCrashBound()) {
com.codename1.io.Log.p("Uncaught exception in thread " + t.getName());
com.codename1.io.Log.e(e);
com.codename1.io.Log.sendLog();
}
}
};
/**
* make sure these important keys have a negative value when passed to
* Codename One or they might be interpreted as characters.
*/
static final int DROID_IMPL_KEY_LEFT = -23446;
static final int DROID_IMPL_KEY_RIGHT = -23447;
static final int DROID_IMPL_KEY_UP = -23448;
static final int DROID_IMPL_KEY_DOWN = -23449;
static final int DROID_IMPL_KEY_FIRE = -23450;
static final int DROID_IMPL_KEY_MENU = -23451;
static final int DROID_IMPL_KEY_BACK = -23452;
static final int DROID_IMPL_KEY_BACKSPACE = -23453;
static final int DROID_IMPL_KEY_CLEAR = -23454;
static final int DROID_IMPL_KEY_SEARCH = -23455;
static final int DROID_IMPL_KEY_CALL = -23456;
static final int DROID_IMPL_KEY_VOLUME_UP = -23457;
static final int DROID_IMPL_KEY_VOLUME_DOWN = -23458;
static final int DROID_IMPL_KEY_MUTE = -23459;
static int[] leftSK = new int[]{DROID_IMPL_KEY_MENU};
/**
* @return the activity
*/
public static CodenameOneActivity getActivity() {
return activity;
}
/**
* @param aActivity the activity to set
*/
public static void setActivity(CodenameOneActivity aActivity) {
activity = aActivity;
if (activity != null) {
activityComponentName = activity.getComponentName();
}
}
CodenameOneSurface myView = null;
CodenameOneTextPaint defaultFont;
private final char[] tmpchar = new char[1];
private final Rect tmprect = new Rect();
protected int defaultFontHeight;
private Vibrator v = null;
private boolean vibrateInitialized = false;
private int displayWidth;
private int displayHeight;
static CodenameOneActivity activity;
static ComponentName activityComponentName;
private static Context context;
RelativeLayout relativeLayout;
final Vector nativePeers = new Vector();
int lastDirectionalKeyEventReceivedByWrapper;
private EventDispatcher callback;
private int timeout = -1;
private CodeScannerImpl scannerInstance;
private HashMap apIds;
private static View viewBelow;
private static View viewAbove;
private static int aboveSpacing;
private static int belowSpacing;
public static boolean asyncView = false;
public static boolean textureView = false;
private AudioService background;
private boolean asyncEditMode = false;
private boolean compatPaintMode;
private MediaRecorder recorder = null;
private boolean statusBarHidden;
private boolean superPeerMode = true;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
/**
* Keeps track of running contexts.
* @see #startContext(Context)
* @see #stopContext(Context)
*/
private static HashSet<Context> activeContexts = new HashSet<Context>();
/**
* A method to be called when a Context begins its execution. This adds the
* context to the context set. When the contenxt's execution completes, it should
* call {@link #stopContext} to clear up resources.
* @param ctx The context that is starting.
* @see #stopContext(Context)
*/
public static void startContext(Context ctx) {
while (deinitializingEdt) {
// It is possible that deinitialize was called just before the
// last context was destroyed so there is a pending deinitialize
// working its way through the system. Give it some time
// before forcing the deinitialize
System.out.println("Waiting for deinitializing to complete before starting a new initialization");
try {
Thread.sleep(30);
} catch (Exception ex){}
}
if (deinitializing && instance != null) {
instance.deinitialize();
}
synchronized(activeContexts) {
activeContexts.add(ctx);
if (instance == null) {
// If this is our first rodeo, just call Display.init() as that should
// be sufficient to set everything up.
Display.init(ctx);
} else {
// If we've initialized before, we should "re-initialize" the implementation
// Reinitializing will force views to be created even if the EDT was already
// running in background mode.
reinit(ctx);
}
}
}
/**
* Cleans up resources in the given context. This method should be called by
* any Activity or Service that called startContext() when it started.
* @param ctx The context to stop.
*
* @see #startContext(Context)
*/
public static void stopContext(Context ctx) {
synchronized(activeContexts) {
activeContexts.remove(ctx);
if (activeContexts.isEmpty()) {
// If we are the last context, we should deinitialize
syncDeinitialize();
} else {
if (instance != null && getActivity() != null) {
// if this is an activity, then we should clean up
// our UI resources anyways because the last context
// to be cleaned up might not have access to the UI thread.
instance.deinitialize();
}
}
}
}
@Override
public void setPlatformHint(String key, String value) {
if(key.equals("platformHint.compatPaintMode")) {
compatPaintMode = value.equalsIgnoreCase("true");
return;
}
if(key.equals("platformHint.legacyPaint")) {
AndroidAsyncView.legacyPaintLogic = value.equalsIgnoreCase("true");;
}
}
/**
* This method in used internally for ads
* @param above shown above the view
* @param below shown below the view
*/
public static void setViewAboveBelow(View above, View below, int spacingAbove, int spacingBelow) {
viewBelow = below;
viewAbove = above;
aboveSpacing = spacingAbove;
belowSpacing = spacingBelow;
}
static boolean hasViewAboveBelow(){
return viewBelow != null || viewAbove != null;
}
/**
* Copy the input stream into the output stream, closes both streams when finishing or in
* a case of an exception
*
* @param i source
* @param o destination
*/
private static void copy(InputStream i, OutputStream o) throws IOException {
copy(i, o, 8192);
}
/**
* Copy the input stream into the output stream, closes both streams when finishing or in
* a case of an exception
*
* @param i source
* @param o destination
* @param bufferSize the size of the buffer, which should be a power of 2 large enoguh
*/
private static void copy(InputStream i, OutputStream o, int bufferSize) throws IOException {
try {
byte[] buffer = new byte[bufferSize];
int size = i.read(buffer);
while(size > -1) {
o.write(buffer, 0, size);
size = i.read(buffer);
}
} finally {
sCleanup(o);
sCleanup(i);
}
}
private static void sCleanup(Object o) {
try {
if(o != null) {
if(o instanceof InputStream) {
((InputStream)o).close();
return;
}
if(o instanceof OutputStream) {
((OutputStream)o).close();
return;
}
}
} catch(Throwable t) {}
}
/**
* Copied here since the cleanup method in util would crash append notification that runs when the app isn't in the foreground
*/
private static byte[] readInputStream(InputStream i) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
copy(i, b);
return b.toByteArray();
}
public static void appendNotification(String type, String body, Context a) {
appendNotification(type, body, null, null, a);
}
public static void appendNotification(String type, String body, String image, String category, Context a) {
try {
String[] fileList = a.fileList();
byte[] data = null;
for (int iter = 0; iter < fileList.length; iter++) {
if (fileList[iter].equals("CN1$AndroidPendingNotifications")) {
InputStream is = a.openFileInput("CN1$AndroidPendingNotifications");
if(is != null) {
data = readInputStream(is);
sCleanup(a);
break;
}
}
}
DataOutputStream os = new DataOutputStream(a.openFileOutput("CN1$AndroidPendingNotifications", 0));
if(data != null) {
data[0]++;
os.write(data);
} else {
os.writeByte(1);
}
String bodyType = type;
if (image != null || category != null) {
type = "99";
}
if(type != null) {
os.writeBoolean(true);
os.writeUTF(type);
} else {
os.writeBoolean(false);
}
if ("99".equals(type)) {
String msg = "body="+java.net.URLEncoder.encode(body, "UTF-8")
+"&type="+java.net.URLEncoder.encode(bodyType, "UTF-8");
if (category != null) {
msg += "&category="+java.net.URLEncoder.encode(category, "UTF-8");
}
if (image != null) {
image += "&image="+java.net.URLEncoder.encode(image, "UTF-8");
}
os.writeUTF(msg);
} else {
os.writeUTF(body);
}
os.writeLong(System.currentTimeMillis());
} catch(IOException err) {
err.printStackTrace();
}
}
private static Map<String,String> splitQuery(String urlencodeQueryString) {
String[] parts = urlencodeQueryString.split("&");
Map<String,String> out = new HashMap<String,String>();
for (String part : parts) {
int pos = part.indexOf("=");
String k,v;
if (pos > 0) {
k = part.substring(0, pos);
v = part.substring(pos+1);
} else {
k = part;
v = "";
}
try { k = java.net.URLDecoder.decode(k, "UTF-8");} catch (Exception ex){}
try {v = java.net.URLDecoder.decode(v, "UTF-8");} catch (Exception ex){}
out.put(k, v);
}
return out;
}
public static void initPushContent(String message, String image, String messageType, String category, Context context) {
com.codename1.push.PushContent.reset();
int iMessageType = 1;
try {iMessageType = Integer.parseInt(messageType);}catch(Throwable t){}
String actionId = null;
String reply = null;
boolean cancel = true;
if (context instanceof Activity) {
Activity activity = (Activity)context;
Bundle extras = activity.getIntent().getExtras();
if (extras != null) {
actionId = extras.getString("pushActionId");
extras.remove("pushActionId");
if (actionId != null && RemoteInputWrapper.isSupported()) {
Bundle textExtras = RemoteInputWrapper.getResultsFromIntent(activity.getIntent());
if (textExtras != null) {
CharSequence cs = textExtras.getCharSequence(actionId + "$Result");
if (cs != null) {
reply = cs.toString();
}
}
}
}
}
if (cancel) {
PushNotificationService.cancelNotification(context);
}
com.codename1.push.PushContent.setType(iMessageType);
com.codename1.push.PushContent.setCategory(category);
if (actionId != null) {
com.codename1.push.PushContent.setActionId(actionId);
}
if (reply != null) {
com.codename1.push.PushContent.setTextResponse(reply);
}
switch (iMessageType) {
case 1:
case 5:
com.codename1.push.PushContent.setBody(message);break;
case 2: com.codename1.push.PushContent.setMetaData(message);break;
case 3: {
String[] parts = message.split(";");
com.codename1.push.PushContent.setMetaData(parts[1]);
com.codename1.push.PushContent.setBody(parts[0]);
break;
}
case 4: {
String[] parts = message.split(";");
com.codename1.push.PushContent.setTitle(parts[0]);
com.codename1.push.PushContent.setBody(parts[1]);
break;
}
case 101: {
com.codename1.push.PushContent.setBody(message.substring(message.indexOf(" ") + 1));
com.codename1.push.PushContent.setType(1);
break;
}
case 102: {
String[] parts = message.split(";");
com.codename1.push.PushContent.setTitle(parts[1]);
com.codename1.push.PushContent.setBody(parts[2]);
com.codename1.push.PushContent.setType(2);
break;
}
}
}
// Name of file where we install the push notification categories as an XML file
// if the main class implements PushActiosProvider
private static String FILE_NAME_NOTIFICATION_CATEGORIES = "CN1$AndroidNotificationCategories";
/**
* Action categories are defined on the Main class by implementing the PushActionsProvider, however
* the main class may not be available to the push receiver, so we need to save these categories
* to the file system when the app is installed, then the push receiver can load these actions
* when it sends a push while the app isn't running.
* @param provider A reference to the App's main class
* @throws IOException
*/
public static void installNotificationActionCategories(PushActionsProvider provider) throws IOException {
// Assume that CN1 is running... this will run when the app starts
// up
Context context = getContext();
boolean requiresUpdate = false;
File categoriesFile = new File(activity.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
if (!categoriesFile.exists()) {
requiresUpdate = true;
}
if (!requiresUpdate) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
if (packageInfo.lastUpdateTime > categoriesFile.lastModified()) {
requiresUpdate = true;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!requiresUpdate) {
return;
}
OutputStream os = getContext().openFileOutput(FILE_NAME_NOTIFICATION_CATEGORIES, 0);
PushActionCategory[] categories = provider.getPushActionCategories();
javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
throw new IOException("Faield to create document builder for creating notification categories XML document", ex);
}
// root elements
org.w3c.dom.Document doc = docBuilder.newDocument();
org.w3c.dom.Element root = (org.w3c.dom.Element)doc.createElement("categories");
doc.appendChild(root);
for (PushActionCategory category : categories) {
org.w3c.dom.Element categoryEl = (org.w3c.dom.Element)doc.createElement("category");
org.w3c.dom.Attr idAttr = doc.createAttribute("id");
idAttr.setValue(category.getId());
categoryEl.setAttributeNode(idAttr);
for (PushAction action : category.getActions()) {
org.w3c.dom.Element actionEl = (org.w3c.dom.Element)doc.createElement("action");
org.w3c.dom.Attr actionIdAttr = doc.createAttribute("id");
actionIdAttr.setValue(action.getId());
actionEl.setAttributeNode(actionIdAttr);
org.w3c.dom.Attr actionTitleAttr = doc.createAttribute("title");
if (action.getTitle() != null) {
actionTitleAttr.setValue(action.getTitle());
} else {
actionTitleAttr.setValue(action.getId());
}
actionEl.setAttributeNode(actionTitleAttr);
if (action.getIcon() != null) {
org.w3c.dom.Attr actionIconAttr = doc.createAttribute("icon");
String iconVal = action.getIcon();
try {
// We'll store the resource IDs for the icon
// rather than the icon name because that is what
// the push notifications require.
iconVal = ""+context.getResources().getIdentifier(iconVal, "drawable", context.getPackageName());
actionIconAttr.setValue(iconVal);
actionEl.setAttributeNode(actionIconAttr);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (action.getTextInputPlaceholder() != null) {
org.w3c.dom.Attr textInputPlaceholderAttr = doc.createAttribute("textInputPlaceholder");
textInputPlaceholderAttr.setValue(action.getTextInputPlaceholder());
actionEl.setAttributeNode(textInputPlaceholderAttr);
}
if (action.getTextInputButtonText() != null) {
org.w3c.dom.Attr textInputButtonTextAttr = doc.createAttribute("textInputButtonText");
textInputButtonTextAttr.setValue(action.getTextInputButtonText());
actionEl.setAttributeNode(textInputButtonTextAttr);
}
categoryEl.appendChild(actionEl);
}
root.appendChild(categoryEl);
}
try {
javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
transformer.transform(source, result);
} catch (Exception ex) {
throw new IOException("Failed to save notification categories as XML.", ex);
}
}
/**
* Retrieves the app's available push action categories from the XML file in which they
* should have been installed on the first load.
* @param context
* @return
* @throws IOException
*/
private static PushActionCategory[] getInstalledPushActionCategories(Context context) throws IOException {
// NOTE: This method may be called from the PushReceiver when the app isn't running so we can't access
// the main activity context, display properties, or any CN1 stuff. Just native android
File categoriesFile = new File(context.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
if (!categoriesFile.exists()) {
return new PushActionCategory[0];
}
javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder docBuilder;
try {
docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
throw new IOException("Faield to create document builder for creating notification categories XML document", ex);
}
org.w3c.dom.Document doc;
try {
doc = docBuilder.parse(context.openFileInput(FILE_NAME_NOTIFICATION_CATEGORIES));
} catch (SAXException ex) {
Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
throw new IOException("Failed to parse instaled push action categories", ex);
}
org.w3c.dom.Element root = doc.getDocumentElement();
java.util.List<PushActionCategory> out = new ArrayList<PushActionCategory>();
org.w3c.dom.NodeList l = root.getElementsByTagName("category");
int len = l.getLength();
for (int i=0; i<len; i++) {
org.w3c.dom.Element el = (org.w3c.dom.Element)l.item(i);
java.util.List<PushAction> actions = new ArrayList<PushAction>();
org.w3c.dom.NodeList al = el.getElementsByTagName("action");
int alen = al.getLength();
for (int j=0; j<alen; j++) {
org.w3c.dom.Element actionEl = (org.w3c.dom.Element)al.item(j);
String textInputPlaceholder = actionEl.hasAttribute("textInputPlaceholder") ? actionEl.getAttribute("textInputPlaceholder") : null;
String textInputButtonText = actionEl.hasAttribute("textInputButtonText") ? actionEl.getAttribute("textInputButtonText") : null;
PushAction action = new PushAction(actionEl.getAttribute("id"), actionEl.getAttribute("title"), actionEl.getAttribute("icon"), textInputPlaceholder, textInputButtonText);
actions.add(action);
}
PushActionCategory cat = new PushActionCategory((String)el.getAttribute("id"), actions.toArray(new PushAction[actions.size()]));
out.add(cat);
}
return out.toArray(new PushActionCategory[out.size()]);
}
public static PendingIntent createPendingIntent(Context ctx, int value, Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= 23) {
// PendingIntent.FLAG_IMMUTABLE
return PendingIntent.getActivity(ctx, value, intent, 67108864);
} else {
return PendingIntent.getActivity(ctx, value, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
}
public static PendingIntent getPendingIntent(Context ctx, int value, Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= 23) {
// PendingIntent.FLAG_IMMUTABLE
return PendingIntent.getService(ctx, value, intent, 67108864);
} else {
return PendingIntent.getService(ctx, value, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
}
public static PendingIntent getBroadcastPendingIntent(Context ctx, int value, Intent intent) {
if (android.os.Build.VERSION.SDK_INT >= 23) {
// PendingIntent.FLAG_IMMUTABLE
return PendingIntent.getBroadcast(ctx, value, intent, 67108864);
} else {
return PendingIntent.getBroadcast(ctx, value, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
}
/**
* Adds actions to a push notification. This is called by the Push broadcast receiver probably before
* Codename One is initialized
* @param provider Reference to the app's main class which implements PushActionsProvider
* @param categoryId The category ID of the push notification.
* @param builder The builder for the push notification.
* @param targetIntent The target intent... this should go to the app's main Activity.
* @param context The current context (inside the Broadcast receiver).
* @throws IOException
*/
public static void addActionsToNotification(PushActionsProvider provider, String categoryId, NotificationCompat.Builder builder, Intent targetIntent, Context context) throws IOException {
// NOTE: THis will likely run when the main activity isn't running so we won't have
// access to any display properties... just native Android APIs will be accessible.
PushActionCategory category = null;
PushActionCategory[] categories;
if (provider != null) {
categories = provider.getPushActionCategories();
} else {
categories = getInstalledPushActionCategories(context);
}
for (PushActionCategory candidateCategory : categories) {
if (categoryId.equals(candidateCategory.getId())) {
category = candidateCategory;
break;
}
}
if (category == null) {
return;
}
int requestCode = 1;
for (PushAction action : category.getActions()) {
Intent newIntent = (Intent)targetIntent.clone();
newIntent.putExtra("pushActionId", action.getId());
PendingIntent contentIntent = createPendingIntent(context, requestCode++, newIntent);
try {
int iconId = 0;
try { iconId = Integer.parseInt(action.getIcon());} catch (Exception ex){}
//android.app.Notification.Action.Builder actionBuilder = new android.app.Notification.Action.Builder(iconId, action.getTitle(), contentIntent);
System.out.println("Adding action "+action.getId()+", "+action.getTitle()+", icon="+iconId);
if (ActionWrapper.BuilderWrapper.isSupported()) {
// We need to take this abstracted "wrapper" approach because the Action.Builder class, and RemoteInput class
// aren't available until API 22.
// These classes use reflection to provide support for these classes safely.
ActionWrapper.BuilderWrapper actionBuilder = new ActionWrapper.BuilderWrapper(iconId, action.getTitle(), contentIntent);
if (action.getTextInputPlaceholder() != null && RemoteInputWrapper.isSupported()) {
RemoteInputWrapper.BuilderWrapper remoteInputBuilder = new RemoteInputWrapper.BuilderWrapper(action.getId()+"$Result");
remoteInputBuilder.setLabel(action.getTextInputPlaceholder());
RemoteInputWrapper remoteInput = remoteInputBuilder.build();
actionBuilder.addRemoteInput(remoteInput);
}
ActionWrapper actionWrapper = actionBuilder.build();
new NotificationCompatWrapper.BuilderWrapper(builder).addAction(actionWrapper);
} else {
builder.addAction(iconId, action.getTitle(), contentIntent);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void firePendingPushes(final PushCallback c, final Context a) {
try {
if(c != null) {
InputStream i = a.openFileInput("CN1$AndroidPendingNotifications");
if(i == null) {
return;
}
DataInputStream is = new DataInputStream(i);
int count = is.readByte();
for(int iter = 0 ; iter < count ; iter++) {
boolean hasType = is.readBoolean();
String actualType = null;
if(hasType) {
actualType = is.readUTF();
}
final String t;
final String b;
final String category;
final String image;
if ("99".equals(actualType)) {
// This was a rich push
Map<String,String> vals = splitQuery(is.readUTF());
t = vals.get("type");
b = vals.get("body");
category = vals.get("category");
image = vals.get("image");
} else {
t = actualType;
b = is.readUTF();
category = null;
image = null;
}
long s = is.readLong();
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
Display.getInstance().setProperty("pendingPush", "true");
Display.getInstance().setProperty("pushType", t);
initPushContent(b, image, t, category, a);
if(t != null && ("3".equals(t) || "6".equals(t))) {
String[] a = b.split(";");
c.push(a[0]);
c.push(a[1]);
} else if (t != null && ("101".equals(t))) {
c.push(b.substring(b.indexOf(" ")+1));
} else {
c.push(b);
}
Display.getInstance().setProperty("pendingPush", null);
}
});
}
a.deleteFile("CN1$AndroidPendingNotifications");
}
} catch(IOException err) {
}
}
public static String[] getPendingPush(String type, Context a) {
InputStream i = null;
try {
i = a.openFileInput("CN1$AndroidPendingNotifications");
if (i == null) {
return null;
}
DataInputStream is = new DataInputStream(i);
int count = is.readByte();
Vector v = new Vector<String>();
for (int iter = 0; iter < count; iter++) {
boolean hasType = is.readBoolean();
String actualType = null;
if (hasType) {
actualType = is.readUTF();
}
final String t;
final String b;
if ("99".equals(actualType)) {
// This was a rich push
Map<String,String> vals = splitQuery(is.readUTF());
t = vals.get("type");
b = vals.get("body");
//category = vals.get("category");
//image = vals.get("image");
} else {
t = actualType;
b = is.readUTF();
//category = null;
//image = null;
}
long s = is.readLong();
if(t != null && ("3".equals(t) || "6".equals(t))) {
String[] m = b.split(";");
v.add(m[0]);
} else if(t != null && "4".equals(t)){
String[] m = b.split(";");
v.add(m[1]);
} else if(t != null && "2".equals(t)){
continue;
}else if (t != null && "101".equals(t)) {
v.add(b.substring(b.indexOf(" ")+1));
}else{
v.add(b);
}
}
String [] retVal = new String[v.size()];
for (int j = 0; j < retVal.length; j++) {
retVal[j] = (String)v.get(j);
}
return retVal;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if(i != null){
i.close();
}
} catch (IOException ex) {
}
}
return null;
}
private static AndroidImplementation instance;
public static AndroidImplementation getInstance() {
return instance;
}