7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
1

Как закрыть диалог

04.06.2013, 02:57. Показов 3832. Ответов 25
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Я запускаю метод, чтобы залогиниться через FB. Всё происходит с помощью фрагмента, после авторизации окно остается фрагмента остается. А как его убрать? Вот код:

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
public void loginFacebook() {
        if (!facebook.isSessionValid()) {
            facebook.authorize(getActivity(),
                    new String[] { "email", "publish_stream" },
                     new DialogListener() {
                        @Override
                        public void onCancel() {
                            // функция отмены действия
                        }
 
                        @Override
                        public void onComplete(Bundle values) {
                                                        
                            accountPrefs.access_token = facebook
                                    .getAccessToken();
                        
                            Log.d(LOG_TAG, "accountPrefs.access_token my "+ accountFPrefs.access_token);
                                                                }
 
                        @Override
                        public void onError(DialogError error) {
 
                            // функция ошибки
                        }
 
                        @Override
                        public void onFacebookError(FacebookError fberror) {
 
                            // функция фейсбучной ошибки
                        }
                    });
        }
                    }
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
04.06.2013, 02:57
Ответы с готовыми решениями:

Закрыть диалог во время выполнения процесса (принудительное срабатывание dismiss()
Всем привет! В приложении есть диалоговое окно с кнопкой, по нажатию которой начинается выполнение...

Как закрыть диалог?
В одном окне я показываю другую public partial class AuthView : Window { public...

Как закрыть диалог с клавиатуры?
Здравствуйте все! Чувствую себя круглым дураком, но никак не могу понять, как же закрыть окно...

Диалог на подтверждение при попытке закрыть программу
При попытке закрыть программу, должен выскочить диалог на подтверждение. Я использовал такой...

25
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
04.06.2013, 04:38  [ТС] 2
дополняю скрином. на правом экране изображен этот фрагмент который я хотел бы закрыть, но он остается висеть.
Миниатюры
Как закрыть диалог  
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
04.06.2013, 18:57  [ТС] 3
Вот только не понятно это фрагмент или это диалог. DialogListener - это что?
0
41 / 41 / 0
Регистрация: 26.05.2013
Сообщений: 160
06.06.2013, 01:05 4
показывай весь код показа фрагмента авторизации в ФБ
1
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
06.06.2013, 03:07  [ТС] 5
Вот код:

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
public class Fragment3 extends ListFragment {
 
        public Facebook facebook;
    public AsyncFacebookRunner mAsyncRunner;
 
 
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View myView = inflater.inflate(R.layout.fragment_screen3,
                container, false);
        
        list = (ListView) myView.findViewById(android.R.id.list);
 
        mViewPager = ((MyActivity) getActivity()).getpager();
 
        //
        butF = (Button) myView.findViewById(R.id.buttonF);
                
        butF.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
 
                // facebook
                fPrefs.restore(getActivity());
                String access_token = fPrefs.access_token;
                long expires = fPrefs.expires;
                if (access_token != null & expires != 0) {
                    resulMy = getCountLooked(myIdGot);
                
                    postMessageOnWall(resulMy, text); 
                }
 
                else{
                        initFB();
                        loginToFacebook();
                }
                
    
            }
        });
          return myView;
    }
 
/** Функция логина в фейсбук */
    public void loginToFacebook() {
 
        if (!facebook.isSessionValid()) {
            facebook.authorize(getActivity(),
                    new String[] { "email", "publish_stream" },
                    new Facebook.DialogListener() {
 
                        @Override
                        public void onCancel() {
 
                            // функция отмены действия
                        }
 
                        @Override
                        public void onComplete(Bundle values) {
                            
                            fPrefs.access_token = facebook
                                    .getAccessToken();
                            fPrefs.expires = facebook.getAccessExpires();
                            fPrefs.save(getActivity());
                                                                        
                            postMessageOnWall(getCountLooked(myIdGot), text);
                        }
 
                        @Override
                        public void onError(DialogError error) {
 
                            // функция ошибки
                        }
 
                        @Override
                        public void onFacebookError(FacebookError fberror) {
 
                            // функция фейсбучной ошибки
                        }
 
                    });
        }
        
        
    }
    
    public void initFB(){
        // инициализируем наши объекты
        facebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        
        loginToFacebook();
}
работа идет с Facebook sdk. Facebook Android sdk
0
41 / 41 / 0
Регистрация: 26.05.2013
Сообщений: 160
06.06.2013, 20:39 6
this.dismiss() ?
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
06.06.2013, 23:49  [ТС] 7
Цитата Сообщение от haribo Посмотреть сообщение
this.dismiss() ?
но наверное тогда уже getActivity().dismiss ? это же в фрагменте всё происходит . И если это, то куда поместить, чтобы правильно сработало??
0
41 / 41 / 0
Регистрация: 26.05.2013
Сообщений: 160
07.06.2013, 00:10 8
именно this, потому сделать это надо непосредственно в диалоге.
поместить нужно туда где нужно закрыть диалог.
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
07.06.2013, 00:46  [ТС] 9
Цитата Сообщение от haribo Посмотреть сообщение
именно this, потому сделать это надо непосредственно в диалоге.
поместить нужно туда где нужно закрыть диалог.
А где этот сам диалог исходя из моего кода??? мои попытки найти его были неудачны.
0
41 / 41 / 0
Регистрация: 26.05.2013
Сообщений: 160
07.06.2013, 01:53 10
не он случаем?

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
facebook.authorize(getActivity(),
                    new String[] { "email", "publish_stream" },
                    new Facebook.DialogListener() {
 
                        @Override
                        public void onCancel() {
 
                            // функция отмены действия
                        }
 
                        @Override
                        public void onComplete(Bundle values) {
                            
                            fPrefs.access_token = facebook
                                    .getAccessToken();
                            fPrefs.expires = facebook.getAccessExpires();
                            fPrefs.save(getActivity());
                                                                        
                            postMessageOnWall(getCountLooked(myIdGot), text);
                        }
 
                        @Override
                        public void onError(DialogError error) {
 
                            // функция ошибки
                        }
 
                        @Override
                        public void onFacebookError(FacebookError fberror) {
 
                            // функция фейсбучной ошибки
                        }
 
                    });
