Saturday, April 18, 2015

How to Create an Android Trial App That Expires After a Fixed Period — 3 Methods

When we start to develop any commercial android application, we may need to develop a trial application which runs on the user's device for a specific time and forces the user to buy the application to use it further.

Below are three techniques you can use to implement a time-limited trial in an Android app, with pros and cons for each.

1) Save first-run timestamp locally (easiest)

When the user runs the application for the first time, save the current date and time to SharedPreferences, a file, or the app database. Every time the app starts, compare the current date/time with the saved first-run timestamp to determine whether the trial period has expired. If it has, call finish() or otherwise prevent further use.

Pros:

  • Very easy to implement.

Cons:

  • Easily broken by uninstalling and reinstalling the app (which clears the app data), or by manipulating the device clock.

2) Hard-coded end date (simple, but flawed)

Hard-code a single end date for the trial in the application. All users stop being able to use the trial after that date.

Pros:

  • Easy to implement.

Cons:

  • Can be bypassed by changing the device date/time.
  • All users share the same end date (not individualized).

3) Server-validated device registration (recommended, most robust)

This approach requires a server and a database. Whenever the app starts, the device sends a unique device identifier to your server. The server checks whether there is already an entry for that device; if not, it creates one with the current date/time as the trial start. On each app start the server evaluates whether the trial period has expired and communicates the result back to the app.

Notes and links:

Pros:

  • Much harder for users to bypass (uninstall/reinstall and device clock changes do not reset server records).

Cons:

  • Requires extra infrastructure (server + database) and careful handling of identifiers and privacy.

Where to do the check in your app

Do the trial expiration check in the onCreate() of your main Activity. If the trial has expired, show an AlertDialog that points the user to the full/commercial version on Google Play and then call finish() when the user confirms.

Useful links:

Example flow (high level, keep this as guidance rather than exact code):

  • App starts -> collect device identifier -> POST to server endpoint -> server replies {"expired":true/false} -> if expired show dialog and call finish().

Security and privacy considerations (brief)

  • Be careful with device identifiers and permissions. Some identifier APIs require runtime permissions or are deprecated on newer Android releases; review current Android docs before choosing an identifier.
  • Document how you store and use device identifiers in your privacy policy.

Closing

Third approach is the most robust and is the recommended way to implement a trial application that cannot be easily broken. It requires more effort (server + database) but provides the best protection for commercial apps.

Happy coding.

Thursday, April 16, 2015

Android: Upload Image + Form Parameters to PHP Server (multipart/form-data)

In any applications if you are working with a client server application, there is a high probability of syncing the images with some parameters to the server.

We have seen lot of examples to sync the text or parameters to the server and also the image or audio or video or any files to the server. You see these examples separately to send these data. But not the combined data to the server.

Now, in this blog we are going to learn how we are going to send the image and some parameters together to the server. Here the client is an android application and the server is apache with php and mysql (database).

We can consider the example of a register screen in the android application. Here I am not going to talk about the server set up, PHP and mysql configuration. It is assumed that the server setup and the PHP/Mysql configuration is done, up and running. Data base related to the registration parameters also ready. I am going to consider the First Name, Last Name, Address, Mobile Number, Email, Gender and image of the candidate to be registered.

These data is captured from the mobile and sent to the server via PHP web service. Here I am discuss about the code written from the client side. I am going to write that in a method "postdata". It is assumed that we know the web service URL of the server to send the data.

define:

public final String Web_URL = "http://xxxx.com/xxxx_reg.php";

Example client-side method (original example)

The following is the client-side method as used in this example. It demonstrates creating a multipart request containing one file and several text form fields, sending it to the server and reading the server response.

