Приложение Б. Исходный код

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.maria.testnavbar" > <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="com.google.android.maps" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCwPRFb3zxhSRw_697sXDGiHHut2xUqF9A" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <activity android:name=".Activities.MainActivity" android:label="@string/app_name" > </activity> <activity android:name=".Activities.AuthActivity" android:label="@string/app_name" > </activity> <receiver android:name=".Services.AlarmReciever" android:process=":remote" /> <receiver android:name=".Widget.NewAppWidget" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/new_app_widget_info" /> </receiver> <service android:name=".Widget.WidgetService" android:exported="false" android:permission="android.permission.BIND_REMOTEVIEWS" /> <activity android:name=".Activities.RegisterActivity" android:label="@string/title_activity_register" > </activity> <activity android:name=".Activities.Voice" android:label="ToDo" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

 

Основные методы класса DBWorker.java

 

  @Override public void onCreate(SQLiteDatabase db) { String SQL_CREATE_ENTRIES = "CREATE TABLE 'task' (" + "_id integer PRIMARY KEY AUTOINCREMENT," + "sID integer NULL," + "userID integer NOT NULL," + "checked integer NULL," + "text varchar(500) NOT NULL," + "dueDate INTEGER NULL," + "notice INTEGER NULL," + "repeatID integer NULL," + "locationNotice integer NULL, " + "lastChange INTEGER NOT NULL);"; db.execSQL(SQL_CREATE_ENTRIES);   SQL_CREATE_ENTRIES = "CREATE TABLE 'user' (" + "_id integer PRIMARY KEY AUTOINCREMENT," + "sID integer NULL," + "login varchar(100) NOT NULL," + "password varchar(100) NOT NULL," + "email varchar(100) NOT NULL," + "active integer NOT NULL," + "lastChange INTEGER NULL);"; db.execSQL(SQL_CREATE_ENTRIES);   SQL_CREATE_ENTRIES = "CREATE TABLE 'context' (" + "_id integer PRIMARY KEY AUTOINCREMENT," + "sID integer NULL," + "userID integer NOT NULL," + "title varchar(100) NOT NULL," + "lastChange INTEGER NULL);"; db.execSQL(SQL_CREATE_ENTRIES);   SQL_CREATE_ENTRIES = "CREATE TABLE 'point' (" + "_id integer PRIMARY KEY AUTOINCREMENT," + "contextID integer NULL, " + "sID integer NULL," + "description varchar(100) NOT NULL," + "lat varchar(100) NOT NULL," + "lng varchar(100) NOT NULL, " + "lastChange INTEGER NULL);"; db.execSQL(SQL_CREATE_ENTRIES);   SQL_CREATE_ENTRIES = "CREATE TABLE 'task_context'(" + "_id integer PRIMARY KEY AUTOINCREMENT," + "taskID integer NOT NULL," + "contextID integer NOT NULL)"; db.execSQL(SQL_CREATE_ENTRIES);   SQL_CREATE_ENTRIES = "CREATE TABLE 'subtask' (" + "_id integer PRIMARY KEY NOT NULL," + "sID integer NULL," + "taskID integer NOT NULL," + "text varchar(500) NOT NULL," + "lastChange INTEGER NULL)"; db.execSQL(SQL_CREATE_ENTRIES); }   @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS 'task'"); db.execSQL("DROP TABLE IF EXISTS 'user'"); db.execSQL("DROP TABLE IF EXISTS 'context'"); db.execSQL("DROP TABLE IF EXISTS 'point'"); db.execSQL("DROP TABLE IF EXISTS 'subtask'"); db.execSQL("DROP TABLE IF EXISTS 'task_context'"); onCreate(db); }   public UserContext checkUser(){ UserContext user = new UserContext(); SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM 'user' WHERE (active = '1') limit 1"; Cursor cursor = db.rawQuery(query, null); if (cursor.getCount() > 0){ cursor.moveToFirst(); user = new UserContext(); user.setID(cursor.getInt(0)); user.setsID(cursor.getInt(1)); user.setLogin(cursor.getString(2)); user.setPassword(cursor.getString(3)); user.setEmail(cursor.getString(4)); user.setActive(cursor.getInt(5)); return user; } else{ return user; } }   public UserContext authUser(String email, String pass){ UserContext user = new UserContext(); Calendar cal = Calendar.getInstance(); long curDate = cal.getTime().getTime()/1000; SQLiteDatabase db = this.getWritableDatabase(); String query = "SELECT * FROM 'user' WHERE (email = '" + email + "' and password = '"+ pass +"')"; Cursor cursor = db.rawQuery(query, null); if (cursor.getCount() > 0){ cursor.moveToFirst(); user = new UserContext(); user.setID(cursor.getInt(0)); user.setsID(cursor.getInt(1)); user.setLogin(cursor.getString(2)); user.setPassword(cursor.getString(3)); user.setEmail(cursor.getString(4)); user.setActive(cursor.getInt(5)); } db.close(); if (user.getLogin() != null) { SQLiteDatabase db1 = this.getWritableDatabase(); ContentValues newValues = new ContentValues(); newValues.put("login", user.getLogin()); newValues.put("password", user.getPassword()); newValues.put("email", user.getEmail()); newValues.put("active", 1); newValues.put("lastChange", curDate); String where = "_id =" + user.getID(); db1.update("user", newValues, where, null); db1.close(); } return user; }   public UserContext registerUser(UserContext user){ Calendar cal = Calendar.getInstance(); long curDate = cal.getTime().getTime()/1000; SQLiteDatabase db = this.getWritableDatabase(); String insertQuery = "INSERT INTO 'user' ('sID','login', 'password', 'email', 'active', 'lastChange') VALUES ('"+user.getsID()+"','" + user.getLogin() + "', '" + user.getPassword() + "', '"+user.getEmail()+"', '1', 'curDate')"; db.execSQL(insertQuery); String query = "SELECT * FROM 'user' order by _id DESC limit 1"; Cursor cursor = db.rawQuery(query, null); int id = 0; if (cursor.moveToFirst()) { do { id = cursor.getInt(0); } while (cursor.moveToNext()); } user.setID(id); db.close(); return user; }   public void Exit() { UserContext user = new UserContext(); Calendar cal = Calendar.getInstance(); long curDate = cal.getTime().getTime()/1000; SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM 'user' WHERE (active = '1') limit 1"; Cursor cursor = db.rawQuery(query, null); if (cursor.getCount() > 0){ cursor.moveToFirst(); user = new UserContext(); user.setID(cursor.getInt(0)); user.setsID(cursor.getInt(1)); user.setLogin(cursor.getString(2)); user.setPassword(cursor.getString(3)); user.setEmail(cursor.getString(4)); user.setActive(cursor.getInt(5)); } db.close(); if (user.getLogin()!=null){ SQLiteDatabase db1 = this.getWritableDatabase(); ContentValues newValues = new ContentValues(); newValues.put("login", user.getLogin()); newValues.put("password", user.getPassword()); newValues.put("email", user.getEmail()); newValues.put("active", 0); newValues.put("sID", user.getsID()); newValues.put("lastChange", curDate); String where = "_id = '"+user.getID()+"'"; db1.update("user", newValues, where, null); db1.close(); } } public int newTask(TaskContext task){ SQLiteDatabase db = this.getWritableDatabase(); long curDate = 0; if (task.getlChSec()>0){ curDate = task.getlChSec(); } else { Calendar cal = Calendar.getInstance(); curDate = cal.getTime().getTime()/1000; } Long due = null; Long notice = null; if (task.getDueDate()!=null){ due = task.getDueDate().getTime()/1000; } if (task.getNotice() != null) { notice = task.getNotice().getTime()/1000; } String insertQuery = "INSERT INTO 'task' " + "('userID', 'checked', 'text', 'dueDate', 'notice', 'repeatID', 'locationNotice', 'lastChange', 'sID') " + "VALUES " + "('" +task.getUserID() + "', " + "'" + task.getChecked() + "', " + "'" + task.getText() + "', " + "'" + due + "', " + "'" + notice + "', " + "'" + task.getRepeatID() + "', " + "'" + task.getLocationNotice() + "', " + "'" + curDate + "'," + "'" + task.getsID() + "')"; db.execSQL(insertQuery); String query = "SELECT * FROM 'task' order by _id DESC limit 1"; Cursor cursor = db.rawQuery(query, null); int id = 0 if (cursor.moveToFirst()) { do { id = cursor.getInt(0); } while (cursor.moveToNext()); } task.setID(id); db.close(); return task.getID(); } public void changeTask(TaskContext task) { SQLiteDatabase db = this.getWritableDatabase(); Calendar cal = Calendar.getInstance(); long curDate = cal.getTime().getTime()/1000; ContentValues newValues = new ContentValues(); Long due = null; Long notice = null; if (task.getDueDate()!=null){ due = task.getDueDate().getTime()/1000; } if (task.getNotice() != null) { notice = task.getNotice().getTime()/1000; } newValues.put("sID ", task.getsID()); newValues.put("userID", task.getUserID()); newValues.put("checked", task.getChecked()); newValues.put("text", task.getText()); newValues.put("dueDate", due); newValues.put("notice", notice); newValues.put("repeatID", task.getRepeatID()); newValues.put("locationNotice", task.getLocationNotice()); newValues.put("lastChange", curDate); String where = "_id =" + task.getID(); db.update("task", newValues, where, null); db.close(); }   public void deleteTask(TaskContext task) { SQLiteDatabase db = this.getWritableDatabase(); String deleteQuery = "DELETE FROM 'task' WHERE userID = '"+task.getUserID()+"' and _id = '"+task.getID()+"'"; db.execSQL(deleteQuery); db.close(); }   public TaskContext getTaskById (int id){ SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM 'task' WHERE _id = '" + id + "'"; Cursor cursor = db.rawQuery(query, null); TaskContext task = new TaskContext(); if (cursor.moveToFirst()) { do { task = new TaskContext(); task.setID(cursor.getInt(0)); task.setsID(cursor.getInt(1)); task.setUserID(cursor.getInt(2)); task.setChecked(cursor.getInt(3)); task.setText(cursor.getString(4)); Date dt = new Date(cursor.getLong(5)*1000); task.setDueDate(dt); dt = new Date(cursor.getLong(6)*1000); task.setNotice(dt); task.setRepeatID(cursor.getInt(7)); task.setLocationNotice(cursor.getInt(8)); } while (cursor.moveToNext()); } return task; } public ArrayList<TaskContext> getTasksByContext(int contextID){ ArrayList<TaskContext> tasks = new ArrayList<TaskContext>(); SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM 'task_context' WHERE contextID = '" + contextID + "'"; Cursor cursor = db.rawQuery(query, null); TaskContext task = new TaskContext(); int taskID; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(appContext); boolean done = prefs.getBoolean("done_tasks", false); String selectQuery; if (cursor.moveToFirst()) { do { taskID = cursor.getInt(1);   if (done){ task = getUncheckedTaskById(taskID); } else{ task = getTaskById(taskID); } tasks.add(task); } while (cursor.moveToNext()); } return tasks; } public ArrayList<TaskContext> getTasksWithoutContext(UserContext user){ ArrayList<TaskContext> tasks = new ArrayList<TaskContext>(); ArrayList<TaskContext> res = new ArrayList<TaskContext>(); tasks = getAllTasks(user); SQLiteDatabase db = this.getReadableDatabase(); String query; Cursor cursor; for (int i = 0; i<tasks.size(); i++){ query = "SELECT * FROM 'task_context' WHERE taskID = '"+tasks.get(i).getID()+"'"; cursor = db.rawQuery(query, null); if (!cursor.moveToFirst()) { res.add(tasks.get(i)); } } return res; } public void addSubTask(SubtaskContext subtask){ Calendar cal = Calendar.getInstance(); long curDate = cal.getTime().getTime()/1000; SQLiteDatabase db = this.getWritableDatabase(); String insertQuery = "INSERT INTO 'subtask' " + "('taskID', 'text', 'lastChange') " + "VALUES " + "('" +subtask.getTaskID() + "', " + "'" + subtask.getText() + "', " + "'" + curDate + "')"; db.execSQL(insertQuery); db.close(); }   public void removeSubTaskByID(int id){ SQLiteDatabase db = this.getWritableDatabase(); String deleteQuery = "DELETE FROM 'subtask' WHERE _id = '"+id+"'"; db.execSQL(deleteQuery); db.close(); } public int addContext(ContextContext cnt){ SQLiteDatabase db = this.getWritableDatabase(); long curDate; if (cnt.getlChSec()>0) { curDate = cnt.getlChSec(); } else { Calendar cal = Calendar.getInstance(); curDate = cal.getTime().getTime() / 1000; } String insertQuery = "INSERT INTO 'context' " + "('userID', 'title', 'sID', 'lastChange') " + "VALUES " + "('" + cnt.getUserID() + "'," + "'" + cnt.getTitle() +"'," + "'" + cnt.getsID() + "'," + "'"+curDate+"')"; db.execSQL(insertQuery); String query = "SELECT * FROM 'context' order by _id DESC limit 1"; Cursor cursor = db.rawQuery(query, null); int id = 0; if (cursor.moveToFirst()) { do { id = cursor.getInt(0); } while (cursor.moveToNext()); } db.close(); return id; } public int addPoint(PointContext point){ SQLiteDatabase db = this.getWritableDatabase(); Calendar cal = Calendar.getInstance(); long curDate = cal.getTime().getTime()/1000; String insertQuery = "INSERT INTO 'point' " + "('description', 'lat', 'lng', 'contextID', 'sID', 'lastChange') " + "VALUES " + "('" + point.getDescription() + "'," + "'" + point.getLat() + "', " + "'" + point.getLng() + "', " + "'" + point.getContextID() + "', " + "'" + point.getsID() + "'," + "'"+curDate+"')"; db.execSQL(insertQuery); String query = "SELECT * FROM 'point' order by _id DESC limit 1"; Cursor cursor = db.rawQuery(query, null); int id = 0; if (cursor.moveToFirst()) { do { id = cursor.getInt(0); } while (cursor.moveToNext()); } db.close(); return id; }   public PointContext getPointByID(int id){ SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM 'point' WHERE _id = '" + id + "'"; Cursor cursor = db.rawQuery(query, null); PointContext point = new PointContext(); if (cursor.moveToFirst()) { do { point = new PointContext(); point.setID(cursor.getInt(0)); point.setContextID(cursor.getInt(1)); point.setsID(cursor.getInt(2)); point.setDescription(cursor.getString(3)); point.setLat(cursor.getString(4)); point.setLng(cursor.getString(5)); } while (cursor.moveToNext()); } db.close(); return point; }   public void removePoint(int id){ SQLiteDatabase db = this.getWritableDatabase(); PointContext point = getPointByID(id); String deleteQuery = "DELETE FROM 'point' WHERE _id = '"+id+"'"; db.execSQL(deleteQuery); db.close(); }   public ArrayList<PointContext> getPointsByContextID(int id){ SQLiteDatabase db = this.getWritableDatabase(); ArrayList<PointContext> points = new ArrayList<PointContext>(); String selectQuery = "SELECT * FROM point where contextID = '"+id+"'"; Cursor cursor = db.rawQuery(selectQuery, null); PointContext point; if (cursor.moveToFirst()) { do { point = new PointContext(); point.setID(cursor.getInt(0)); point.setsID(cursor.getInt(2)); point.setContextID(cursor.getInt(1)); point.setDescription(cursor.getString(3)); point.setLat(cursor.getString(4)); point.setLng(cursor.getString(5)); points.add(point); } while (cursor.moveToNext()); } db.close(); return points; }

 

