OSDN Git Service

T29631
[everfolder/source.git] / source / workspace / EverFolder / src / com / yuji / ef / service / NoteUpdatorService.java
1 package com.yuji.ef.service;
2
3 import java.util.Calendar;
4
5 import android.app.AlarmManager;
6 import android.app.PendingIntent;
7 import android.app.Service;
8 import android.content.Context;
9 import android.content.Intent;
10 import android.os.Binder;
11 import android.os.IBinder;
12 import android.widget.Toast;
13
14 import com.evernote.client.oauth.android.EvernoteSession;
15 import com.yuji.ef.Initialize;
16 import com.yuji.ef.R;
17 import com.yuji.ef.SettingActivity;
18 import com.yuji.ef.common.Constant;
19 import com.yuji.ef.dao.LockDao;
20 import com.yuji.ef.dao.NodeCacheDao;
21 import com.yuji.ef.dao.NodeDao;
22 import com.yuji.ef.exception.EfError;
23 import com.yuji.ef.exception.EfException;
24 import com.yuji.ef.exception.RollbackException;
25 import com.yuji.ef.pref.EditPrefUtil;
26 import com.yuji.ef.task.NoteUpdateTask;
27 import com.yuji.ef.utility.DateUtil;
28 import com.yuji.ef.utility.Debug;
29 import com.yuji.ef.utility.EvernoteUtil;
30 import com.yuji.ef.utility.NetworkUtil;
31 import com.yuji.ef.utility.OAuthUtil;
32
33 public class NoteUpdatorService extends Service {
34         private static final boolean DEBUG = false;
35
36         public class KitchenTimerBinder extends Binder {
37                 public NoteUpdatorService getService() {
38                         return NoteUpdatorService.this;
39                 }
40         }
41
42         public static final String ACTION = "NoteUpdatorService";
43         public static final String ACTION_START = "START";
44         private EditPrefUtil pref = new EditPrefUtil(this);
45         private KitchenTimerBinder binder = new KitchenTimerBinder();
46         private String action = null;
47
48         @Override
49         public void onCreate() {
50                 super.onCreate();
51
52                 if (DEBUG) {
53                         Toast toast = Toast.makeText(getApplicationContext(), "onCreate()",
54                                         Toast.LENGTH_SHORT);
55                         toast.show();
56                 }
57         }
58
59         private Runnable task = new Runnable() {
60                 public void run() {
61                         try {
62                                 // cancelAlermTime(NoteUpdatorService.this);
63
64                                 if (action.equals(ACTION_START)) {
65                                         // 初期起動
66                                 } else {
67                                         // タイマー起動
68                                         synchronized (binder) {
69                                                 LockDao dao = (LockDao) LockDao.getInstance();
70                                                 try {
71                                                         if (!NetworkUtil
72                                                                         .isConnected(NoteUpdatorService.this)) {
73                                                                 updateDate(NoteUpdatorService.this
74                                                                                 .getString(R.string.serviceUpdateDisableNetworkMsg));
75                                                                 return;
76                                                         }
77                                                         OAuthUtil authUtil = OAuthUtil.getInstance();
78                                                         EvernoteSession session = authUtil
79                                                                         .setupSession(NoteUpdatorService.this);
80                                                         EvernoteUtil util = EvernoteUtil.getInstance();
81                                                         util.setSession(session);
82                                                         if (!util.isLoggedIn()) {
83                                                                 updateDate(NoteUpdatorService.this
84                                                                                 .getString(R.string.serviceUpdateNotLoggedkMsg));
85                                                                 return;
86                                                         }
87                                                         boolean b = dao.lock(NoteUpdatorService.this,
88                                                                         Constant.LOCK_UPDATE_NOTE);
89                                                         if (b) {
90                                                                 execute();
91                                                         } else {
92                                                                 String info = dao.getLockInfo();
93                                                                 Debug.d(this, info);
94                                                                 updateDate(NoteUpdatorService.this
95                                                                                 .getString(R.string.serviceUpdateReferenceDataMsg));
96                                                         }
97                                                 } catch (RollbackException e) {
98                                                         if (e.getError() == EfError.NETWORK) {
99                                                                 updateDate(NoteUpdatorService.this
100                                                                                 .getString(R.string.serviceUpdateDisableNetworkMsg));
101                                                         } else {
102                                                                 updateDate(NoteUpdatorService.this
103                                                                                 .getString(R.string.serviceUpdateUnexpectedErrorkMsg));
104                                                         }
105                                                 } catch (Exception e) {
106                                                         Debug.d(this, null, e);
107                                                         updateDate(NoteUpdatorService.this
108                                                                         .getString(R.string.serviceUpdateUnexpectedErrorkMsg));
109                                                 } finally {
110                                                         // ロック未取得でも解除する(ゴミ掃除)
111                                                         dao.unlock(NoteUpdatorService.this,
112                                                                         Constant.LOCK_UPDATE_NOTE);
113
114                                                         Intent intent = new Intent(Constant.ACTION_UPDATE);
115                                                         sendBroadcast(intent);
116                                                 }
117                                         }
118                                 }
119                         } finally {
120                                 setNextTime(NoteUpdatorService.this);
121                                 NoteUpdatorService.this.stopSelf();
122                         }
123                 }
124
125                 private void execute() throws EfException {
126                         pref.put(Constant.PREF_UPDATE_DATA, Constant.ON);
127                         pref.update();
128
129                         Initialize.initialize(NoteUpdatorService.this, null);
130
131                         NoteUpdateTask task = new NoteUpdateTask(null, true, true, true,
132                                         false);
133                         task.doExecute();
134
135                         updateDate(null);
136                 }
137
138         };
139
140         private void updateDate(String msg) {
141                 Calendar cal = Calendar.getInstance();
142                 String date = DateUtil.toDateString(this, cal.getTimeInMillis());
143
144                 if (msg != null) {
145                         date = date + " (" + msg + ")";
146                 }
147
148                 pref.put(Constant.PREF_UPDATE_DATETIME, date);
149                 pref.update();
150         }
151
152         @Override
153         public void onStart(Intent intent, int startId) {
154                 super.onStart(intent, startId);
155
156                 action = intent.getAction();
157                 action = (action == null) ? "" : action;
158
159                 if (DEBUG) {
160                         Toast toast = Toast.makeText(getApplicationContext(), "onStart() "
161                                         + action + " " + startId, Toast.LENGTH_SHORT);
162                         toast.show();
163                 }
164
165                 Thread thread = new Thread(null, task, "AlarmService_Service");
166                 thread.start();
167         }
168
169         @Override
170         public void onDestroy() {
171                 super.onDestroy();
172
173                 if (DEBUG) {
174                         Toast toast = Toast.makeText(getApplicationContext(),
175                                         "onDestroy()", Toast.LENGTH_SHORT);
176                         toast.show();
177                 }
178         }
179
180         @Override
181         public IBinder onBind(Intent intent) {
182                 if (DEBUG) {
183                         Toast toast = Toast.makeText(getApplicationContext(), "onBind()",
184                                         Toast.LENGTH_SHORT);
185                         toast.show();
186                 }
187
188                 return binder;
189         }
190
191         @Override
192         public void onRebind(Intent intent) {
193                 if (DEBUG) {
194                         Toast toast = Toast.makeText(getApplicationContext(), "onRebind()",
195                                         Toast.LENGTH_SHORT);
196                         toast.show();
197                 }
198         }
199
200         @Override
201         public boolean onUnbind(Intent intent) {
202                 if (DEBUG) {
203                         Toast toast = Toast.makeText(getApplicationContext(), "onUnbind()",
204                                         Toast.LENGTH_SHORT);
205                         toast.show();
206                 }
207                 return true;
208         }
209
210         public static void setNextTime(Context context) {
211                 EditPrefUtil pref = new EditPrefUtil(context);
212
213                 long updateTime = pref.getLong(Constant.PREF_UPDATE_TIME);
214                 if (updateTime <= 0) {
215                         return;
216                 }
217
218                 Calendar cal = Calendar.getInstance();
219                 // cal.add(Calendar.HOUR, (int) updateTime);
220                 cal.add(Calendar.SECOND, (int) 15); // TODO
221
222                 long t = cal.getTimeInMillis();
223                 PendingIntent alarmSender = PendingIntent.getService(context, 0,
224                                 new Intent(context, NoteUpdatorService.class), 0);
225                 AlarmManager am = (AlarmManager) context
226                                 .getSystemService(Context.ALARM_SERVICE);
227                 am.set(AlarmManager.RTC, t, alarmSender);
228
229                 pref.put(Constant.PREF_NEXT_TIME, t);
230                 pref.update();
231         }
232
233         private static void cancelAlermTime(Context context) {
234                 Calendar cal = Calendar.getInstance();
235
236                 long t = cal.getTimeInMillis();
237                 PendingIntent alarmSender = PendingIntent.getService(context, 0,
238                                 new Intent(context, NoteUpdatorService.class), 0);
239                 AlarmManager am = (AlarmManager) context
240                                 .getSystemService(Context.ALARM_SERVICE);
241                 am.cancel(alarmSender);
242         }
243
244         public static void stopService(Context context) {
245                 PendingIntent alarmSender = PendingIntent.getService(context, 0,
246                                 new Intent(context, NoteUpdatorService.class),
247                                 PendingIntent.FLAG_CANCEL_CURRENT);
248         }
249
250         public static boolean isSetAlarmSender(Context context) {
251                 PendingIntent alarmSender = PendingIntent.getService(context, 0,
252                                 new Intent(context, NoteUpdatorService.class),
253                                 PendingIntent.FLAG_NO_CREATE);
254                 return alarmSender != null;
255         }
256
257         public static void init(Context context) {
258                 EditPrefUtil pref = new EditPrefUtil(context);
259
260                 boolean isSet = NoteUpdatorService.isSetAlarmSender(context);
261                 int updateTime = pref.getInt(Constant.PREF_UPDATE_TIME);
262
263                 // サービス起動中でなく、ロックが残っている場合、削除(DB排他で、ロックされないこと)
264                 // サービスのロック削除
265                 long t = pref.getLong(Constant.PREF_NEXT_TIME);
266                 Calendar cal = Calendar.getInstance();
267                 long now = cal.getTimeInMillis();
268                 if (t < now) {
269                         isSet = false;
270
271                         // サービス起動中の場合は、DBロックがかかり
272                         // 下記の処理でLockDaoがLOCK_UPDATE_NOTEを削除させないようにするため
273                         // ダミーでisEmpty()を読んでいる
274                         NodeDao nodeDao = (NodeDao) NodeCacheDao.getInstance();
275                         nodeDao.isEmpty();
276                         
277                         // サービスが起動していない & ロックが残ってしまったので、強制的に削除
278                         LockDao lockDao = (LockDao) LockDao.getInstance();
279                         lockDao.unlock(NoteUpdatorService.class, Constant.LOCK_UPDATE_NOTE);
280                         // サービスでのロック解除のため、下記は削除しない
281                         // lockDao.unlock(NoteUpdateTask.LOCK_OBJ, Constant.LOCK_UPDATE_NOTE);
282                         //lockDao.unlock(SettingActivity.class, Constant.LOCK_UPDATE_NOTE);
283                         lockDao = null;
284                 }
285
286                 if (updateTime > 0) {
287                         if (!isSet) {
288                                 // 再起動時
289                                 setNextTime(context);
290                         }
291                 } else {
292                         if (isSet) {
293                                 // データ削除時
294                                 // isSetはクリアされないが、問題ないので毎回よぶ
295                                 stopService(context);
296                         }
297                 }
298         }
299 }