Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 28 | Rev 30 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 gabriel 1
package com.cesams.twogetskills.service;
2
import android.content.Intent;
28 gabriel 3
import android.graphics.drawable.Drawable;
4
import android.os.Build;
5
import android.text.TextUtils;
1 gabriel 6
import android.util.Log;
7
 
27 gabriel 8
import com.cesams.twogetskills.Configuration;
1 gabriel 9
import com.cesams.twogetskills.Constants;
28 gabriel 10
import com.cesams.twogetskills.dao.AppDatabase;
11
import com.cesams.twogetskills.dao.DatabaseHelper;
12
import com.cesams.twogetskills.dao.SyncDao;
13
import com.cesams.twogetskills.entity.Sync;
1 gabriel 14
import com.cesams.twogetskills.library.Functions;
27 gabriel 15
import com.cesams.twogetskills.library.Http;
28 gabriel 16
import com.cesams.twogetskills.library.UniqueID;
27 gabriel 17
import com.cesams.twogetskills.preference.Preference;
1 gabriel 18
import com.google.firebase.messaging.FirebaseMessagingService;
19
import com.google.firebase.messaging.RemoteMessage;
20
 
28 gabriel 21
import org.json.JSONException;
22
import org.json.JSONObject;
23
 
27 gabriel 24
import java.io.IOException;
28 gabriel 25
import java.util.List;
1 gabriel 26
 
27 gabriel 27
import okhttp3.Call;
28
import okhttp3.FormBody;
29
import okhttp3.OkHttpClient;
30
import okhttp3.Request;
31
import okhttp3.RequestBody;
32
import okhttp3.Response;
1 gabriel 33
 
27 gabriel 34
 
