Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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