Класс AsyncRequest.java

public class AsyncRequest extends AsyncTask<RequestContext, Void, ResponseContext> {   Context context;   public AsyncRequest(Context context) { super(); this.context = context; }   @Override protected void onPreExecute() { super.onPreExecute(); }   @Override protected ResponseContext doInBackground(RequestContext... request) {   ResponseContext resp = new ResponseContext(); JSONObject obj; DefaultHttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); HttpResponse response = null; StringEntity se; client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); String credentials = request[0].getLogin() + ":" + request[0].getPass(); String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); int status = -1; try { switch (request[0].getMethod()){ case "GET": HttpGet get = new HttpGet(request[0].getUrl()); get.addHeader("Authorization", "Basic " + base64EncodedCredentials); response = client.execute(get); break; case "POST": HttpPost post = new HttpPost(request[0].getUrl()); se = new StringEntity( request[0].getJsonData().toString(), "UTF-8"); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8")); post.addHeader("Authorization", "Basic " + base64EncodedCredentials); post.addHeader("Content-Encoding", HTTP.UTF_8); post.setEntity(se); response = client.execute(post); break; case "PUT": HttpPut put = new HttpPut(request[0].getUrl()); se = new StringEntity( request[0].getJsonData().toString(), "UTF-8"); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8")); put.addHeader("Authorization", "Basic " + base64EncodedCredentials); put.addHeader("Content-Encoding", HTTP.UTF_8); put.setEntity(se); response = client.execute(put); break; case "DELETE": MyDelete delete = new MyDelete(request[0].getUrl()); se = new StringEntity( request[0].getJsonData().toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); delete.addHeader("Authorization", "Basic " + base64EncodedCredentials); delete.setEntity(se); response = client.execute(delete); break; default: break; }   if(response!=null){ status = response.getStatusLine().getStatusCode(); resp.setResponseCode(status); is = response.getEntity().getContent(); }   obj = readStream(is); resp.setResponse(obj); return resp; } catch(Exception e) { Log.e("NewError!", e.toString()); return resp; } }   @Override protected void onPostExecute(ResponseContext jsonData) { } }

 