А вообще, надо открыть исходники модуля которым пользуешься и почитать чужой код. Полезно, даже больше, чем 1000 строк своих велосипедов.
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
07.06.2013, 02:11  [ТС] 11
Цитата Сообщение от haribo Посмотреть сообщение
не он случаем?
он скорей всего, так а что именно закрыть нужно? наверное же какой-то объект? Я думаю это, 4 строчка:
Java
1
new Facebook.DialogListener() {
но как, у меня не получилось. Каким способом это сделать или это не здесь этот диалог?

Цитата Сообщение от haribo Посмотреть сообщение
А вообще, надо открыть исходники модуля которым пользуешься и почитать чужой код. Полезно, даже больше, чем 1000 строк своих велосипедов.
Всё Api sdk facebook, можно перелопатить но найти нужное очень сложно.
0
41 / 41 / 0
Регистрация: 26.05.2013
Сообщений: 160
07.06.2013, 09:40 12
после
Java
1
postMessageOnWall(getCountLooked(myIdGot), text);
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
07.06.2013, 11:23  [ТС] 13
но оно мне не дает написать
Java
1
this.dismiss()
пишет: The method dismiss() is undefined for the type new Facebook.DialogListener(){}

как быть?
0
41 / 41 / 0
Регистрация: 26.05.2013
Сообщений: 160
07.06.2013, 11:37 14
щас нет возможности проверить.
могу лишь сказать что тебе нужно завершить диалог - это значит вызвать метод finish() в диалоге или же dialog.dismiss() у объекта твоего диалога
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
07.06.2013, 11:37 15
смотрите код метода authorize
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
07.06.2013, 12:25  [ТС] 16
Цитата Сообщение от haribo Посмотреть сообщение
могу лишь сказать что тебе нужно завершить диалог - это значит вызвать метод finish() в диалоге или же dialog.dismiss() у объекта твоего диалога
но диалог я так понимаю создается здесь
Java
1
  new DialogListener() {
5-ая строчка. Но как бы создается на лету, т.е. сразу new DialogListener, нету такого плана DialogListener dialogLis = new DialogListener(); чтобы я потом мог сделать что-то подобное типа dialogLis.dismiss(). Я пробовал, создать объект, но что-то не получалось. Можно здесь вообще создать экземпляр класса и закрыть его здесь?

Добавлено через 7 минут
Цитата Сообщение от V0v1k Посмотреть сообщение
смотрите код метода authorize
В классе Facebook.class несколько методов authorize и они как-то не особо информативны, может вы поймете. Вот весь код этого класса:
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
/**
 * Copyright 2010-present Facebook
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    [url]http://www.apache.org/licenses/LICENSE-2.0[/url]
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package com.facebook.android;
 
import android.Manifest;
import android.app.Activity;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.net.Uri;
import android.os.*;
import com.facebook.*;
import com.facebook.Session.StatusCallback;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
 
/**
 * THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
 * <p/>
 * All public members of this class are intentionally deprecated.
 * New code should instead use
 * {@link Session} to manage session state,
 * {@link Request} to make API requests, and
 * {@link com.facebook.widget.WebDialog} to make dialog requests.
 * <p/>
 * Adding @Deprecated to this class causes warnings in other deprecated classes
 * that reference this one.  That is the only reason this entire class is not
 * deprecated.
 *
 * @devDocDeprecated
 */
public class Facebook {
 
    // Strings used in the authorization flow
    @Deprecated
    public static final String REDIRECT_URI = "fbconnect://success";
    @Deprecated
    public static final String CANCEL_URI = "fbconnect://cancel";
    @Deprecated
    public static final String TOKEN = "access_token";
    @Deprecated
    public static final String EXPIRES = "expires_in";
    @Deprecated
    public static final String SINGLE_SIGN_ON_DISABLED = "service_disabled";
 
    @Deprecated
    public static final Uri ATTRIBUTION_ID_CONTENT_URI =
        Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider");
    @Deprecated
    public static final String ATTRIBUTION_ID_COLUMN_NAME = "aid";
 
    @Deprecated
    public static final int FORCE_DIALOG_AUTH = -1;
 
    private static final String LOGIN = "oauth";
 
    // Used as default activityCode by authorize(). See authorize() below.
    private static final int DEFAULT_AUTH_ACTIVITY_CODE = 32665;
 
    // Facebook server endpoints: may be modified in a subclass for testing
    @Deprecated
    protected static String DIALOG_BASE_URL = "https://m.facebook.com/dialog/";
    @Deprecated
    protected static String GRAPH_BASE_URL = "https://graph.facebook.com/";
    @Deprecated
    protected static String RESTSERVER_URL = "https://api.facebook.com/restserver.php";
 
    private final Object lock = new Object();
 
    private String accessToken = null;
    private long accessExpiresMillisecondsAfterEpoch = 0;
    private long lastAccessUpdateMillisecondsAfterEpoch = 0;
    private String mAppId;
 
    private Activity pendingAuthorizationActivity;
    private String[] pendingAuthorizationPermissions;
    private Session pendingOpeningSession;
 
    private volatile Session session; // must synchronize this.sync to write
    private boolean sessionInvalidated; // must synchronize this.sync to access
    private SetterTokenCachingStrategy tokenCache;
    private volatile Session userSetSession;
 
    // If the last time we extended the access token was more than 24 hours ago
    // we try to refresh the access token again.
    final private long REFRESH_TOKEN_BARRIER = 24L * 60L * 60L * 1000L;
 
    /**
     * Constructor for Facebook object.
     * 
     * @param appId
     *            Your Facebook application ID. Found at
     *            [url]www.facebook.com/developers/apps.php[/url].
     */
    @Deprecated
    public Facebook(String appId) {
        if (appId == null) {
            throw new IllegalArgumentException("You must specify your application ID when instantiating "
                    + "a Facebook object. See README for details.");
        }
        mAppId = appId;
    }
 
    /**
     * Default authorize method. Grants only basic permissions.
     * <p/>
     * See authorize() below for @params.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     */
    @Deprecated
    public void authorize(Activity activity, final DialogListener listener) {
        authorize(activity, new String[]{}, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK,
                listener);
    }
 
    /**
     * Authorize method that grants custom permissions.
     * <p/>
     * See authorize() below for @params.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     */
    @Deprecated
    public void authorize(Activity activity, String[] permissions, final DialogListener listener) {
        authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK, listener);
    }
 
    /**
     * Full authorize method.
     * <p/>
     * Starts either an Activity or a dialog which prompts the user to log in to
     * Facebook and grant the requested permissions to the given application.
     * <p/>
     * This method will, when possible, use Facebook's single sign-on for
     * Android to obtain an access token. This involves proxying a call through
     * the Facebook for Android stand-alone application, which will handle the
     * authentication flow, and return an OAuth access token for making API
     * calls.
     * <p/>
     * Because this process will not be available for all users, if single
     * sign-on is not possible, this method will automatically fall back to the
     * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
     * by Facebook in an embedded WebView, not by the client application. As
     * such, the dialog makes a network request and renders HTML content rather
     * than a native UI. The access token is retrieved from a redirect to a
     * special URL that the WebView handles.
     * <p/>
     * Note that User credentials could be handled natively using the OAuth 2.0
     * Username and Password Flow, but this is not supported by this SDK.
     * <p/>
     * See [url]http://developers.facebook.com/docs/authentication/[/url] and
     * [url]http://wiki.oauth.net/OAuth-2[/url] for more details.
     * <p/>
     * Note that this method is asynchronous and the callback will be invoked in
     * the original calling thread (not in a background thread).
     * <p/>
     * Also note that requests may be made to the API without calling authorize
     * first, in which case only public information is returned.
     * <p/>
     * IMPORTANT: Note that single sign-on authentication will not function
     * correctly if you do not include a call to the authorizeCallback() method
     * in your onActivityResult() function! Please see below for more
     * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
     * as the activityCode parameter in your call to authorize().
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param activity
     *            The Android activity in which we want to display the
     *            authorization dialog.
     * @param permissions
     *            A list of permissions required for this application: e.g.
     *            "read_stream", "publish_stream", "offline_access", etc. see
     *            [url]http://developers.facebook.com/docs/authentication/permissions[/url]
     *            This parameter should not be null -- if you do not require any
     *            permissions, then pass in an empty String array.
     * @param activityCode
     *            Single sign-on requires an activity result to be called back
     *            to the client application -- if you are waiting on other
     *            activities to return data, pass a custom activity code here to
     *            avoid collisions. If you would like to force the use of legacy
     *            dialog-based authorization, pass FORCE_DIALOG_AUTH for this
     *            parameter. Otherwise just omit this parameter and Facebook
     *            will use a suitable default. See
     *            [url]http://developer.android.com/reference/android/[/url]
     *            app/Activity.html for more information.
     * @param listener
     *            Callback interface for notifying the calling application when
     *            the authentication dialog has completed, failed, or been
     *            canceled.
     */
    @Deprecated
    public void authorize(Activity activity, String[] permissions, int activityCode, final DialogListener listener) {
        SessionLoginBehavior behavior = (activityCode >= 0) ? SessionLoginBehavior.SSO_WITH_FALLBACK
                : SessionLoginBehavior.SUPPRESS_SSO;
 
        authorize(activity, permissions, activityCode, behavior, listener);
    }
 
    /**
     * Full authorize method.
     * 
     * Starts either an Activity or a dialog which prompts the user to log in to
     * Facebook and grant the requested permissions to the given application.
     * 
     * This method will, when possible, use Facebook's single sign-on for
     * Android to obtain an access token. This involves proxying a call through
     * the Facebook for Android stand-alone application, which will handle the
     * authentication flow, and return an OAuth access token for making API
     * calls.
     * 
     * Because this process will not be available for all users, if single
     * sign-on is not possible, this method will automatically fall back to the
     * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
     * by Facebook in an embedded WebView, not by the client application. As
     * such, the dialog makes a network request and renders HTML content rather
     * than a native UI. The access token is retrieved from a redirect to a
     * special URL that the WebView handles.
     * 
     * Note that User credentials could be handled natively using the OAuth 2.0
     * Username and Password Flow, but this is not supported by this SDK.
     * 
     * See [url]http://developers.facebook.com/docs/authentication/[/url] and
     * [url]http://wiki.oauth.net/OAuth-2[/url] for more details.
     * 
     * Note that this method is asynchronous and the callback will be invoked in
     * the original calling thread (not in a background thread).
     * 
     * Also note that requests may be made to the API without calling authorize
     * first, in which case only public information is returned.
     * 
     * IMPORTANT: Note that single sign-on authentication will not function
     * correctly if you do not include a call to the authorizeCallback() method
     * in your onActivityResult() function! Please see below for more
     * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
     * as the activityCode parameter in your call to authorize().
     * 
     * @param activity
     *            The Android activity in which we want to display the
     *            authorization dialog.
     * @param permissions
     *            A list of permissions required for this application: e.g.
     *            "read_stream", "publish_stream", "offline_access", etc. see
     *            [url]http://developers.facebook.com/docs/authentication/permissions[/url]
     *            This parameter should not be null -- if you do not require any
     *            permissions, then pass in an empty String array.
     * @param activityCode
     *            Single sign-on requires an activity result to be called back
     *            to the client application -- if you are waiting on other
     *            activities to return data, pass a custom activity code here to
     *            avoid collisions. If you would like to force the use of legacy
     *            dialog-based authorization, pass FORCE_DIALOG_AUTH for this
     *            parameter. Otherwise just omit this parameter and Facebook
     *            will use a suitable default. See
     *            [url]http://developer.android.com/reference/android/[/url]
     *            app/Activity.html for more information.
     * @param behavior
     *            The {@link SessionLoginBehavior SessionLoginBehavior} that
     *            specifies what behaviors should be attempted during
     *            authorization.
     * @param listener
     *            Callback interface for notifying the calling application when
     *            the authentication dialog has completed, failed, or been
     *            canceled.
     */
    private void authorize(Activity activity, String[] permissions, int activityCode,
                          SessionLoginBehavior behavior, final DialogListener listener) {
        checkUserSession("authorize");
        pendingOpeningSession = new Session.Builder(activity).
                setApplicationId(mAppId).
                setTokenCachingStrategy(getTokenCache()).
                build();
        pendingAuthorizationActivity = activity;
        pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0];
 
        StatusCallback callback = new StatusCallback() {
            @Override
            public void call(Session callbackSession, SessionState state, Exception exception) {
                // Invoke user-callback.
                onSessionCallback(callbackSession, state, exception, listener);
            }
        };
 
        Session.OpenRequest openRequest = new Session.OpenRequest(activity).
                setCallback(callback).
                setLoginBehavior(behavior).
                setRequestCode(activityCode).
                setPermissions(Arrays.asList(permissions));
        openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0);
    }
 
    private void openSession(Session session, Session.OpenRequest openRequest, boolean isPublish) {
        openRequest.setIsLegacy(true);
        if (isPublish) {
            session.openForPublish(openRequest);
        } else {
            session.openForRead(openRequest);
        }
    }
 
    @SuppressWarnings("deprecation")
    private void onSessionCallback(Session callbackSession, SessionState state, Exception exception,
            DialogListener listener) {
        Bundle extras = callbackSession.getAuthorizationBundle();
 
        if (state == SessionState.OPENED) {
            Session sessionToClose = null;
 
            synchronized (Facebook.this.lock) {
                if (callbackSession != Facebook.this.session) {
                    sessionToClose = Facebook.this.session;
                    Facebook.this.session = callbackSession;
                    Facebook.this.sessionInvalidated = false;
                }
            }
 
            if (sessionToClose != null) {
                sessionToClose.close();
            }
 
            listener.onComplete(extras);
        } else if (exception != null) {
            if (exception instanceof FacebookOperationCanceledException) {
                listener.onCancel();
            } else if ((exception instanceof FacebookAuthorizationException) && (extras != null)
                    && extras.containsKey(Session.WEB_VIEW_ERROR_CODE_KEY)
                    && extras.containsKey(Session.WEB_VIEW_FAILING_URL_KEY)) {
                DialogError error = new DialogError(exception.getMessage(),
                        extras.getInt(Session.WEB_VIEW_ERROR_CODE_KEY),
                        extras.getString(Session.WEB_VIEW_FAILING_URL_KEY));
                listener.onError(error);
            } else {
                FacebookError error = new FacebookError(exception.getMessage());
                listener.onFacebookError(error);
            }
        }
    }
 
    /**
     * Helper to validate a service intent by resolving and checking the
     * provider's package signature.
     * 
     * @param context
     * @param intent
     * @return true if the service intent resolution happens successfully and
     *         the signatures match.
     */
    private boolean validateServiceIntent(Context context, Intent intent) {
        ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
        if (resolveInfo == null) {
            return false;
        }
 
        return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName);
    }
 
    /**
     * Query the signature for the application that would be invoked by the
     * given intent and verify that it matches the FB application's signature.
     * 
     * @param context
     * @param packageName
     * @return true if the app's signature matches the expected signature.
     */
    private boolean validateAppSignatureForPackage(Context context, String packageName) {
 
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        } catch (NameNotFoundException e) {
            return false;
        }
 
        for (Signature signature : packageInfo.signatures) {
            if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * IMPORTANT: If you are using the deprecated authorize() method,
     * this method must be invoked at the top of the calling
     * activity's onActivityResult() function or Facebook authentication will
     * not function properly!
     * <p/>
     * If your calling activity does not currently implement onActivityResult(),
     * you must implement it and include a call to this method if you intend to
     * use the authorize() method in this SDK.
     * <p/>
     * For more information, see
     * [url]http://developer.android.com/reference/android/app/[/url]
     * Activity.html#onActivityResult(int, int, android.content.Intent)
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     */
    @Deprecated
    public void authorizeCallback(int requestCode, int resultCode, Intent data) {
        checkUserSession("authorizeCallback");
        Session pending = this.pendingOpeningSession;
        if (pending != null) {
            if (pending.onActivityResult(this.pendingAuthorizationActivity, requestCode, resultCode, data)) {
                this.pendingOpeningSession = null;
                this.pendingAuthorizationActivity = null;
                this.pendingAuthorizationPermissions = null;
            }
        }
    }
 
    /**
     * Refresh OAuth access token method. Binds to Facebook for Android
     * stand-alone application application to refresh the access token. This
     * method tries to connect to the Facebook App which will handle the
     * authentication flow, and return a new OAuth access token. This method
     * will automatically replace the old token with a new one. Note that this
     * method is asynchronous and the callback will be invoked in the original
     * calling thread (not in a background thread).
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param context
     *            The Android Context that will be used to bind to the Facebook
     *            RefreshToken Service
     * @param serviceListener
     *            Callback interface for notifying the calling application when
     *            the refresh request has completed or failed (can be null). In
     *            case of a success a new token can be found inside the result
     *            Bundle under Facebook.ACCESS_TOKEN key.
     * @return true if the binding to the RefreshToken Service was created
     */
    @Deprecated
    public boolean extendAccessToken(Context context, ServiceListener serviceListener) {
        checkUserSession("extendAccessToken");
        Intent intent = new Intent();
 
        intent.setClassName("com.facebook.katana", "com.facebook.katana.platform.TokenRefreshService");
 
        // Verify that the application whose package name is
        // com.facebook.katana
        // has the expected FB app signature.
        if (!validateServiceIntent(context, intent)) {
            return false;
        }
 
        return context.bindService(intent, new TokenRefreshServiceConnection(context, serviceListener),
                Context.BIND_AUTO_CREATE);
    }
 
    /**
     * Calls extendAccessToken if shouldExtendAccessToken returns true.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @return the same value as extendAccessToken if the the token requires
     *         refreshing, true otherwise
     */
    @Deprecated
    public boolean extendAccessTokenIfNeeded(Context context, ServiceListener serviceListener) {
        checkUserSession("extendAccessTokenIfNeeded");
        if (shouldExtendAccessToken()) {
            return extendAccessToken(context, serviceListener);
        }
        return true;
    }
 
    /**
     * Check if the access token requires refreshing.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @return true if the last time a new token was obtained was over 24 hours
     *         ago.
     */
    @Deprecated
    public boolean shouldExtendAccessToken() {
        checkUserSession("shouldExtendAccessToken");
        return isSessionValid()
                && (System.currentTimeMillis() - lastAccessUpdateMillisecondsAfterEpoch >= REFRESH_TOKEN_BARRIER);
    }
 
    /**
     * Handles connection to the token refresh service (this service is a part
     * of Facebook App).
     */
    private class TokenRefreshServiceConnection implements ServiceConnection {
 
        final Messenger messageReceiver = new Messenger(
                new TokenRefreshConnectionHandler(Facebook.this, this));
 
        final ServiceListener serviceListener;
        final Context applicationsContext;
 
        Messenger messageSender = null;
 
        public TokenRefreshServiceConnection(Context applicationsContext, ServiceListener serviceListener) {
            this.applicationsContext = applicationsContext;
            this.serviceListener = serviceListener;
        }
 
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            messageSender = new Messenger(service);
            refreshToken();
        }
 
        @Override
        public void onServiceDisconnected(ComponentName arg) {
            serviceListener.onError(new Error("Service disconnected"));
            // We returned an error so there's no point in
            // keeping the binding open.
            applicationsContext.unbindService(TokenRefreshServiceConnection.this);
        }
 
        private void refreshToken() {
            Bundle requestData = new Bundle();
            requestData.putString(TOKEN, accessToken);
 
            Message request = Message.obtain();
            request.setData(requestData);
            request.replyTo = messageReceiver;
 
            try {
                messageSender.send(request);
            } catch (RemoteException e) {
                serviceListener.onError(new Error("Service connection error"));
            }
        }
    }
 
    // Creating a static Handler class to reduce the possibility of a memory leak.
    // Handler objects for the same thread all share a common Looper object, which they post messages
    // to and read from. As messages contain target Handler, as long as there are messages with target
    // handler in the message queue, the handler cannot be garbage collected. If handler is not static,
    // the instance of the containing class also cannot be garbage collected even if it is destroyed.
    private static class TokenRefreshConnectionHandler extends Handler {
        WeakReference<Facebook> facebookWeakReference;
        WeakReference<TokenRefreshServiceConnection> connectionWeakReference;
 
        TokenRefreshConnectionHandler(Facebook facebook, TokenRefreshServiceConnection connection) {
            super();
            facebookWeakReference = new WeakReference<Facebook>(facebook);
            connectionWeakReference = new WeakReference<TokenRefreshServiceConnection>(connection);
        }
 
        @Override
        @SuppressWarnings("deprecation")
        public void handleMessage(Message msg) {
            Facebook facebook = facebookWeakReference.get();
            TokenRefreshServiceConnection connection = connectionWeakReference.get();
            if (facebook == null || connection == null) {
                return;
            }
 
            String token = msg.getData().getString(TOKEN);
            // Legacy functions in Facebook class (and ServiceListener implementors) expect expires_in in
            // milliseconds from epoch
            long expiresAtMsecFromEpoch = msg.getData().getLong(EXPIRES) * 1000L;
 
            if (token != null) {
                facebook.setAccessToken(token);
                facebook.setAccessExpires(expiresAtMsecFromEpoch);
 
                Session refreshSession = facebook.session;
                if (refreshSession != null) {
                    // Session.internalRefreshToken expects the original bundle with expires_in in seconds from
                    // epoch.
                    LegacyHelper.extendTokenCompleted(refreshSession, msg.getData());
                }
 
                if (connection.serviceListener != null) {
                    // To avoid confusion we should return the expiration time in
                    // the same format as the getAccessExpires() function - that
                    // is in milliseconds.
                    Bundle resultBundle = (Bundle) msg.getData().clone();
                    resultBundle.putLong(EXPIRES, expiresAtMsecFromEpoch);
 
                    connection.serviceListener.onComplete(resultBundle);
                }
            } else if (connection.serviceListener != null) { // extract errors only if
                // client wants them
                String error = msg.getData().getString("error");
                if (msg.getData().containsKey("error_code")) {
                    int errorCode = msg.getData().getInt("error_code");
                    connection.serviceListener.onFacebookError(new FacebookError(error, null, errorCode));
                } else {
                    connection.serviceListener.onError(new Error(error != null ? error : "Unknown service error"));
                }
            }
 
            if (connection != null) {
                // The refreshToken function should be called rarely,
                // so there is no point in keeping the binding open.
                connection.applicationsContext.unbindService(connection);
            }
        }
    }
 
    /**
     * Invalidate the current user session by removing the access token in
     * memory, clearing the browser cookie, and calling auth.expireSession
     * through the API.
     * <p/>
     * Note that this method blocks waiting for a network response, so do not
     * call it in a UI thread.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param context
     *            The Android context in which the logout should be called: it
     *            should be the same context in which the login occurred in
     *            order to clear any stored cookies
     * @throws IOException
     * @throws MalformedURLException
     * @return JSON string representation of the auth.expireSession response
     *         ("true" if successful)
     */
    @Deprecated
    public String logout(Context context) throws MalformedURLException, IOException {
        return logoutImpl(context);
    }
 
    String logoutImpl(Context context) throws MalformedURLException, IOException  {
        checkUserSession("logout");
        Bundle b = new Bundle();
        b.putString("method", "auth.expireSession");
        String response = request(b);
 
        long currentTimeMillis = System.currentTimeMillis();
        Session sessionToClose = null;
 
        synchronized (this.lock) {
            sessionToClose = session;
 
            session = null;
            accessToken = null;
            accessExpiresMillisecondsAfterEpoch = 0;
            lastAccessUpdateMillisecondsAfterEpoch = currentTimeMillis;
            sessionInvalidated = false;
        }
 
        if (sessionToClose != null) {
            sessionToClose.closeAndClearTokenInformation();
        }
 
        return response;
    }
 
    /**
     * Make a request to Facebook's old (pre-graph) API with the given
     * parameters. One of the parameter keys must be "method" and its value
     * should be a valid REST server API method.
     * <p/>
     * See [url]http://developers.facebook.com/docs/reference/rest/[/url]
     * <p/>
     * Note that this method blocks waiting for a network response, so do not
     * call it in a UI thread.
     * <p/>
     * Example: <code>
     *  Bundle parameters = new Bundle();
     *  parameters.putString("method", "auth.expireSession");
     *  String response = request(parameters);
     * </code>
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Request} for more info.
     *
     * @param parameters
     *            Key-value pairs of parameters to the request. Refer to the
     *            documentation: one of the parameters must be "method".
     * @throws IOException
     *             if a network error occurs
     * @throws MalformedURLException
     *             if accessing an invalid endpoint
     * @throws IllegalArgumentException
     *             if one of the parameters is not "method"
     * @return JSON string representation of the response
     */
    @Deprecated
    public String request(Bundle parameters) throws MalformedURLException, IOException {
        if (!parameters.containsKey("method")) {
            throw new IllegalArgumentException("API method must be specified. "
                    + "(parameters must contain key \"method\" and value). See"
                    + " http://developers.facebook.com/docs/reference/rest/");
        }
        return requestImpl(null, parameters, "GET");
    }
 
    /**
     * Make a request to the Facebook Graph API without any parameters.
     * <p/>
     * See [url]http://developers.facebook.com/docs/api[/url]
     * <p/>
     * Note that this method blocks waiting for a network response, so do not
     * call it in a UI thread.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Request} for more info.
     *
     * @param graphPath
     *            Path to resource in the Facebook graph, e.g., to fetch data
     *            about the currently logged authenticated user, provide "me",
     *            which will fetch [url]http://graph.facebook.com/me[/url]
     * @throws IOException
     * @throws MalformedURLException
     * @return JSON string representation of the response
     */
    @Deprecated
    public String request(String graphPath) throws MalformedURLException, IOException {
        return requestImpl(graphPath, new Bundle(), "GET");
    }
 
    /**
     * Make a request to the Facebook Graph API with the given string parameters
     * using an HTTP GET (default method).
     * <p/>
     * See [url]http://developers.facebook.com/docs/api[/url]
     * <p/>
     * Note that this method blocks waiting for a network response, so do not
     * call it in a UI thread.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Request} for more info.
     *
     * @param graphPath
     *            Path to resource in the Facebook graph, e.g., to fetch data
     *            about the currently logged authenticated user, provide "me",
     *            which will fetch [url]http://graph.facebook.com/me[/url]
     * @param parameters
     *            key-value string parameters, e.g. the path "search" with
     *            parameters "q" : "facebook" would produce a query for the
     *            following graph resource:
     *            [url]https://graph.facebook.com/search?q=facebook[/url]
     * @throws IOException
     * @throws MalformedURLException
     * @return JSON string representation of the response
     */
    @Deprecated
    public String request(String graphPath, Bundle parameters) throws MalformedURLException, IOException {
        return requestImpl(graphPath, parameters, "GET");
    }
 
    /**
     * Synchronously make a request to the Facebook Graph API with the given
     * HTTP method and string parameters. Note that binary data parameters (e.g.
     * pictures) are not yet supported by this helper function.
     * <p/>
     * See [url]http://developers.facebook.com/docs/api[/url]
     * <p/>
     * Note that this method blocks waiting for a network response, so do not
     * call it in a UI thread.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Request} for more info.
     *
     * @param graphPath
     *            Path to resource in the Facebook graph, e.g., to fetch data
     *            about the currently logged authenticated user, provide "me",
     *            which will fetch [url]http://graph.facebook.com/me[/url]
     * @param params
     *            Key-value string parameters, e.g. the path "search" with
     *            parameters {"q" : "facebook"} would produce a query for the
     *            following graph resource:
     *            [url]https://graph.facebook.com/search?q=facebook[/url]
     * @param httpMethod
     *            http verb, e.g. "GET", "POST", "DELETE"
     * @throws IOException
     * @throws MalformedURLException
     * @return JSON string representation of the response
     */
    @Deprecated
    public String request(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
            MalformedURLException, IOException {
        return requestImpl(graphPath, params, httpMethod);
    }
 
    // Internal call to avoid deprecated warnings.
    @SuppressWarnings("deprecation")
    String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
            MalformedURLException, IOException {
        params.putString("format", "json");
        if (isSessionValid()) {
            params.putString(TOKEN, getAccessToken());
        }
        String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
        return Util.openUrl(url, httpMethod, params);
    }
 
    /**
     * Generate a UI dialog for the request action in the given Android context.
     * <p/>
     * Note that this method is asynchronous and the callback will be invoked in
     * the original calling thread (not in a background thread).
     *
     * This method is deprecated. See {@link com.facebook.widget.WebDialog}.
     *
     * @param context
     *            The Android context in which we will generate this dialog.
     * @param action
     *            String representation of the desired method: e.g. "login",
     *            "stream.publish", ...
     * @param listener
     *            Callback interface to notify the application when the dialog
     *            has completed.
     */
    @Deprecated
    public void dialog(Context context, String action, DialogListener listener) {
        dialog(context, action, new Bundle(), listener);
    }
 
    /**
     * Generate a UI dialog for the request action in the given Android context
     * with the provided parameters.
     * <p/>
     * Note that this method is asynchronous and the callback will be invoked in
     * the original calling thread (not in a background thread).
     *
     * This method is deprecated. See {@link com.facebook.widget.WebDialog}.
     * 
     * @param context
     *            The Android context in which we will generate this dialog.
     * @param action
     *            String representation of the desired method: e.g. "feed" ...
     * @param parameters
     *            String key-value pairs to be passed as URL parameters.
     * @param listener
     *            Callback interface to notify the application when the dialog
     *            has completed.
     */
    @Deprecated
    public void dialog(Context context, String action, Bundle parameters, final DialogListener listener) {
        parameters.putString("display", "touch");
        parameters.putString("redirect_uri", REDIRECT_URI);
 
        if (action.equals(LOGIN)) {
            parameters.putString("type", "user_agent");
            parameters.putString("client_id", mAppId);
        } else {
            parameters.putString("app_id", mAppId);
            // We do not want to add an access token when displaying the auth dialog.
            if (isSessionValid()) {
                parameters.putString(TOKEN, getAccessToken());
            }
        }
 
        if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            Util.showAlert(context, "Error", "Application requires permission to access the Internet");
        } else {
            new FbDialog(context, action, parameters, listener).show();
        }
    }
 
    /**
     * Returns whether the current access token is valid
     *
     * @return boolean - whether this object has an non-expired session token
     */
    @Deprecated
    public boolean isSessionValid() {
        return (getAccessToken() != null)
                && ((getAccessExpires() == 0) || (System.currentTimeMillis() < getAccessExpires()));
    }
 
    /**
     * Allows the user to set a Session for the Facebook class to use.
     * If a Session is set here, then one should not use the authorize, logout,
     * or extendAccessToken methods which alter the Session object since that may
     * result in undefined behavior. Using those methods after setting the
     * session here will result in exceptions being thrown.
     *
     * @param session the Session object to use, cannot be null
     */
    @Deprecated
    public void setSession(Session session) {
        if (session == null) {
            throw new IllegalArgumentException("session cannot be null");
        }
        synchronized (this.lock) {
            this.userSetSession = session;
        }
    }
 
    private void checkUserSession(String methodName) {
        if (userSetSession != null) {
            throw new UnsupportedOperationException(
                    String.format("Cannot call %s after setSession has been called.", methodName));
        }
    }
 
    /**
     * Get the underlying Session object to use with 3.0 api.
     * 
     * @return Session - underlying session
     */
    @Deprecated
    public final Session getSession() {
        while (true) {
            String cachedToken = null;
            Session oldSession = null;
 
            synchronized (this.lock) {
                if (userSetSession != null) {
                    return userSetSession;
                }
                if ((session != null) || !sessionInvalidated) {
                    return session;
                }
 
                cachedToken = accessToken;
                oldSession = session;
            }
 
            if (cachedToken == null) {
                return null;
            }
 
            // At this point we do not have a valid session, but mAccessToken is
            // non-null.
            // So we can try building a session based on that.
            List<String> permissions;
            if (oldSession != null) {
                permissions = oldSession.getPermissions();
            } else if (pendingAuthorizationPermissions != null) {
                permissions = Arrays.asList(pendingAuthorizationPermissions);
            } else {
                permissions = Collections.<String>emptyList();
            }
 
            Session newSession = new Session.Builder(pendingAuthorizationActivity).
                    setApplicationId(mAppId).
                    setTokenCachingStrategy(getTokenCache()).
                    build();
            if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) {
                return null;
            }
            Session.OpenRequest openRequest =
                    new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions);
            openSession(newSession, openRequest, !permissions.isEmpty());
 
            Session invalidatedSession = null;
            Session returnSession = null;
 
            synchronized (this.lock) {
                if (sessionInvalidated || (session == null)) {
                    invalidatedSession = session;
                    returnSession = session = newSession;
                    sessionInvalidated = false;
                }
            }
 
            if (invalidatedSession != null) {
                invalidatedSession.close();
            }
 
            if (returnSession != null) {
                return returnSession;
            }
            // Else token state changed between the synchronized blocks, so
            // retry..
        }
    }
 
    /**
     * Retrieve the OAuth 2.0 access token for API access: treat with care.
     * Returns null if no session exists.
     *
     * @return String - access token
     */
    @Deprecated
    public String getAccessToken() {
        Session s = getSession();
        if (s != null) {
            return s.getAccessToken();
        } else {
            return null;
        }
    }
 
    /**
     * Retrieve the current session's expiration time (in milliseconds since
     * Unix epoch), or 0 if the session doesn't expire or doesn't exist.
     *
     * @return long - session expiration time
     */
    @Deprecated
    public long getAccessExpires() {
        Session s = getSession();
        if (s != null) {
            return s.getExpirationDate().getTime();
        } else {
            return accessExpiresMillisecondsAfterEpoch;
        }
    }
 
    /**
     * Retrieve the last time the token was updated (in milliseconds since
     * the Unix epoch), or 0 if the token has not been set.
     *
     * @return long - timestamp of the last token update.
     */
    @Deprecated
    public long getLastAccessUpdate() {
        return lastAccessUpdateMillisecondsAfterEpoch;
    }
 
    /**
     * Restore the token, expiration time, and last update time from cached values.
     * These should be values obtained from getAccessToken(), getAccessExpires, and
     * getLastAccessUpdate() respectively.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param accessToken - access token
     * @param accessExpires - access token expiration time
     * @param lastAccessUpdate - timestamp of the last token update
     */
    @Deprecated
    public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) {
        checkUserSession("setTokenFromCache");
        synchronized (this.lock) {
            this.accessToken = accessToken;
            accessExpiresMillisecondsAfterEpoch = accessExpires;
            lastAccessUpdateMillisecondsAfterEpoch = lastAccessUpdate;
        }
    }
 
    /**
     * Set the OAuth 2.0 access token for API access.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param token
     *            - access token
     */
    @Deprecated
    public void setAccessToken(String token) {
        checkUserSession("setAccessToken");
        synchronized (this.lock) {
            accessToken = token;
            lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis();
            sessionInvalidated = true;
        }
    }
 
    /**
     * Set the current session's expiration time (in milliseconds since Unix
     * epoch), or 0 if the session doesn't expire.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param timestampInMsec
     *            - timestamp in milliseconds
     */
    @Deprecated
    public void setAccessExpires(long timestampInMsec) {
        checkUserSession("setAccessExpires");
        synchronized (this.lock) {
            accessExpiresMillisecondsAfterEpoch = timestampInMsec;
            lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis();
            sessionInvalidated = true;
        }
    }
 
    /**
     * Set the current session's duration (in seconds since Unix epoch), or "0"
     * if session doesn't expire.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param expiresInSecsFromNow
     *            - duration in seconds (or 0 if the session doesn't expire)
     */
    @Deprecated
    public void setAccessExpiresIn(String expiresInSecsFromNow) {
        checkUserSession("setAccessExpiresIn");
        if (expiresInSecsFromNow != null) {
            long expires = expiresInSecsFromNow.equals("0") ? 0 : System.currentTimeMillis()
                    + Long.parseLong(expiresInSecsFromNow) * 1000L;
            setAccessExpires(expires);
        }
    }
 
    /**
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @return the String representing application ID
     */
    @Deprecated
    public String getAppId() {
        return mAppId;
    }
 
    /**
     * This method is deprecated.  See {@link Facebook} and {@link Session} for more info.
     *
     * @param appId the String representing the application ID
     */
    @Deprecated
    public void setAppId(String appId) {
        checkUserSession("setAppId");
        synchronized (this.lock) {
            mAppId = appId;
            sessionInvalidated = true;
        }
    }
 
    private TokenCachingStrategy getTokenCache() {
        // Intentionally not volatile/synchronized--it is okay if we race to
        // create more than one of these.
        if (tokenCache == null) {
            tokenCache = new SetterTokenCachingStrategy();
        }
        return tokenCache;
    }
 
    private static String[] stringArray(List<String> list) {
        String[] array = new String[list.size()];
 
        if (list != null) {
            for (int i = 0; i < array.length; i++) {
                array[i] = list.get(i);
            }
        }
 
        return array;
    }
 
    private static List<String> stringList(String[] array) {
        if (array != null) {
            return Arrays.asList(array);
        } else {
            return Collections.emptyList();
        }
    }
 
    private class SetterTokenCachingStrategy extends TokenCachingStrategy {
 
        @Override
        public Bundle load() {
            Bundle bundle = new Bundle();
 
            if (accessToken != null) {
                TokenCachingStrategy.putToken(bundle, accessToken);
                TokenCachingStrategy.putExpirationMilliseconds(bundle, accessExpiresMillisecondsAfterEpoch);
                TokenCachingStrategy.putPermissions(bundle, stringList(pendingAuthorizationPermissions));
                TokenCachingStrategy.putSource(bundle, AccessTokenSource.WEB_VIEW);
                TokenCachingStrategy.putLastRefreshMilliseconds(bundle, lastAccessUpdateMillisecondsAfterEpoch);
            }
 
            return bundle;
        }
 
        @Override
        public void save(Bundle bundle) {
            accessToken = TokenCachingStrategy.getToken(bundle);
            accessExpiresMillisecondsAfterEpoch = TokenCachingStrategy.getExpirationMilliseconds(bundle);
            pendingAuthorizationPermissions = stringArray(TokenCachingStrategy.getPermissions(bundle));
            lastAccessUpdateMillisecondsAfterEpoch = TokenCachingStrategy.getLastRefreshMilliseconds(bundle);
        }
 
        @Override
        public void clear() {
            accessToken = null;
        }
    }
 
    /**
     * Get Attribution ID for app install conversion tracking.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Settings} for more info.
     *
     * @param contentResolver
     * @return Attribution ID that will be used for conversion tracking. It will be null only if
     *         the user has not installed or logged in to the Facebook app.
     */
    @Deprecated
    public static String getAttributionId(ContentResolver contentResolver) {
        return Settings.getAttributionId(contentResolver);
    }
 
    /**
     * Get the auto install publish setting.  If true, an install event will be published during authorize(), unless
     * it has occurred previously or the app does not have install attribution enabled on the application's developer
     * config page.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Settings} for more info.
     *
     * @return a Boolean indicating whether installation of the app should be auto-published.
     */
    @Deprecated
    public boolean getShouldAutoPublishInstall() {
        return Settings.getShouldAutoPublishInstall();
    }
 
    /**
     * Sets whether auto publishing of installs will occur.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Settings} for more info.
     *
     * @param value a Boolean indicating whether installation of the app should be auto-published.
     */
    @Deprecated
    public void setShouldAutoPublishInstall(boolean value) {
        Settings.setShouldAutoPublishInstall(value);
    }
 
    /**
     * Manually publish install attribution to the Facebook graph.  Internally handles tracking repeat calls to prevent
     * multiple installs being published to the graph.
     * <p/>
     * This method is deprecated.  See {@link Facebook} and {@link Settings} for more info.
     *
     * @param context the current Android context
     * @return Always false.  Earlier versions of the API returned true if it was no longer necessary to call.
     * Apps should ignore this value, but for compatibility we will return false to ensure repeat calls (and the
     * underlying code will prevent duplicate network traffic).
     */
    @Deprecated
    public boolean publishInstall(final Context context) {
        Settings.publishInstallAsync(context, mAppId);
        return false;
    }
 
    /**
     * Callback interface for dialog requests.
     * <p/>
     * THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
     * <p/>
     * All public members of this class are intentionally deprecated.
     * New code should instead use
     * {@link com.facebook.widget.WebDialog}
     * <p/>
     * Adding @Deprecated to this class causes warnings in other deprecated classes
     * that reference this one.  That is the only reason this entire class is not
     * deprecated.
     *
     * @devDocDeprecated
     */
    public static interface DialogListener {
 
        /**
         * Called when a dialog completes.
         * 
         * Executed by the thread that initiated the dialog.
         * 
         * @param values
         *            Key-value string pairs extracted from the response.
         */
        public void onComplete(Bundle values);
 
        /**
         * Called when a Facebook responds to a dialog with an error.
         * 
         * Executed by the thread that initiated the dialog.
         * 
         */
        public void onFacebookError(FacebookError e);
 
        /**
         * Called when a dialog has an error.
         * 
         * Executed by the thread that initiated the dialog.
         * 
         */
        public void onError(DialogError e);
 
        /**
         * Called when a dialog is canceled by the user.
         * 
         * Executed by the thread that initiated the dialog.
         * 
         */
        public void onCancel();
 
    }
 
    /**
     * Callback interface for service requests.
     * <p/>
     * THIS CLASS SHOULD BE CONSIDERED DEPRECATED.
     * <p/>
     * All public members of this class are intentionally deprecated.
     * New code should instead use
     * {@link Session} to manage session state.
     * <p/>
     * Adding @Deprecated to this class causes warnings in other deprecated classes
     * that reference this one.  That is the only reason this entire class is not
     * deprecated.
     *
     * @devDocDeprecated
     */
    public static interface ServiceListener {
 
        /**
         * Called when a service request completes.
         * 
         * @param values
         *            Key-value string pairs extracted from the response.
         */
        public void onComplete(Bundle values);
 
        /**
         * Called when a Facebook server responds to the request with an error.
         */
        public void onFacebookError(FacebookError e);
 
        /**
         * Called when a Facebook Service responds to the request with an error.
         */
        public void onError(Error e);
 
    }
 
    @Deprecated
    public static final String FB_APP_SIGNATURE =
        "30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310"
        + "b3009060355040613025553310b30090603550408130243413112301006035504"
        + "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204"
        + "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504"
        + "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333"
        + "13231353231365a180f32303530303932353231353231365a307a310b30090603"
        + "55040613025553310b30090603550408130243413112301006035504071309506"
        + "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c"
        + "653111300f060355040b130846616365626f6f6b311d301b06035504031314466"
        + "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01"
        + "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa"
        + "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7"
        + "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc"
        + "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603"
        + "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050"
        + "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c"
        + "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6"
        + "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2"
        + "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd"
        + "928a2";
}
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
07.06.2013, 12:52 17
Цитата Сообщение от Stylish2013 Посмотреть сообщение
Java
1
new FbDialog(context, action, parameters, listener).show();
вот строка создания и вывода диалога.

