• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.DateFormat;
23 import java.text.SimpleDateFormat;
24 import java.util.Date;
25 
26 /**
27  * A simple logger that uses shared preferences to log messages, their reads
28  * and replies. Don't use this in a real world application. This logger is only
29  * used for displaying the messages in the text view.
30  */
31 class MessageLogger {
32 
33     private static final String PREF_MESSAGE = "MESSAGE_LOGGER";
34     private static final DateFormat DATE_FORMAT = SimpleDateFormat.getDateTimeInstance();
35     private static final String LINE_BREAKS = "\n\n";
36 
37     public static final String LOG_KEY = "message_data";
38 
logMessage(Context context, String message)39     public static void logMessage(Context context, String message) {
40         SharedPreferences prefs = getPrefs(context);
41         message = DATE_FORMAT.format(new Date(System.currentTimeMillis())) + ": " + message;
42         prefs.edit()
43                 .putString(LOG_KEY, prefs.getString(LOG_KEY, "") + LINE_BREAKS + message)
44                 .apply();
45     }
46 
getPrefs(Context context)47     public static SharedPreferences getPrefs(Context context) {
48         return context.getSharedPreferences(PREF_MESSAGE, Context.MODE_PRIVATE);
49     }
50 
getAllMessages(Context context)51     public static String getAllMessages(Context context) {
52         return getPrefs(context).getString(LOG_KEY, "");
53     }
54 
clear(Context context)55     public static void clear(Context context) {
56         getPrefs(context).edit().remove(LOG_KEY).apply();
57     }
58 }
59