Основные методы класса WebWorker.java

  public UserContext registerUser(String email, String login, String pass) { UserContext newUser = new UserContext(); try { JSONObject json = new JSONObject(); json.put("name", login); json.put("email", email); json.put("password", pass); RequestContext request = new RequestContext(); request.setMethod("POST"); request.setJsonData(json); request.setUrl("http://irinn.us/api/v1.0/user/"); AsyncRequest async = new AsyncRequest(cnt); async.execute(request); ResponseContext response = async.get();   switch (response.getResponseCode()) { case -1: //Toast.makeText(cnt, "Ошибка с запросом", Toast.LENGTH_LONG).show(); break; case 201: newUser = getToken(pass, email); break; case 405: // Toast.makeText(cnt, "Пользователь с таким email уже существует", Toast.LENGTH_LONG).show(); break; case 400: //Toast.makeText(cnt, "Вообще ничего не отправилось(", Toast.LENGTH_LONG).show(); break; default: //Toast.makeText(cnt, "Вообще не понятно, что вернулось с сервера", Toast.LENGTH_LONG).show(); break; } } catch (JSONException e) { Log.d("Error JSONException: ", e.toString()); } catch (InterruptedException e) { Log.d("Error InterruptedExc: ", e.toString()); } catch (ExecutionException e) { Log.d("Error ExecutionExc: ", e.toString()); } return newUser; } boolean ret = false; try { Calendar cal = Calendar.getInstance(); Date curDate = cal.getTime(); RequestContext request = new RequestContext(); JSONObject json = new JSONObject(); json.put("checked", task.getChecked()); if (task.getDueDate() != null) { json.put("due_date", task.getDueDate().getTime() / 1000); } else { json.put("due_date", 0); } json.put("last_change", curDate.getTime() / 1000); json.put("notice", task.getNotice()); json.put("location_notice", task.getLocationNotice()); json.put("repeat_id", task.getRepeatID()); json.put("text", task.getText()); json.put("contexts", scID); request.setMethod("PUT"); request.setUrl("http://irinn.us/api/v1.0/tasks/" + task.getsID()); request.setJsonData(json); request.setLogin(user.getEmail()); request.setPass(user.getPassword()); AsyncRequest async = new AsyncRequest (cnt); async.execute(request); ResponseContext response = async.get();   switch (response.getResponseCode()) { case 200: ret = true; break; } } catch (JSONException ex) { Log.e("ERROR", ex.toString()); } catch (ExecutionException ex) { Log.e("ERROR", ex.toString()); } catch (InterruptedException ex) { Log.e("ERROR", ex.toString()); } return ret; }   public void makeFullSync(UserContext user) { DBWorker db = new DBWorker(cnt); try { RequestContext request = new RequestContext(); request.setLogin(user.getEmail()); request.setPass(user.getPassword()); request.setMethod("GET"); request.setUrl("http://irinn.us/api/v1.0/contexts/"); AsyncRequest async = new AsyncRequest (cnt); async.execute(request); ResponseContext response = async.get();   switch (response.getResponseCode()) { case 200: JSONArray contexts = response.getResponse().getJSONArray("contexts"); for (int i = 0; i < contexts.length(); i++) { JSONObject context = contexts.getJSONObject(i); JSONArray pointsIDs = context.getJSONArray("points");   ContextContext contextDB = new ContextContext(); contextDB.setUserID(user.getID()); contextDB.setTitle(context.getString("title")); contextDB.setsID(context.getInt("id")); contextDB.setlChSec(context.getInt("last_change"));   int newCNTID = db.addContext(contextDB);   for (int k = 0; k < pointsIDs.length(); k++) {   int id = pointsIDs.getInt(k); getPointByServerID(user, id, newCNTID); } } break; } request = new RequestContext(); request.setLogin(user.getEmail()); request.setPass(user.getPassword()); request.setMethod("GET"); request.setUrl("http://irinn.us/api/v1.0/tasks/"); async = new AsyncRequest (cnt); async.execute(request); response = async.get(); switch (response.getResponseCode()) { case 200: JSONArray tasks = response.getResponse().getJSONArray("tasks"); for (int i = 0; i < tasks.length(); i++) { JSONObject task = tasks.getJSONObject(i); String t = task.getString("subtask"); JSONArray subIDs = null; if (t != "null") subIDs = task.getJSONArray("subtask"); t = task.getString("contexts"); JSONArray t_cnt = null; if (t != "null") t_cnt = task.getJSONArray("contexts"); TaskContext taskDB = new TaskContext(); taskDB.setUserID(user.getID()); taskDB.setsID(task.getInt("id")); taskDB.setLastChange(new Date(task.getInt("last_change") * 1000)); taskDB.setChecked(task.getInt("checked")); taskDB.setDueDate(new Date((long) task.getInt("due_date") * 1000)); taskDB.setNotice(new Date((long) task.getInt("notice") * 1000)); taskDB.setRepeatID(task.getInt("repeat_id")); taskDB.setText(task.getString("text")); taskDB.setLocationNotice(task.getInt("location_notice")); int newTaskID = db.newTask(taskDB); if (subIDs != null) { for (int k = 0; k < subIDs.length(); k++) { int id = subIDs.getInt(k); getSubTaskByServerID(user, id, newTaskID); } } if (t_cnt != null) { for (int l = 0; l < t_cnt.length(); l++) { int id = t_cnt.getInt(l); db.saveTaskContextFromServer(newTaskID, id); } } } break; } } catch (JSONException ex) { Log.e("ERROR", ex.toString()); } catch (ExecutionException ex) { Log.e("ERROR", ex.toString()); } catch (InterruptedException ex) { Log.e("ERROR", ex.toString()); } String now = Long.toString(Calendar.getInstance().getTimeInMillis() / 1000); int nnow = Integer.parseInt(now); SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("sync", nnow); editor.apply(); }   public void makeSync(UserContext user) {   if (hasInternetConnection()) { String APP_PREFERENCES_COUNTER = "sync"; SharedPreferences mSettings = cnt.getSharedPreferences("mysettings", Context.MODE_PRIVATE); int sync = mSettings.getInt("sync", 0); if (sync == 0) { makeFullSync(user); } else { syncContexts(user, sync); syncTasks(user, sync); String now = Long.toString(Calendar.getInstance().getTimeInMillis() / 1000); int nnow = Integer.parseInt(now); SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("sync", nnow); editor.apply(); } } }   public void syncContexts(UserContext user, int lastSync) { DBWorker db = new DBWorker(cnt); try { RequestContext request = new RequestContext(); request.setLogin(user.getEmail()); request.setPass(user.getPassword()); request.setMethod("GET"); request.setUrl("http://irinn.us/api/v1.0/contexts/sync/" + lastSync); AsyncRequest async = new AsyncRequest (cnt); async.execute(request); ResponseContext response = async.get(); switch (response.getResponseCode()) { case 200: JSONArray contexts = response.getResponse().getJSONArray("contexts"); for (int i = 0; i < contexts.length(); i++) { JSONObject context = contexts.getJSONObject(i); JSONArray pointsIDs = context.getJSONArray("points"); ContextContext contextDB = new ContextContext(); contextDB.setUserID(user.getID()); contextDB.setTitle(context.getString("title")); contextDB.setsID(context.getInt("id")); contextDB.setlChSec(context.getInt("last_change")); ContextContext DBCheck = db.getContextLastChangeFromSID(contextDB); if (DBCheck.getlChSec() == 0) { int id = db.addContext(contextDB); contextDB.setID(id); for (int k = 0; k < pointsIDs.length(); k++) { int pID = pointsIDs.getInt(k); getPointByServerID(user, pID, id); } } else if (DBCheck.getlChSec() < contextDB.getlChSec()) { db.updateContextFromServer(contextDB); db.removeAllContextPoints(DBCheck.getID()); for (int k = 0; k < pointsIDs.length(); k++) { int pID = pointsIDs.getInt(k); getPointByServerID(user, pID, DBCheck.getID()); } } else { updateContext(contextDB, user); for (int k = 0; k < pointsIDs.length(); k++) { int pID = pointsIDs.getInt(k); PointContext pnt = new PointContext(); pnt.setsID(pID); deletePoint(pnt, user); } ArrayList<PointContext> pnts = db.getPointsByContextID(DBCheck.getID()); for (int k = 0; k < pnts.size(); k++) { addPoint(pnts.get(k), DBCheck, user); } } } break; } } catch (JSONException ex) { Log.e("ERROR", ex.toString()); } catch (ExecutionException ex) { Log.e("ERROR", ex.toString()); } catch (InterruptedException ex) { Log.e("ERROR", ex.toString()); } ArrayList<ContextContext> newLocalCont = db.getAllUnsyncContexts(user); if (newLocalCont.size() > 0) { for (int i = 0; i < newLocalCont.size(); i++) { ContextContext scont = addContext(newLocalCont.get(i).getTitle(), user); db.updateContext(scont); ArrayList<PointContext> newLocalPoints = db.getPointsByContextID(newLocalCont.get(i).getID()); for (int k = 0; k < newLocalPoints.size(); k++) { PointContext nPoint = addPoint(newLocalPoints.get(k), scont, user); db.updatePoint(nPoint); } } } }   public void syncTasks(UserContext user, int lastSync) { DBWorker db = new DBWorker(cnt); try { RequestContext request = new RequestContext(); request.setLogin(user.getEmail()); request.setPass(user.getPassword()); request.setMethod("GET"); request.setUrl("http://irinn.us/api/v1.0/tasks/sync/" + lastSync); AsyncRequest async = new AsyncRequest (cnt); async.execute(request); ResponseContext response = async.get(); switch (response.getResponseCode()) { case 200: JSONArray tasks = response.getResponse().getJSONArray("tasks"); for (int i = 0; i < tasks.length(); i++) { JSONObject task = tasks.getJSONObject(i); String t = task.getString("subtask"); JSONArray subIDs = null; if (t != "null") subIDs = task.getJSONArray("subtask"); t = task.getString("contexts"); JSONArray t_cnt = null; if (t != "null") t_cnt = task.getJSONArray("contexts"); TaskContext taskDB = new TaskContext(); taskDB.setUserID(user.getID()); taskDB.setsID(task.getInt("id")); taskDB.setlChSec(task.getInt("last_change")); taskDB.setChecked(task.getInt("checked")); taskDB.setDueDate(new Date((long) task.getInt("due_date") * 1000)); taskDB.setNotice(new Date((long) task.getInt("notice") * 1000)); taskDB.setRepeatID(task.getInt("repeat_id")); taskDB.setText(task.getString("text")); taskDB.setLocationNotice(task.getInt("location_notice")); TaskContext DBCheck = db.getTaskLastChangeFromSID(taskDB); if (DBCheck.getlChSec() == 0) { int id = db.newTask(taskDB); taskDB.setID(id); if (subIDs != null) { for (int k = 0; k < subIDs.length(); k++) { int pID = subIDs.getInt(k); getSubTaskByServerID(user, pID, id); } } if (t_cnt != null) { for (int l = 0; l < t_cnt.length(); l++) { int rid = t_cnt.getInt(l); db.saveTaskContextFromServer(id, rid); } } } else if (DBCheck.getlChSec() < taskDB.getlChSec()) { db.updateTaskFromServer(taskDB); db.removeAllSubtasks(DBCheck.getID()); if (subIDs != null) { for (int k = 0; k < subIDs.length(); k++) { int subID = subIDs.getInt(k); getSubTaskByServerID(user, subID, DBCheck.getID()); } } for (int l = 0; l < t_cnt.length(); l++) { int id = t_cnt.getInt(l); db.saveTaskContextFromServer(DBCheck.getID(), id); } } else { String cnts = db.getTaskContextServerIDs(DBCheck, user); updateTask(DBCheck, user, cnts); if (subIDs != null) { for (int k = 0; k < subIDs.length(); k++) { int pID = subIDs.getInt(k); SubtaskContext pnt = new SubtaskContext(); pnt.setsID(pID); deleteSubTask(pnt, user); } } ArrayList<SubtaskContext> pnts = db.getSubTaskListByTaskID(DBCheck.getID()); for (int k = 0; k < pnts.size(); k++) { addSubTask(pnts.get(k), user, DBCheck.getsID()); } } } break; } } catch (JSONException ex) { Log.e("ERROR", ex.toString()); } catch (ExecutionException ex) { Log.e("ERROR", ex.toString()); } catch (InterruptedException ex) { Log.e("ERROR", ex.toString()); } ArrayList<TaskContext> newLocalTasks = db.getAllUnsyncTask(user); if (newLocalTasks.size() > 0) { for (int i = 0; i < newLocalTasks.size(); i++) { String cnts = db.getTaskContextServerIDs(newLocalTasks.get(i), user); int tsID = addTask(newLocalTasks.get(i), user, cnts); db.changeTask(newLocalTasks.get(i)); ArrayList<SubtaskContext> pnts = db.getSubTaskListByTaskID(newLocalTasks.get(i).getID()); for (int k = 0; k < pnts.size(); k++) { addSubTask(pnts.get(k), user, newLocalTasks.get(i).getsID()); } } }   }     public boolean hasInternetConnection() { ConnectivityManager cm = (ConnectivityManager) cnt.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { return false; } NetworkInfo[] netInfo = cm.getAllNetworkInfo(); if (netInfo == null) { return false; } for (NetworkInfo ni : netInfo) { if (ni.getTypeName().equalsIgnoreCase("WIFI")) if (ni.isConnected()) { Log.d(this.toString(), "test: wifi conncetion found"); return true; } if (ni.getTypeName().equalsIgnoreCase("MOBILE")) if (ni.isConnected()) { Log.d(this.toString(), "test: mobile connection found"); return true; } } return false; }    

 

Класс ContextNotify.java

public class ContextNotify {   Context cnt; Double curLatitude; Double curLongtitude; SimpleLocation location; DBWorker db; UserContext user;   ContextContext curContext; int curContextID;   public static final String APP_PREFERENCES = "mysettings"; public static final String APP_PREFERENCES_VAR = "curContext"; private SharedPreferences mSettings;   private static final int NOTIFICATION_ID = 1000;   public ContextNotify(Context context){ this.cnt = context; location = new SimpleLocation(cnt); db = new DBWorker(cnt); mSettings = cnt.getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE); user = db.checkUser();   }   public String CheckContext(){   if (!location.hasLocationEnabled()) { SimpleLocation.openSettings(cnt); } String n = null; curLatitude = location.getLatitude(); curLongtitude = location.getLongitude(); ArrayList<PointContext> points = new ArrayList<PointContext>(); points = db.getAllPoints(); for (int i=0; i<points.size(); i++){ Double distance = location.calculateDistance(curLatitude, curLongtitude, Double.parseDouble(points.get(i).getLat()), Double.parseDouble(points.get(i).getLng())); if (distance < 250){ curContextID = points.get(i).getContextID(); curContext = db.getContextByID(curContextID); if (curContext.getUserID() == user.getID()){ break; } else { curContextID = 0; } } }   int setCnt = mSettings.getInt(APP_PREFERENCES_VAR, 0); if (curContextID > 0 && setCnt > 0 && curContextID!=setCnt){ n = createNotify(); SharedPreferences.Editor editor = mSettings.edit(); editor.putInt(APP_PREFERENCES_VAR, curContextID); editor.apply(); } else if (curContextID > 0 && setCnt == 0){ n = createNotify(); SharedPreferences.Editor editor = mSettings.edit(); editor.putInt(APP_PREFERENCES_VAR, curContextID); editor.apply(); } else if (curContextID==setCnt){   } else { SharedPreferences.Editor editor = mSettings.edit(); editor.putInt(APP_PREFERENCES_VAR, 0); editor.apply(); } if (n!=null) return n; else return null; }   public String createNotify() { if (curContextID > 0) { String remTitle = ""; ArrayList<TaskContext> taskList = db.getNotifyTasksByContext(curContextID); if (taskList.size() == 1) { remTitle = taskList.get(0).getText(); } else { if (taskList.size() > 0) { for (int i = 0; i < taskList.size(); i++) { if (i != 0) remTitle += "; "; remTitle += taskList.get(i).getText(); } } } if (remTitle.length()>0){ Intent notificationIntent = new Intent(cnt, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(cnt,0, notificationIntent,PendingIntent.FLAG_CANCEL_CURRENT); Notification.Builder builder = new Notification.Builder(cnt); Resources res = cnt.getResources(); builder.setContentIntent(contentIntent) .setSmallIcon(R.mipmap.ic_action_about) .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_action_event)) .setTicker("ToDO!") .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(curContext.getTitle()); builder.setContentText(remTitle); Notification notification = builder.build(); long[] vibrate = new long[]{1000, 1000}; notification.ledARGB = Color.GREEN; notification.ledOffMS = 0; notification.ledOnMS = 1; notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;   NotificationManager notificationManager = (NotificationManager) cnt.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notification);   } } return null; }   }

 

