2
0
Эх сурвалжийг харах

Cleaned code, bugs fixed

Now with async POST requests!
Deben Oldert 10 жил өмнө
parent
commit
e348ccbdca

+ 7 - 17
Android app/java/com/dev/deben/implementation/GcmService.java

@@ -1,15 +1,11 @@
 /*
-Copyright 2015 Google Inc. All Rights Reserved.
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-    http://www.apache.org/licenses/LICENSE-2.0
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
+ * Feel free to copy/use it for your own project.
+ * Keep in mind that it took me several days/weeks, beers and asperines to make this.
+ * So be nice, and give me some credit, I won't bite and it won't hurt you.
+ *
+ * Created by Deben Oldert
  */
+
 package com.dev.deben.implementation;
 
 import android.os.Bundle;
@@ -20,13 +16,7 @@ import com.google.android.gms.gcm.GcmListenerService;
 import org.json.JSONException;
 
 import java.io.IOException;
-import java.util.HashMap;
-
 
-
-/**
- * Service used for receiving GCM messages. When a message is received this service will log it.
- */
 public class GcmService extends GcmListenerService {
 
     function fn = new function(this);
@@ -39,7 +29,7 @@ public class GcmService extends GcmListenerService {
         } catch (IOException | JSONException e) {
             e.printStackTrace();
         }
-        int id = fn.notifier(from, "New VPN login request");
+        int id = fn.notifier("Access control", "New VPN login request");
         SystemClock.sleep(30000);
         fn.cancelNotify(id);
     }

+ 0 - 41
Android app/java/com/dev/deben/implementation/InstanceIdService.java

@@ -1,41 +0,0 @@
-package com.dev.deben.implementation;
-
-import com.google.android.gms.gcm.GoogleCloudMessaging;
-import com.google.android.gms.iid.InstanceIDListenerService;
-import com.google.android.gms.iid.InstanceID;
-
-import org.json.JSONException;
-
-import java.io.IOException;
-import java.util.HashMap;
-import android.content.Context;
-
-/**
- * Created by Deben on 22-10-15.
- */
-public class InstanceIdService extends InstanceIDListenerService {
-    Context ctx = this;
-
-
-
-
-    function fn = new function(ctx);
-
-    public String getIid() {
-        return InstanceID.getInstance(ctx).getId().toString();
-    }
-
-    public String getToken() throws IOException {
-        return "";
-        /*String authEntity = "implementation-51b96";
-        String scope = "GCM";
-        System.out.println("GENERATING TOKEN");
-        try {
-            return InstanceID.getInstance(ctx).getToken("implementation-51b96", "GCM").toString();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-        return "";*/
-    }
-
-};

+ 71 - 50
Android app/java/com/dev/deben/implementation/LoginActivity.java

@@ -1,34 +1,45 @@
+/*
+ * Feel free to copy/use it for your own project.
+ * Keep in mind that it took me several days/weeks, beers and asperines to make this.
+ * So be nice, and give me some credit, I won't bite and it won't hurt you.
+ *
+ * Created by Deben Oldert
+ */
+
 package com.dev.deben.implementation;
 
+import android.app.ProgressDialog;
 import android.content.Intent;
+import android.graphics.Color;
 import android.net.Uri;
-import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
-import android.view.Menu;
-import android.view.MenuItem;
+import android.os.StrictMode;
+import android.support.v7.app.AppCompatActivity;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
-import android.app.ProgressDialog;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.GoogleApiAvailability;
+import com.loopj.android.http.AsyncHttpClient;
+import com.loopj.android.http.AsyncHttpResponseHandler;
 
 import org.json.JSONException;
 import org.json.simple.JSONObject;
 import org.json.simple.JSONValue;
 
 import java.io.IOException;
-import java.io.StringWriter;
 import java.util.HashMap;
