Proyectos de Subversion Android Microlearning - Nuevo Interface

Rev

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