AlarmReceiver.java

public class AlarmReciever extends BroadcastReceiver { DBWorker db; private static final int NOTIFY_ID = 101; @Override public void onReceive(Context context, Intent intent) { try { Integer taskID = Integer.parseInt(intent.getAction()); db = new DBWorker(context); TaskContext task = db.getTaskById(taskID); Intent notificationIntent = new Intent(context, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); Resources res = context.getResources(); Notification.Builder builder = new Notification.Builder(context); builder.setContentIntent(contentIntent) .setSmallIcon(R.mipmap.ic_action_about) .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_action_event)) .setTicker("ToDO!") .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle("Напоминание") .setContentText(task.getText()); Notification notification = builder.build(); long[] vibrate = new long[]{1000, 1000}; notification.vibrate = vibrate; notification.ledARGB = Color.GREEN; notification.ledOffMS = 0; notification.ledOnMS = 1; notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS;   NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFY_ID, notification); } catch (NumberFormatException e){ Log.d("Error", e.toString()); } } }

 

 


 

“______” ________________ 20__ г.

 

Последний лист дипломного проекта

 

Дипломный проект выполнен мною самостоятельно. Использованные в работе материалы из опубликованной научной, учебной литературы и Интернет имеют ссылки на них.

 

 

Отпечатано в 2 экземплярах.