1 gabriel 35
public class FcmMessagingService extends FirebaseMessagingService {
36
 
37
 
38
    private static final String TAG = "C2GS - FcmMessageServ";
28 gabriel 39
    private AppDatabase mAppDatabase;
40
    boolean isSyncDevice = false;
41
    boolean isSyncToken = false;
42
    Preference preference;
1 gabriel 43
 
27 gabriel 44
 
1 gabriel 45
    @Override
46
    public void onCreate() {
28 gabriel 47
 
48
        preference = Preference.getInstance(getApplicationContext());
49
        preference.load();
50
        mAppDatabase = DatabaseHelper.getInstance(getApplicationContext()).getAppDatabase();
1 gabriel 51
        super.onCreate();
52
    }
53
 
54
    public void onMessageReceived(RemoteMessage remoteMessage) {
55
 
28 gabriel 56
 
1 gabriel 57
        Log.d("FcmMessagingService", "onMessageReceived");
58
 
59
        if (remoteMessage.getData().size() > 0) {
60
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
61
 
62
            if(remoteMessage.getData().containsKey("command")) {
63
                String command = remoteMessage.getData().get("command").trim();
64
 
65
                Intent intent = new Intent(Constants.BROADCAST_TYPE_COMMAND);
66
                intent.putExtra("command", command);
28 gabriel 67
                sendBroadcast(intent);
1 gabriel 68
            }
69
        }
70
        if (remoteMessage.getNotification() != null) {
71
            String title = remoteMessage.getNotification().getTitle();
72
            String body = remoteMessage.getNotification().getBody();
73
 
74
 
75
            String command = "";
76
            int new_capsules = 0;
77
            if (remoteMessage.getData().size() > 0) {
78
                Log.d(TAG, "Message data payload: " + remoteMessage.getData());
79
 
80
                if(remoteMessage.getData().containsKey("command")) {
81
                    command = remoteMessage.getData().get("command").trim();
82
                }
83
 
84
                if(remoteMessage.getData().containsKey("new_capsules")) {
85
                   new_capsules = Functions.Numero2Int(remoteMessage.getData().get("new_capsules"));
86
                }
87
            }
88
 
89
            Log.d(TAG, "title = " + title);
90
            Log.d(TAG, "body = " + body);
91
            Log.d(TAG, "command = " + command);
92
            Log.d(TAG, "new_capsules = " + new_capsules);
93
 
94
            Intent intent = new Intent(Constants.BROADCAST_TYPE_NOTIFICATION);
95
            intent.putExtra("title", title);
96
            intent.putExtra("body", body);
97
            intent.putExtra("command", command);
8 gabriel 98
            intent.putExtra("new_capsules", new_capsules);
1 gabriel 99
 
100
 
101
 
28 gabriel 102
            sendBroadcast(intent);
1 gabriel 103
        }
104
    }
105
 
106
 
107
 
28 gabriel 108
 
1 gabriel 109
    public void onNewToken(String fcm_token)
110
    {
29 efrain 111
        Log.e("BUG Token", "Token 2 :  " + fcm_token);
112
        /*
27 gabriel 113
        Log.e("FcmMessagingService", "onNewToken token = " + fcm_token);
28 gabriel 114
 
115
        String uuid = UniqueID.id(getApplicationContext());
116
 
27 gabriel 117
        preference.setDeviceToken (fcm_token);
28 gabriel 118
        preference.setDeviceUuid(uuid);
27 gabriel 119
        preference.save();
1 gabriel 120
 
28 gabriel 121
        Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_DEVICE, uuid);
122
        mAppDatabase.getSyncDao().insert(sync);
1 gabriel 123
 
28 gabriel 124
        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, fcm_token);
125
        mAppDatabase.getSyncDao().insert(sync);
126
 
127
        syncTokenFMCTo2getSkillServer();
29 efrain 128
 
27 gabriel 129
            Intent intent = new Intent(Constants.BROADCAST_TYPE_TOKEN);
130
            intent.putExtra("token", Functions.trimNull(fcm_token));
28 gabriel 131
            sendBroadcast(intent);
132
 */
133
 
134
    }
135
 
136
    private void syncTokenFMCTo2getSkillServer(){
137
 
138
 
139
        SyncDao syncDao = mAppDatabase.getSyncDao();
140
        List<Sync> records = syncDao.selectBatch();
141
 
142
        if(records.size() > 0) {
143
            syncToServer(records);
27 gabriel 144
        }
28 gabriel 145
}
146
 
147
    public void syncToServer(List<Sync> records) {
148
 
149
        for (Sync record : records) {
150
            if (record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
151
 
152
 
153
                try {
154
                    Http http = new Http(this.getCacheDir());
155
                    OkHttpClient client = http.getHttpClient(false);
156
 
157
                    RequestBody formBody = new FormBody.Builder()
158
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID, String.valueOf(Configuration.APPLICATION_ID))
159
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
160
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
161
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
162
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
163
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
164
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
165
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
166
                            .build();
167
 
168
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
169
                    Request request = new Request.Builder()
170
                            .url(Configuration.URL_DEVICE)
171
                            .post(formBody)
172
                            .build();
173
 
174
                    Call call = client.newCall(request);
175
                    call.enqueue(new okhttp3.Callback() {
176
                        public void onResponse(Call call, Response response)
177
                                throws IOException {
178
                           // isSyncDevice = false;
179
                            Log.d(TAG, "Response Device :  " + response.body().toString());
180
 
181
                            processResponseSyncToServer(response.body().string(), "device");
182
                        }
183
 
184
                        public void onFailure(Call call, IOException e) {
185
                            isSyncDevice = false;
186
                            Log.d(TAG, "Error :  " + e.getMessage());
187
                        }
188
                    });
189
                } catch (Exception e) {
190
                }
191
            }
192
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncDevice){
193
 
194
                //Sucede que intenta sincronizar primero el Token antes que el device.
195
                Log.e("Esta intentando","sync el token antes que device");
196
            }
197
 
198
            if (record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken && isSyncDevice) {
199
                isSyncToken = true;
200
                Log.d(TAG, "FCM");
201
                Log.e("Token a Sync", "" + record.getData());
202
 
203
                try {
204
                    Http http = new Http(this.getCacheDir());
205
                    OkHttpClient client = http.getHttpClient(false);
206
 
207
                    RequestBody formBody = new FormBody.Builder()
208
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID, preference.getDeviceUuid())
209
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
210
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
211
                            .build();
212
 
213
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
214
                    Request request = new Request.Builder()
215
                            .url(Configuration.URL_FCM)
216
                            .post(formBody)
217
                            .build();
218
 
219
                    Call call = client.newCall(request);
220
                    call.enqueue(new okhttp3.Callback() {
221
                        public void onResponse(Call call, Response response)
222
                                throws IOException {
223
                            isSyncToken = false;
224
                            Log.e("Send FCM Token", "Procesando respuesta..");
225
                            processResponseSyncToServer(response.body().string(), "fcmtoken");
226
                        }
227
 
228
                        public void onFailure(Call call, IOException e) {
229
                            Log.d(TAG, "Error :  " + e.getMessage());
230
                            isSyncToken = false;
231
                        }
232
                    });
233
                } catch (Exception e) {
234
                    e.printStackTrace();
235
 
236
                }
237
            }
238
        }
1 gabriel 239
    }
240
 
28 gabriel 241
    private void processResponseSyncToServer(String dataString, String origen)
242
    {
243
        boolean success = false;
244
        long sync_id = 0;
245
 
246
        Log.d(TAG, "processResponseServer = " + dataString);
247
        try {
248
            JSONObject objJSON = new JSONObject(dataString);
249
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
250
            if(success  && objJSON.has("data")) {
251
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
252
 
253
 
254
                if(jsonObjectData.has("sync_id")) {
255
                    sync_id = jsonObjectData.getLong("sync_id");
256
                }
257
 
258
            }
259
            Log.d(TAG, "SyncID = " + sync_id);
260
            if(success && sync_id > 0) {
261
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
262
                mAppDatabase.getSyncDao().remove(sync_id);
263
 
264
                if(origen.equals("device"))
265
                {
266
                    Log.e("Sync","device exitoso, ahora sigo con TokenFCM");
267
                    isSyncDevice=true;
268
                    syncTokenFMCTo2getSkillServer();
269
                }
270
                if(origen.equals("fcmtoken")){
271
                    Log.e("Token", "termino de sync con exito");
272
                }
273
            }
274
        } catch (JSONException e) {
275
            e.printStackTrace();
276
        }
277
    }
278
 
1 gabriel 279
}