-import android.os.StrictMode;
-import com.google.android.gms.common.ConnectionResult;
-import com.google.android.gms.common.GoogleApiAvailability;
+
+import cz.msebera.android.httpclient.Header;
+import cz.msebera.android.httpclient.entity.StringEntity;
 
 public class LoginActivity extends AppCompatActivity {
 
     function fn = new function(this);
-    TextView error;
+    TextView err;
     Button login;
-    String regCode;
     EditText userField;
     EditText passField;
     EditText codeField;
@@ -42,8 +53,8 @@ public class LoginActivity extends AppCompatActivity {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_login);
 
-        error = (TextView) findViewById(R.id.error);
-        error.setVisibility(View.INVISIBLE);
+        err = (TextView) findViewById(R.id.error);
+        err.setVisibility(View.INVISIBLE);
         login = (Button) findViewById(R.id.login);
         userField = (EditText) findViewById(R.id.username);
         passField = (EditText) findViewById(R.id.password);
@@ -111,28 +122,30 @@ public class LoginActivity extends AppCompatActivity {
         });
     }
 
-    private void login(String username, String password, String code) throws IOException, JSONException {
-        error.setVisibility(View.INVISIBLE);
-        error.setText("");
+    private void login(String usr, String pass, String cod) throws IOException, JSONException {
+        final String username = usr;
+        final String password = pass;
+        final String reqCode = cod;
+        final ProgressDialog progress = new ProgressDialog(this);
+        err.setVisibility(View.INVISIBLE);
+        err.setText("");
         if(username == null || username.equals("") && username.length() < 5) {
-            error.setText("Username too short");
-            error.setVisibility(View.VISIBLE);
+            err.setText("Username too short");
+            err.setVisibility(View.VISIBLE);
             return;
         }
         if(password == null || password.equals("") && password.length() < 5) {
-            error.setText("Password too short");
-            error.setVisibility(View.VISIBLE);
+            err.setText("Password too short");
+            err.setVisibility(View.VISIBLE);
             return;
         }
-        if(code == null || code.equals("") || code.length() != 4) {
-            error.setText("Invalid register code");
-            error.setVisibility(View.VISIBLE);
+        if(reqCode == null || reqCode.equals("") || reqCode.length() != 4) {
+            err.setText("Invalid register code");
+            err.setVisibility(View.VISIBLE);
             return;
         }
-
-            ProgressDialog progress = new ProgressDialog(this);
-            progress.setTitle("Registering");
-            progress.setMessage("Processing request...");
+            progress.setTitle("Registering your device");
+            progress.setMessage("Processing...");
             progress.setCancelable(false);
             progress.show();
 
@@ -147,44 +160,52 @@ public class LoginActivity extends AppCompatActivity {
             JSONObject json = new JSONObject();
             json.put("function", "register");
             json.put("requestId", fn.readSetting("requestId"));
-            json.put("registerCode", code);
+            json.put("registerCode", reqCode);
             json.put("username", username);
             json.put("password", password);
             json.put("userInfo", info);
 
-            StringWriter out = new StringWriter();
-            json.writeJSONString(out);
+        AsyncHttpClient client = new AsyncHttpClient();
 
-            String response = fn.makeRequest("GET", fn.readSetting("serverUrl"), out.toString());
-            System.out.println(response);
-            if(response.length() == 0 || response == null || response == "") {
+        client.post(this, fn.readSetting("serverUrl"), new StringEntity(json.toJSONString()), "application/json", new AsyncHttpResponseHandler() {
+            @Override
+            public void onFailure(int code, Header[] headers, byte[] responseBody, Throwable error) {
+                err.setTextColor(Color.parseColor("#ff1700"));
+                err.setText("HTTP ERROR: " + code);
+                err.setVisibility(View.VISIBLE);
                 progress.dismiss();
-                error.setText("Request Failed. Try again later");
-                error.setVisibility(View.VISIBLE);
-                return;
             }
-            else {
-                Object obj = JSONValue.parse(response);
-                JSONObject res = (JSONObject) obj;
-                if(res.get("result").equals("0") || Integer.parseInt(res.get("result").toString()) == 0) {
 
+            @Override
+            public void onSuccess(int code, Header[] headers, byte[] responseBody) {
+                String res = new String(responseBody);
+                Object obj = JSONValue.parse(res);
+                JSONObject response = (JSONObject) obj;
+
+                if (response.get("result") != null && response.get("result").equals("0") || Integer.parseInt(response.get("result").toString()) == 0) {
                     HashMap<String, String> set = new HashMap<>();
                     set.put("username", username);
                     set.put("password", password);
-                    set.put("registerCode", code);
+                    set.put("registerCode", reqCode);
                     set.put("requestId", "0");
-                    fn.writeSetting(set);
+                    try {
+                        fn.writeSetting(set);
+                    } catch (IOException | JSONException e) {
+                        e.printStackTrace();
+                    }
                     progress.dismiss();
                     fn.redirect("Main");
-                }
-                else {
+                    err.setVisibility(View.VISIBLE);
+                    progress.dismiss();
+                } else {
                     progress.dismiss();
-                    error.setText("Error "+res.get("result")+": "+res.get("resultText"));
-                    error.setVisibility(View.VISIBLE);
+                    err.setText("Error " + response.get("result") + ": " + response.get("resultText"));
+                    err.setVisibility(View.VISIBLE);
                     return;
                 }
             }
-            return;
+        });
+        return;
     }
     private boolean checkPlayServices() {
         GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
@@ -193,12 +214,12 @@ public class LoginActivity extends AppCompatActivity {
             if (apiAvailability.isUserResolvableError(resultCode)) {
                 apiAvailability.getErrorDialog(this, resultCode, 9000)
                         .show();
-                error.setText("Service must be up to date in order to use this app");
-                error.setVisibility(View.VISIBLE);
+                err.setText("Service must be up to date in order to use this app");
+                err.setVisibility(View.VISIBLE);
                 login.setEnabled(false);
             } else {
-                error.setText("Device not supported");
-                error.setVisibility(View.VISIBLE);
+                err.setText("Device not supported");
+                err.setVisibility(View.VISIBLE);
                 login.setEnabled(false);
                 finish();
             }

+ 56 - 30
Android app/java/com/dev/deben/implementation/MainActivity.java

@@ -1,34 +1,51 @@
+/*
+ * Feel free to copy/use it for your own project.
+ * Keep in mind that it took me several days/weeks, beers and asperines to make this.
+ * So be nice, and give me some credit, I won't bite and it won't hurt you.
+ *
+ * Created by Deben Oldert
+ */
+
 package com.dev.deben.implementation;
 
 import android.app.ProgressDialog;
+import android.content.Context;
 import android.graphics.Color;
-import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
+import android.support.v7.app.AppCompatActivity;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;
 
+import com.loopj.android.http.*;
+
 import org.json.JSONException;
 import org.json.simple.JSONObject;
 import org.json.simple.JSONValue;
 
 import java.io.IOException;
-import java.io.StringWriter;
+
+import cz.msebera.android.httpclient.entity.StringEntity;
+import cz.msebera.android.httpclient.Header;
 
 
 public class MainActivity extends AppCompatActivity {
 
     function fn = new function(this);
+
     public boolean active = true;
     Button accept;
     Button deny;
     TextView status;
     TextView desc;
+    Context ctx = this;
+    boolean opt;
 
     @Override
     public void onBackPressed() {
+        return;
     }
 
     @Override
@@ -92,6 +109,7 @@ public class MainActivity extends AppCompatActivity {
             @Override
             public void onClick(View v) {
                 try {
+                    opt = true;
                     buildReply(true, accept, deny);
                 } catch (JSONException | IOException e) {
                     e.printStackTrace();
@@ -103,6 +121,7 @@ public class MainActivity extends AppCompatActivity {
             @Override
             public void onClick(View v) {
                 try {
+                    opt = false;
                     buildReply(false, accept, deny);
                 } catch (JSONException | IOException e) {
                     e.printStackTrace();
@@ -135,13 +154,11 @@ public class MainActivity extends AppCompatActivity {
 
     }
 
-
-
     private void buildReply(boolean grand, Button accept, Button deny) throws JSONException, IOException {
         accept.setEnabled(false);
         deny.setEnabled(false);
 
-        ProgressDialog progress = new ProgressDialog(this);
+        final ProgressDialog progress = new ProgressDialog(this);
         progress.setTitle((grand ? "Approving" : "Cancelling") + " request");
         progress.setMessage("Processing...");
         progress.setCancelable(false);
@@ -155,34 +172,43 @@ public class MainActivity extends AppCompatActivity {
         json.put("notificationId", fn.readSetting("notificationId"));
         json.put("confirmation", grand ? "approved" : "cancelled");
 
-        StringWriter out = new StringWriter();
-        json.writeJSONString(out);
-
-        String response = fn.makeRequest("POST", fn.readSetting("serverUrl"), out.toString());
-        Object obj = JSONValue.parse(response);
-        JSONObject res = (JSONObject) obj;
-
+        AsyncHttpClient client = new AsyncHttpClient();
 
-
-        if(res.get("result").equals("0") || Integer.parseInt(res.get("result").toString()) == 0) {
-            status.setText("VPN request successfully " + (grand ? "APPROVED" : "CANCELLED"));
-            if(grand) {
-                status.setTextColor(Color.parseColor("#04ff00"));
-            }
-            else {
-                status.setTextColor(Color.parseColor("#DF7401"));
+        client.post(ctx, fn.readSetting("serverUrl"), new StringEntity(json.toJSONString()), "application/json", new AsyncHttpResponseHandler() {
+            @Override
+            public void onFailure(int code, Header[] headers, byte[] responseBody, Throwable error) {
+                status.setTextColor(Color.parseColor("#ff1700"));
+                status.setText("HTTP ERROR: " + code);
+                status.setVisibility(View.VISIBLE);
+                progress.dismiss();
             }
-            fn.writeSetting("requestId", "0");
-        }
-        else {
-            status.setText("Something went wrong, " + res.get("result").toString() + "\n" + res.get("resultText").toString());
-            status.setTextColor(Color.parseColor("#ff1700"));
-        }
-        status.setVisibility(View.VISIBLE);
-        accept.setEnabled(true);
-        deny.setEnabled(true);
 
-        progress.dismiss();
+            @Override
+            public void onSuccess(int code, Header[] headers, byte[] responseBody) {
+                String res = new String(responseBody);
+                Object obj = JSONValue.parse(res);
+                JSONObject response = (JSONObject) obj;
+
+                if (response.get("result") != null && response.get("result").equals("0") || Integer.parseInt(response.get("result").toString()) == 0) {
+                    status.setTextColor(Color.parseColor("#04ff00"));
+                    status.setText("SUCCESS");
+
+                    try {
+                        fn.writeSetting("requestId", "0");
+                    } catch (IOException | JSONException e) {
+                        e.printStackTrace();
+                    }
+                    finish();
+                    startActivity(getIntent());
+                } else {
+                    status.setText(response.get("result").toString() + "\n" + response.get("resultText").toString());
+                    status.setTextColor(Color.parseColor("#ff1700"));
+                }
+                status.setVisibility(View.VISIBLE);
+                progress.dismiss();
+                fn.cancelNotify();
+            }
+        });
     }
 
 

+ 5 - 36
Android app/java/com/dev/deben/implementation/RegisterIntentService.java

@@ -1,29 +1,16 @@
-/**
- * Copyright 2015 Google Inc. All Rights Reserved.
+/*
+ * Feel free to copy/use it for your own project.
+ * Keep in mind that it took me several days/weeks, beers and asperines to make this.
+ * So be nice, and give me some credit, I won't bite and it won't hurt you.
  *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Created by Deben Oldert
  */
 
 package com.dev.deben.implementation;
 
 import android.app.IntentService;
 import android.content.Intent;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-import android.support.v4.content.LocalBroadcastManager;
-import android.util.Log;
 
-import com.google.android.gms.gcm.GcmPubSub;
 import com.google.android.gms.gcm.GoogleCloudMessaging;
 import com.google.android.gms.iid.InstanceID;
 
@@ -45,37 +32,19 @@ public class RegisterIntentService extends IntentService {
     protected void onHandleIntent(Intent intent) {
 
         try {
-            // [START register_for_gcm]
-            // Initially this call goes out to the network to retrieve the token, subsequent calls
-            // are local.
-            // [START get_token]
             InstanceID instanceID = InstanceID.getInstance(this);
-            // R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
-            // See https://developers.google.com/cloud-messaging/android/start for details on this file.
             String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                     GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
-            // [END get_token]
-           // Log.i(TAG, "GCM Registration Token: " + token);
             System.out.println("Service creating token");
             System.out.println("Token: "+token);
 
             sendRegistrationToServer(token);
 
-            // [END register_for_gcm]
         } catch (Exception e) {
             System.out.println("Failed to complete token refresh");
         }
 
     }
-
-    /**
-     * Persist registration to third-party servers.
-     *
-     * Modify this method to associate the user's GCM registration token with any server-side account
-     * maintained by your application.
-     *
-     * @param token The new token.
-     */
     private void sendRegistrationToServer(String token) throws IOException, JSONException {
         System.out.println("REGISTERING TOKEN");
 

+ 48 - 64
Android app/java/com/dev/deben/implementation/function.java

@@ -1,50 +1,40 @@
+/*
+ * Feel free to copy/use it for your own project.
+ * Keep in mind that it took me several days/weeks, beers and asperines to make this.
+ * So be nice, and give me some credit, I won't bite and it won't hurt you.
+ *
+ * Created by Deben Oldert
+ */
+
 package com.dev.deben.implementation;
 
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.PowerManager;
+import android.provider.Settings.Secure;
+import android.support.v4.app.NotificationCompat;
+
 import org.json.JSONException;
-//import org.json.JSONObject;
-import org.json.simple.JSONValue;
 import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
 
 import java.io.BufferedReader;
+import java.io.DataOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
-import java.util.HashMap;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.content.ContextWrapper;
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-import android.widget.EditText;
-import android.widget.Toast;
 import java.io.StringWriter;
-import java.util.Map;
 import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
 import java.net.URL;
-import java.io.DataOutputStream;
-
-import android.provider.Settings.Secure;
-import com.google.android.gms.common.GoogleApiAvailability;
-import com.google.android.gms.common.ConnectionResult;
-
-import com.google.android.gms.gcm.GoogleCloudMessaging;
-import com.google.android.gms.iid.InstanceID;
-import android.support.v4.app.NotificationCompat;
-import android.app.TaskStackBuilder;
-import android.app.PendingIntent;
-import android.app.NotificationManager;
-import android.content.Context;
+import java.util.HashMap;
+import java.util.Map;
 
-/**
- * Created by Deben on 21-10-15.
- */
 public class function {
     private static Context ctx;
     private static String settings;
@@ -56,7 +46,6 @@ public class function {
 
     public boolean writeSetting(HashMap<String, String> set) throws IOException, JSONException {
         String jsonText = settingFile();
-        //System.out.println("JSON WRITE BEFORE: "+jsonText);
         if(jsonText != null) {
             Object obj = JSONValue.parse(jsonText);
             JSONObject json = (JSONObject) obj;
@@ -64,7 +53,7 @@ public class function {
                 json.put(entry.getKey(), entry.getValue());
             }
 
-            FileOutputStream fout = ctx.openFileOutput(file, ctx.MODE_PRIVATE);
+            FileOutputStream fout = ctx.openFileOutput(file, Context.MODE_PRIVATE);
             OutputStreamWriter outwr = new OutputStreamWriter(fout);
 
             StringWriter out = new StringWriter();
@@ -75,11 +64,9 @@ public class function {
 
             outwr.write(txt);
             outwr.close();
-            //System.out.println("JSON WRITE AFTER: " + txt);
             return true;
         }
         else{
-            //System.out.println("JSON WRITE NULL");
             return false;
         }
     }
@@ -90,7 +77,7 @@ public class function {
             JSONObject json = (JSONObject) obj;
             json.put(key, value);
 
-            FileOutputStream fout = ctx.openFileOutput(file, ctx.MODE_PRIVATE);
+            FileOutputStream fout = ctx.openFileOutput(file, Context.MODE_PRIVATE);
             OutputStreamWriter outwr = new OutputStreamWriter(fout);
 
             StringWriter out = new StringWriter();
@@ -109,31 +96,10 @@ public class function {
     }
     public void init() throws IOException, JSONException {
         settings = settingFile();
-        System.out.println("INIT START");
-        Object obj = JSONValue.parse(settings);
-        JSONObject json = (JSONObject) obj;
-        if(json.get("apiKey").equals("")) {
-            System.out.println("INIT CREATE");
-
-            Intent intent = new Intent(ctx, InstanceIdService.class);
-            ctx.startService(intent);
-
-            //InstanceIdService srv = new InstanceIdService();
-
-            //HashMap<String, String> set = new HashMap<>();
-            //set.put("apiKey", srv.getToken());
-
-            //System.out.println("TOKEN: "+srv.getToken());
-
-            //writeSetting(set);
-
-            settings = settingFile();
-        }
-        System.out.println("INIT STOP");
     }
 
     public String readSetting(String key) throws JSONException, IOException {
-            Object obj = JSONValue.parse(settings);
+            Object obj = JSONValue.parse((settings != null) ? settings:settingFile());
             JSONObject json = (JSONObject) obj;
             String value = null;
             if (json.get(key) != null) {
@@ -158,9 +124,8 @@ public class function {
     }
 
     private String settingFile() throws IOException, JSONException {
-        ContextWrapper cw = new ContextWrapper(ctx);
 
-        String jsonStr = null;
+        String jsonStr;
 
         System.out.println("Trying to read settings");
 
@@ -168,7 +133,7 @@ public class function {
             FileInputStream fin = ctx.openFileInput(file);
             BufferedReader rd = new BufferedReader(new InputStreamReader(fin));
             StringBuilder sb = new StringBuilder();
-            String line = null;
+            String line;
             while ((line = rd.readLine()) != null) {
                 sb.append(line);
             }
@@ -178,7 +143,7 @@ public class function {
             System.out.println("Read settings");
         }
         catch(IOException e){
-            FileOutputStream fout = ctx.openFileOutput(file, ctx.MODE_PRIVATE);
+            FileOutputStream fout = ctx.openFileOutput(file, Context.MODE_PRIVATE);
             OutputStreamWriter outwr = new OutputStreamWriter(fout);
 
             JSONObject json = new JSONObject();
@@ -201,7 +166,7 @@ public class function {
             outwr.write(jsonStr);
             outwr.close();
         }
-        System.out.println("return settings: "+jsonStr);
+        System.out.println("return settings: " + jsonStr);
         return jsonStr;
 
     }
@@ -346,6 +311,18 @@ public class function {
         System.out.println("BUILDING NOTIFICATION");
         NotificationManager nMgr = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
         PendingIntent pi = PendingIntent.getActivity(ctx, 0, new Intent(ctx, MainActivity.class), 0);
+
+        PowerManager pm = (PowerManager)ctx.getSystemService(Context.POWER_SERVICE);
+        boolean active = pm.isInteractive();
+        PowerManager.WakeLock wl;
+        if(!active) {
+            wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "NOTIFY");
+            wl.acquire(30000);
+        }
+        else {
+            redirect("Main");
+        }
+
         int id = (int)System.currentTimeMillis();
         Notification mBuilder = new NotificationCompat.Builder(ctx)
                         .setSmallIcon(R.drawable.action_logo)
@@ -353,13 +330,20 @@ public class function {
                         .setContentText(msg)
                         .setAutoCancel(true)
                         .setContentIntent(pi)
+                        .setCategory(Notification.CATEGORY_CALL)
                         .build();
+        mBuilder.defaults |= Notification.DEFAULT_VIBRATE;
+        mBuilder.defaults |= Notification.DEFAULT_SOUND;
+
         nMgr.notify(id, mBuilder);
         return id;
-
     }
     public void cancelNotify(int id) {
         NotificationManager nMgr = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
         nMgr.cancel(id);
     }
+    public void cancelNotify() {
+        NotificationManager nMgr = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
+        nMgr.cancelAll();
+    }
 }