Библиография 27 наименования.

Один экземпляр сдан на кафедру.

 

 

Маликова Мария Александровна

 

Дата

 

 

[Е1]В современных условиях возникает проблема: эффективного распределения времени.

[Е2]

[Е3]Ежедневное планирование необходимо для эффективного управления временем.

[I4]В Ведении также должны быть прописаны: Объект исследования, предмет исследования, задание работы, методологические, теоритические и информационные основы исследования.

 

[I5]Глава 1. Образ и анализ задач контекстно-ориентированного планирования.

[I6]Важной функцией данного приложения является напоминание.

[I7]Планирование помогает определить поаледовательность выполнения задач и их согласованность между собой.

[I8]Составляя планы, человек ставит перед собой задачи.

[I9]цели

[I10]по разделам

[I11]На карте представлены контексты. Например,

[I12]Повтор предложения.

[I13]Для пользователя сервиса Google, приложение станет очень удобным и полезным.

[I14]Кнопки «Сегодня», «завтра», «Через неделю» помогут назначить время и сроки выпонения поставленой цели.

[I15]По задумке создателей, он подходит исключительно для членов семьи.

[I16]планы

[I17]Новое предложение

[I18]Если необходимо создать напоминание, то пользователь может воспользоваться будильником, таймерои или стикирами.

[I19]На данной диаграмме представлены основные операции, осуществляемые пользователем. Они реализуются в следующей последовательности:

1. фиксция задачи в текстовом виде с помощью блокнота или текстового редактора;

2. создание напоминания с использованием блокнота или стикеров, а также выходные данные каждой операции и элементы управления.

 

[I20]Рис. 2 Уровень модели – диаграмма декомпозиции IFDEF0 [I20]

 

[I21]На рис. 3. Изображен [I21] порядок операций. Они еобходимы для фиксации задач в текстовом виде.

[I22]Пропущена запятая

[I23]Глава 2. Проектирование системы контекстно-ориентированного планирования задач.

[I24]Информационной системы (в дальнейшем будет использоваться ИС )

[I25]В ввиде иерархичной структуры

[I26]Пропущенна запятая после слово диаграмма

[I27]работы