Добавлено через 1 минуту
а зачем вам его закрывать?
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
07.06.2013, 13:12  [ТС] 18
Цитата Сообщение от V0v1k Посмотреть сообщение
а зачем вам его закрывать?
После авторизации он остается висеть на экране.

Добавлено через 3 минуты
Цитата Сообщение от V0v1k Посмотреть сообщение
вот строка создания и вывода диалога.
но я ничего не могу изменить и дописать в Facebook.class
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
07.06.2013, 13:14 19
Цитата Сообщение от Stylish2013 Посмотреть сообщение
После авторизации он остается висеть на экране.
странно, не должно такого быть...

Цитата Сообщение от Stylish2013 Посмотреть сообщение
но я ничего не могу изменить и дописать в Facebook.class
можете изменить Facebook.java
0
7 / 7 / 1
Регистрация: 20.04.2013
Сообщений: 666
07.06.2013, 13:23  [ТС] 20
Цитата Сообщение от V0v1k Посмотреть сообщение
странно, не должно такого быть...
вот и я так думаю.

Цитата Сообщение от V0v1k Посмотреть сообщение
можете изменить Facebook.java
а, что изменить подскажите. Ведь просто FbDialog.dismiss(); не сделаешь.
0
07.06.2013, 13:23
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
07.06.2013, 13:23
Помогаю со студенческими работами здесь

Завершить работу слота (закрыть диалог) потока, если извне для него была вызвана exit()
Привет! С Qt работал мало и очень давно, поэтому задаю такие вопросы. Смотрите - в самом...

Как создать диалог выбора шрифта и диалог выбора цвета
как создать диалог выбора шрифта и диалог выбора цвета в wpf

как сделать так,чтобы когда я нажимаю кнопку закрыть в правом верхнем углу выходило окно сообшение?(типа вы хотите закрыть программу/да или нет/)
как сделать так,чтобы когда я нажимаю кнопку закрыть в правом верхнем углу выходило окно...

Как обработать диалог?
как сделать так чтобы после открытия диалога он не пропадал по нажатию пальцем в зоне активити...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru