Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

Rev 27 | Rev 29 | 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
    {
28 gabriel 111
 
27 gabriel 112
        Log.e("FcmMessagingService", "onNewToken token = " + fcm_token);
28 gabriel 113
 
114
        String uuid = UniqueID.id(getApplicationContext());
115
 
27 gabriel 116
        preference.setDeviceToken (fcm_token);
28 gabriel 117
        preference.setDeviceUuid(uuid);
27 gabriel 118
        preference.save();
1 gabriel 119
 
28 gabriel 120
        Sync sync = new Sync(Constants.SYNC_ADAPTER_TYPE_DEVICE, uuid);
121
        mAppDatabase.getSyncDao().insert(sync);
1 gabriel 122
 
28 gabriel 123
        sync = new Sync(Constants.SYNC_ADAPTER_TYPE_FCM, fcm_token);
124
        mAppDatabase.getSyncDao().insert(sync);
125
 
126
        syncTokenFMCTo2getSkillServer();
127
/*
27 gabriel 128
            Intent intent = new Intent(Constants.BROADCAST_TYPE_TOKEN);
129
            intent.putExtra("token", Functions.trimNull(fcm_token));
28 gabriel 130
            sendBroadcast(intent);
131
 */
132
 
133
    }
134
 
135
    private void syncTokenFMCTo2getSkillServer(){
136
 
137
 
138
        SyncDao syncDao = mAppDatabase.getSyncDao();
139
        List<Sync> records = syncDao.selectBatch();
140
 
141
        if(records.size() > 0) {
142
            syncToServer(records);
27 gabriel 143
        }
28 gabriel 144
}
145
 
146
    public void syncToServer(List<Sync> records) {
147
 
148
        for (Sync record : records) {
149
            if (record.getType() == Constants.SYNC_ADAPTER_TYPE_DEVICE && !isSyncDevice) {
150
 
151
 
152
                try {
153
                    Http http = new Http(this.getCacheDir());
154
                    OkHttpClient client = http.getHttpClient(false);
155
 
156
                    RequestBody formBody = new FormBody.Builder()
157
                            .add(Constants.POST_DEVICE_FIELD_APPLICATION_ID, String.valueOf(Configuration.APPLICATION_ID))
158
                            .add(Constants.POST_DEVICE_FIELD_DEVICE_UUID, preference.getDeviceUuid())
159
                            .add(Constants.POST_DEVICE_FIELD_MANUFACTURER, Build.MANUFACTURER)
160
                            .add(Constants.POST_DEVICE_FIELD_BRAND, Build.BRAND)
161
                            .add(Constants.POST_DEVICE_FIELD_VERSION, Build.VERSION.RELEASE + " " + Build.VERSION_CODES.class.getFields()[android.os.Build.VERSION.SDK_INT].getName())
162
                            .add(Constants.POST_DEVICE_FIELD_MODEL, Build.MODEL)
163
                            .add(Constants.POST_DEVICE_FIELD_PLATFORM, "android")
164
                            .add(Constants.POST_DEVICE_FIELD_SYNC_ID, String.valueOf(record.getId()))
165
                            .build();
166
 
167
                    Log.d(TAG, "URL = " + Configuration.URL_DEVICE);
168
                    Request request = new Request.Builder()
169
                            .url(Configuration.URL_DEVICE)
170
                            .post(formBody)
171
                            .build();
172
 
173
                    Call call = client.newCall(request);
174
                    call.enqueue(new okhttp3.Callback() {
175
                        public void onResponse(Call call, Response response)
176
                                throws IOException {
177
                           // isSyncDevice = false;
178
                            Log.d(TAG, "Response Device :  " + response.body().toString());
179
 
180
                            processResponseSyncToServer(response.body().string(), "device");
181
                        }
182
 
183
                        public void onFailure(Call call, IOException e) {
184
                            isSyncDevice = false;
185
                            Log.d(TAG, "Error :  " + e.getMessage());
186
                        }
187
                    });
188
                } catch (Exception e) {
189
                }
190
            }
191
            if(record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncDevice){
192
 
193
                //Sucede que intenta sincronizar primero el Token antes que el device.
194
                Log.e("Esta intentando","sync el token antes que device");
195
            }
196
 
197
            if (record.getType() == Constants.SYNC_ADAPTER_TYPE_FCM && !isSyncToken && isSyncDevice) {
198
                isSyncToken = true;
199
                Log.d(TAG, "FCM");
200
                Log.e("Token a Sync", "" + record.getData());
201
 
202
                try {
203
                    Http http = new Http(this.getCacheDir());
204
                    OkHttpClient client = http.getHttpClient(false);
205
 
206
                    RequestBody formBody = new FormBody.Builder()
207
                            .add(Constants.POST_FCM_FIELD_DEVICE_UUID, preference.getDeviceUuid())
208
                            .add(Constants.POST_FCM_FIELD_TOKEN, record.getData())
209
                            .add(Constants.POST_FCM_FIELD_SYNC_ID, String.valueOf(record.getId()))
210
                            .build();
211
 
212
                    Log.d(TAG, "URL = " + Configuration.URL_FCM);
213
                    Request request = new Request.Builder()
214
                            .url(Configuration.URL_FCM)
215
                            .post(formBody)
216
                            .build();
217
 
218
                    Call call = client.newCall(request);
219
                    call.enqueue(new okhttp3.Callback() {
220
                        public void onResponse(Call call, Response response)
221
                                throws IOException {
222
                            isSyncToken = false;
223
                            Log.e("Send FCM Token", "Procesando respuesta..");
224
                            processResponseSyncToServer(response.body().string(), "fcmtoken");
225
                        }
226
 
227
                        public void onFailure(Call call, IOException e) {
228
                            Log.d(TAG, "Error :  " + e.getMessage());
229
                            isSyncToken = false;
230
                        }
231
                    });
232
                } catch (Exception e) {
233
                    e.printStackTrace();
234
 
235
                }
236
            }
237
        }
1 gabriel 238
    }
239
 
28 gabriel 240
    private void processResponseSyncToServer(String dataString, String origen)
241
    {
242
        boolean success = false;
243
        long sync_id = 0;
244
 
245
        Log.d(TAG, "processResponseServer = " + dataString);
246
        try {
247
            JSONObject objJSON = new JSONObject(dataString);
248
            success = objJSON.has("success") ? objJSON.getBoolean("success")  : false;
249
            if(success  && objJSON.has("data")) {
250
                JSONObject jsonObjectData = objJSON.getJSONObject("data");
251
 
252
 
253
                if(jsonObjectData.has("sync_id")) {
254
                    sync_id = jsonObjectData.getLong("sync_id");
255
                }
256
 
257
            }
258
            Log.d(TAG, "SyncID = " + sync_id);
259
            if(success && sync_id > 0) {
260
                Log.d(TAG, "DELETE SYNC RECORD : " + sync_id);
261
                mAppDatabase.getSyncDao().remove(sync_id);
262
 
263
                if(origen.equals("device"))
264
                {
265
                    Log.e("Sync","device exitoso, ahora sigo con TokenFCM");
266
                    isSyncDevice=true;
267
                    syncTokenFMCTo2getSkillServer();
268
                }
269
                if(origen.equals("fcmtoken")){
270
                    Log.e("Token", "termino de sync con exito");
271
                }
272
            }
273
        } catch (JSONException e) {
274
            e.printStackTrace();
275
        }
276
    }
277
 
1 gabriel 278
}