MessagingService / src / com.example.android.messagingservice /

MessageLogger.java

1
/*
2
 * Copyright (C) 2014 The Android Open Source Project
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
 
17
package com.example.android.messagingservice;
18
 
19
import android.content.Context;
20
import android.content.SharedPreferences;
21
 
22
import java.text.SimpleDateFormat;
23
import java.util.Date;
24
 
25
/**
26
 * A simple logger that uses shared preferences to log messages, their reads
27
 * and replies. Don't use this in a real world application. This logger is only
28
 * used for displaying the messages in the text view.
29
 */
30
public class MessageLogger {
31
 
32
    private static final String PREF_MESSAGE = "MESSAGE_LOGGER";
33
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
34
 
35
    public static final String LOG_KEY = "message_data";
36
    public static final String LINE_BREAKS = "\n\n";
37
 
38
    public static void logMessage(Context context, String message) {
39
        SharedPreferences prefs = getPrefs(context);
40
        message = DATE_FORMAT.format(new Date(System.currentTimeMillis())) + ": " + message;
41
        prefs.edit()
42
                .putString(LOG_KEY, prefs.getString(LOG_KEY, "") + LINE_BREAKS + message)
43
                .apply();
44
    }
45
 
46
    public static SharedPreferences getPrefs(Context context) {
47
        return context.getSharedPreferences(PREF_MESSAGE, Context.MODE_PRIVATE);
48
    }
49
 
50
    public static String getAllMessages(Context context) {
51
        return getPrefs(context).getString(LOG_KEY, "");
52
    }
53
 
54
    public static void clear(Context context) {
55
        getPrefs(context).edit().remove(LOG_KEY).apply();
56
    }
57
}