@Override
public String postdata() {
    // Create a new HttpClient and Post Header
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Web_URL);
        HttpContext localContext = new BasicHttpContext();

        /* Create a object for Mutipart Entity to send the data together */
        MultipartEntity multipartEntity = new MultipartEntity();
        String path = "image_path"; // user has to enter his image path where the captured image is stored
        File sourceFile = new File(path);
        FileBody bin1 = new FileBody(sourceFile);

        multipartEntity.addPart("uploaded_file", bin1);
        multipartEntity.addPart("fName", "Jose");
        multipartEntity.addPart("lName", "Pareria");
        multipartEntity.addPart("address", "#999, 2nd Main, 10th Block, Koramangala, Bangalore-10");
        multipartEntity.addPart("mobile", "+919999999999");
        multipartEntity.addPart("email", "abc@xyz.com");
        multipartEntity.addPart("gender", "Male");

        // Setting the Entity and executing
        httppost.setEntity(multipartEntity);
        HttpResponse response = httpclient.execute(httppost, localContext);

        // Getting the Response from the server
        BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }
        String getData = builder.toString();
        System.out.println(" data  " + getData);

    } catch (ClientProtocolException e) {
        Log.w("Network Error", e.toString());
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.w("IO Exception", e.toString());
    }
    return "";
}

How it works

  • The client prepares a multipart/form-data POST request. One part is a file part named "uploaded_file" containing the image file. The other parts are text form fields (fName, lName, address, mobile, email, gender).
  • The request is sent to the PHP endpoint (WebURL). The server-side script should read the file from $FILES['uploadedfile'] and the parameters from $POST.
  • The client reads the server response stream and prints it to system output.

Important implementation notes and what the code does NOT cover

  • Field names used in the request: uploaded_file, fName, lName, address, mobile, email, gender. The server must use the same names to access values.
  • The example assumes a literal "image_path" string; in a real app replace that with the actual path returned by the camera/gallery intent or a scaled/cached file.
  • The code reads the response as UTF-8 and collects it into a string (getData).

Notes for modern Android (required updates)

This article and code were written using APIs common in older Android versions. Concretely:

  • Apache HttpClient (DefaultHttpClient, HttpPost) and org.apache.http.entity.mime.MultipartEntity are deprecated and were removed from the Android SDK in newer platform releases. If your app targets modern Android versions, this code may not compile or run.

  • Use one of these modern approaches for production apps:

  • OkHttp (okhttp3) with MultipartBody for multipart uploads.

  • Retrofit (built on OkHttp) with @Multipart and @Part annotations.

  • HttpURLConnection for a lower-level standard-library approach.

  • Additional practical requirements (add these before using this code in a real app):

  • Use HTTPS (TLS) instead of HTTP to protect credentials and files in transit.

  • Request runtime permissions (READEXTERNALSTORAGE / WRITEEXTERNALSTORAGE or use scoped storage APIs) and camera permission if capturing images.

  • Scale or compress images before upload to avoid out-of-memory errors and reduce upload time.

  • Perform network calls off the UI thread (AsyncTask is deprecated — prefer executors, Kotlin coroutines, or Retrofit callbacks).

  • Add proper error handling: check HTTP response codes, server error messages, and timeouts.

  • Sanitize and validate data on the server side; restrict accepted file types and file sizes.

Suggested server-side expectations (what PHP should handle)

  • The PHP endpoint should expect a multipart/form-data POST with these keys:

  • $FILES['uploadedfile'] — the uploaded image file

  • $POST['fName'], $POST['lName'], $POST['address'], $POST['mobile'], $POST['email'], $POST['gender'] — the text fields

  • The server should:

  • Validate the uploaded file (MIME type, extension) and size.

  • Move the uploaded file to a safe directory (moveuploadedfile).

  • Insert form fields and the saved file path into the database as needed.

  • Return a clear JSON response indicating success or failure so the client can parse it.

Troubleshooting and testing

  • To inspect what the client sends, test against a known working PHP endpoint or use an HTTP inspector (Charles/mitmproxy) with HTTPS properly configured.
  • Log server-side errors and echo JSON with error messages for easier debugging.

That's it. Try it out. Happy coding.

Wednesday, April 15, 2015

Android: Hide Soft Keyboard by Tapping Outside an EditText

There is the difference in the Keypad behavior between Android and iOS. When a user taps an EditText, the soft keyboard appears. On Android you normally have to press "Done"/"Next" on the keyboard or the device Back button to hide it. On iOS you can often tap anywhere outside the input to dismiss the keyboard — this post shows how to replicate that behavior on Android.

TL;DR

Override dispatchTouchEvent in your Activity and hide the keyboard when the touch occurs outside the focused EditText. See the complete method below.

Problem

On Android, tapping outside an EditText does not automatically dismiss the soft keyboard. If you want the app to behave like iOS (tap outside to dismiss), you must detect touches outside the currently focused EditText and call InputMethodManager.hideSoftInputFromWindow(…).

Solution (Activity)

Override dispatchTouchEvent in the Activity that hosts your EditText(s). The following method checks whether the currently focused view is an EditText, determines whether the touch was outside that view, and hides the keyboard if so.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    View view = getCurrentFocus();
    boolean ret = super.dispatchTouchEvent(event);

    if (view instanceof EditText) {
        // Re-get focus to use when computing coordinates (guard against changes)
        View w = getCurrentFocus();
        if (w == null) {
            return ret;
        }

        int[] scrcoords = new int[2];
        w.getLocationOnScreen(scrcoords);

        float x = event.getRawX() + w.getLeft() - scrcoords[0];
        float y = event.getRawY() + w.getTop() - scrcoords[1];

        // If the touch action is ACTION_UP and the touch is outside the view bounds
        if (event.getAction() == MotionEvent.ACTION_UP &&
            (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom())) {

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // Use the window token of the currently focused view (guarding for null)
                View currentFocus = getWindow().getCurrentFocus();
                if (currentFocus != null) {
                    imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
                }
            }
        }
    }

    return ret;
}

What this does

  • Checks whether the currently focused view is an EditText.
  • Computes the touch coordinates relative to the EditText's position on screen.
  • If the touch occurred outside the EditText (ACTION_UP), it hides the soft keyboard via InputMethodManager.hideSoftInputFromWindow(…).

Note: If you remove the coordinate checks, the keyboard may not come up the next time you tap the EditText — so keep the bounds checks to ensure normal behavior.

Short hide call (single EditText)

If you already have a reference to the EditText and want to hide the keyboard directly (for example from a click listener), use:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Fragments

If your EditText lives in a Fragment, one approach is:

  • Implement the dispatchTouchEvent override in the hosting Activity (the Activity receives touch events before fragments do), or
  • Add a touch listener on the fragment's root view and detect taps outside the focused EditText, then hide the keyboard with InputMethodManager as shown above.

Troubleshooting and notes

  • Always guard against null from getCurrentFocus() and getWindow().getCurrentFocus() to avoid NullPointerException.
  • If your layout moves or you use complex nested views, confirm the coordinate math still applies (getLocationOnScreen is used to normalize coordinates).
  • Consider accessibility and UI expectations: tapping to dismiss is convenient but ensure it doesn't interfere with other gestures.

All the best and happy coding. (y)

Monday, October 28, 2013

Schedule a PHP Script on Windows Server with Task Scheduler (Windows Cron)

Overview

Without any manual trigger or interaction, if you want to run a specific task at a specific time you can use a scheduled task. On Linux/Unix this is done with cron / crontab; on Windows the equivalent built-in tool is Task Scheduler. This article shows a simple workflow to run a PHP script on a Windows server (WAMP) on a schedule by invoking PHP from a batch file.

Requirements

  • A PHP script that is independently executable (no missing relative include paths). Example: backupcron.php.
  • PHP CLI installed (php.exe) as part of WAMP (or a separate PHP install).
  • Permission to create and run scheduled tasks on the Windows server.

Key points before you begin

  • Use absolute paths in scripts and the batch file.
  • If your PHP script depends on include files, ensure includes use absolute paths or the script sets the correct working directory.
  • Replace the example PHP path below with the path on your machine (the example uses php5.4.3 as an illustration).

Procedure (step-by-step)

  1. Create the PHP action script (example name: backupcron.php). Make sure it is executable from the command line and does not depend on relative include paths unless handled explicitly.

  2. Create a Windows batch file that runs the PHP script. Example name: backup.bat.

    Example batch file content (exact example from the original article):

@echo off
C:\wamp\bin\php\php5.4.3\php.exe -f C:\wamp\www\Test\admin\backupcron.php

Recommended safer variant (handles spaces and logs output):

@echo off
"C:\wamp\bin\php\phpX.Y.Z\php.exe" -f "C:\wamp\www\Test\admin\backupcron.php" >> "C:\wamp\www\Test\admin\backup.log" 2>&1
  • Replace phpX.Y.Z with your installed PHP folder (e.g., php7.4.30 or php8.1.0).
  • The >> and 2>&1 redirect stdout and stderr to a log file for debugging.
  1. Test the batch file from a Command Prompt. Open cmd.exe and run the batch file path explicitly. Fix any immediate PHP or path errors.

  2. Open Task Scheduler: Start → Programs → Accessories → System Tools → Task Scheduler.

Task Scheduler main view

  1. In Task Scheduler, open the Task Scheduler Library to view scheduled jobs.

Task Scheduler library

  1. Click "Create Basic Task" (or "Create Task" for advanced options) from the right panel and follow the wizard:
  • Give the task a name and description.
  • Trigger: choose the schedule (Daily, Weekly, One time, or "When I log on", etc.).

Create Basic Task wizard options

  1. For more control, open the Trigger properties and set repetition options (for example: every hour). Example trigger view:

Trigger properties example

  1. In the Action step choose to "Start a program" and set the program/script to cmd.exe and the arguments to run your batch file. Example used in the original article:
  • Program/script: cmd
  • Add arguments (optional): /c C:\wamp\www\Test\admin\backup.bat

Alternatively you can directly point the Action to the batch file:

  • Program/script: C:\wamp\www\Test\admin\backup.bat

Example action dialogs from the original article:

Action example 1

Action example 2

  1. Common action configuration notes:
  • If using cmd.exe /c, include the full path to your .bat file in the arguments.
  • If you point directly to the .bat file, set the "Start in (optional)" field to the folder containing the batch file so relative paths work.
  • Use quoted paths if any path contains spaces.
  1. Other task options you may need to change (found on the General tab or when creating an advanced Task):
  • Set the user account under which the task runs. If the task needs network access or specific privileges, use an account with the right permissions.
  • Consider selecting "Run whether user is logged on or not" if you need the task to run in the background.
  • If the task requires elevation, check "Run with highest privileges".
  1. Create or copy your batch file to the target location (example path used in the article):
C:\wamp\www\Test\admin\backup.bat
  1. Example batch file content (again):
@echo off
C:\wamp\bin\php\php5.4.3\php.exe -f C:\wamp\www\Test\admin\backupcron.php
  1. backupcron.php is the PHP action script that contains the code to generate the backup file.

  2. After creating the scheduled task, you can run it manually from Task Scheduler (right-click → Run) to validate that it works.

  3. Verify the scheduled executions in Task Scheduler's "History" tab or by checking your output file or the log file if you redirected output in the batch file.

Troubleshooting (common failures and fixes)

  • "Nothing happens" — open a command prompt and run the batch file manually to see errors.
  • PHP path errors — verify the path to php.exe and update the batch file accordingly.
  • Include files missing — make sure your PHP script uses absolute paths or sets chdir(__DIR__) at the top so includes resolve relative to the script folder.
  • Permissions — verify the task's user account has permission to run php.exe and write to output folders. Try "Run whether user is logged on or not" and provide credentials, and/or check "Run with highest privileges" if elevation is required.
  • Paths with spaces — wrap paths in double quotes.
  • No error output — append >> path\to\log.txt 2>&1 to the batch file command to capture stdout/stderr.

Example logging batch file (recommended)

@echo off
"C:\wamp\bin\php\phpX.Y.Z\php.exe" -f "C:\wamp\www\Test\admin\backupcron.php" >> "C:\wamp\www\Test\admin\backup.log" 2>&1

Final checks

  • Test from the command line first.
  • Test running the task manually from Task Scheduler.
  • Check log files and Task Scheduler History for errors.

That's all: follow the steps above to execute specific tasks at specific intervals on Windows using Task Scheduler and a simple .bat wrapper for PHP CLI.

Thursday, October 17, 2013

How to Prevent Backslashes from Being Removed When Inserting Windows File Paths into MySQL

Hi, I faced a problem while inserting the file path to mysql database. You can also encounter similar problem when you work with Mysql. So thought of adding this info for your information.

Problem

While inserting a file path to my mysql table, I noticed that the slashes in the path are missed once they added to mysql table. This is because the problem is with the backslashes \, which are often used to escape certain characters. Hence Mysql considers it as a escape character and ignores it.

Why this happens

Backslash () is an escape character in many languages and in SQL string literals. When you send a string containing single backslashes to MySQL without properly escaping them, they may be interpreted as escape sequences or removed. In PHP, functions that prepare SQL statements or construct SQL literals must receive strings with backslashes escaped, otherwise the stored value will not contain the original single backslashes.

Solutions

You can overcome this problem by different methods.

1) Double the backslashes

You can add double slashes instead of single slash in the directory path.

Eg:

Original (how you think of the path):

D:\Projects\Test\SQLBackup

Written with single backslashes (this may be interpreted incorrectly when inserted):

D:\Projects\Test\SQLBackup  <-- in source you must escape each backslash when building the SQL literal

In many contexts (for example in PHP string literals) you must represent each backslash as \\ in the source so that a single \ ends up in the stored value. If you see backslashes missing in the database, doubling them before insertion is one straightforward fix.

2) Use PHP quotemeta()

You can just do:

quotemeta($rawpath)

before the insert statement. This function adds backslashes before characters that are considered special in regular expressions; it can also help prevent removal of backslashes when building SQL literals.

3) Use PHP addslashes()

You can also just do:

addslashes($url)

This will escape single quotes, double quotes, backslashes and NUL bytes by prefixing them with backslashes.

All the above should work. I just tried the first two and they work perfectly fine.

Safer, recommended approach (avoid manual escaping)

While the above methods fix the immediate problem, the safest practice for inserting any user-supplied or variable strings into a database is to use parameterized queries (prepared statements) or escaping functions that are tied to the database connection's character set.

Examples:

  • Using mysqlirealescape_string (if you are using mysqli and not using prepared statements):
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset('utf8mb4');
$escaped = $mysqli->real_escape_string($path);
$sql = "INSERT INTO files (path) VALUES ('" . $escaped . "')";
$mysqli->query($sql);
  • Using a prepared statement (recommended):
$mysqli = new mysqli($host, $user, $pass, $db);
$stmt = $mysqli->prepare("INSERT INTO files (path) VALUES (?)");
$stmt->bind_param('s', $path);
$stmt->execute();

Prepared statements avoid the need to manually escape backslashes for SQL and protect against SQL injection. They are the preferred method for inserting strings such as file paths.

Other notes

  • As an alternative for storing paths, you can consider using forward slashes (/) in paths on many platforms (PHP accepts them on Windows for many filesystem functions) — they avoid the escaping issues of backslashes and are cross-platform-friendly.
  • Ensure your DB connection charset is set (for example, utf8mb4) before calling escaping functions like real_escape_string.

So thought of sharing this info with you all. Happy Coding!!!