Android Tutorial Trial Tutorial

Hey everyone,

Here I will explain how you can make an evaluation/trial version of your app using an online database.
With this, the user will be able to open up the app x times. When 0 is achieved, it will force close the app.

First you'd need some basic knowledge of HTML, PHP, SQL and ofcourse Basic4Android.
I will not explain on how to setup your directory files, SQL Database, etc.

Here's how it works:

Before the app runs (in globals) I send my IMEI with a POST Method to a php webserver. I do this with one code with a library I have written, instead of using HTTPUtils etc.
The database exists of three columns:
id, IMEI, starts.

The PHP file looks in the database if the IMEI exists, if it exists, it looks for the amount in the third column and substracts 1. If it doesn't exists, a IMEI.txt file is generated. The file contains how much the app can be opened. 30 here.
If 0 is succeeded, the text Expired appears.

In my app, a timer runs during 6 seconds. This is done to process everything server side. When the timer ticks, I perform a http GET to the IMEI.txt (its not IMEI.txt but e.g. 59644885484.txt). If the response string is an amount, then the app runs, otherwise if it's "Expired", then the app is closed.

Some code:

B4X:
Sub Globals
        ProgressDialogShow("Trial Activated" & CRLF & "Connecting with webserver for authentication")
   Dim p As PhoneId
   Dim cantopen As Boolean
   cantopen = False
   Dim camera1 As AdvancedCamera
   Dim strActivationCheck As String
   strActivationCheck = "http://www.example.com/" & p.GetDeviceId & ".txt"

'Small password protection, PHP File on webserver, IMEI, Trials
' change the url to the url of your site.
'You should download the latest version of my Advanced Camera Library to use 'AppTrial' because it is a lot easie for me this way instead of working with HTTPutlils.
   Camera1.AppTrial("Password","http://www.example.com/trialCheck.php",p.GetDeviceId,30)

   tmrEvaluation.Initialize("tmrEvaluation",6000)
   tmrEvaluation.Enabled = True

End Sub

Sub tmrEvaluation_tick
   ProgressDialogShow("Checking Activation.")
   tmrEvaluation.Enabled = False
   Dim request1 As HttpRequest
   request1.InitializeGet(strActivationCheck)
   request1.Timeout=50000
   If HttpClient1.Execute(request1, 1) = False Then
   Return
   End If
End Sub

Sub http_ResponseSuccess (Response As HttpResponse, TaskId As Int)
   ProgressDialogHide()
   If TaskId = 1 Then
   Dim strActivationResponse As String
   strActivationResponse = response.GetString("UTF8")
      If strActivationResponse = "Expired" Then
      cantopen = True
         Msgbox("The evaluation version of StreamNation Studio has expired." & CRLF & "You can buy the full version or take the chance of winning the full version by rating the app and giving it a small review!","Evaluation")
         ExitApplication
      Else
         Msgbox("You can run the app " & strActivationResponse & " more times.","Evaluation")
      End If
   End If

End Sub

Sub Http_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    If TaskId = 1 Then
   Msgbox(Reason,"An error occured." & CRLF & "Check your internet connection or try again later.")
   ExitApplication
   End If

End Sub

Attached is the PHP file. Upload it and link to that PHP File.
It is commented. Open it and edit where asked.

Here is a maintenance table of how many times StreamNation Studio is downloaded, opened, used,...:

http://www.rootsoftllc.com/streamNation/trialStats.php

XverhelstX
 

Attachments

  • ServerPHP.zip
    739 bytes · Views: 723
Last edited:

timo

Active Member
Licensed User
Longtime User
this piece of code
B4X:
'Optional: Remove '[' and ']' from the response received from my server:-> array[{jsonObject}]
 Dim tmp As String
 Dim lungh As Int
 tmp=result
 lungh= tmp.Length
 tmp= tmp.SubString2(1,lungh-1) 'cut first+last char
 result=tmp
 '-----------------------------------------------------
is for putting [] away. If you don't do it, i think that your response begins with an array (list), not an object(map) and next object gets error.
 
Last edited:

Fox

Active Member
Licensed User
Longtime User
the imei of the emulator should be: "000000000000000"; verify in your Mysql records if it is so.


the imei of emulator is zero yes. so the solution for this would be :sign0163:
 

Fox

Active Member
Licensed User
Longtime User
OK. Your code is writing right in the MSql DB. To see if the response is also correct, you can maybe post PHP and B4A code


php code:

B4X:
<?php
$hst  = "localhost";
$db = "xxxxxxxxxx";
$usr = "xxxxxxxx";
$pwd = "xxxxxxxx";
$imi= $_GET['imei'];

$conn_DB=mysql_connect($hst,$usr,$pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

$query="SELECT * FROM gtrial WHERE imei ='$imi'";
$result=mysql_query($query,$conn_DB) or die(mysql_error());
$numrows=mysql_num_rows($result);

If ($numrows == 0) {
$restano=3;
$queryINS="INSERT INTO gtrial (imei,startsleft) VALUES ('$imi',$restano)";
mysql_query($queryINS);
                    }
else if ($numrows > 0) {
//never > 1 anyway
$restano=mysql_result($result,0,'startsleft'); 
        if($restano>0)         {
            $restano=$restano -1;
$queryUPDT="UPDATE gtrial SET startsleft = $restano WHERE imei='$imi'";
mysql_query($queryUPDT);
                            }
                        }
                        
$queryOUT="SELECT * FROM gtrial WHERE imei ='$imi'";
$output=mysql_query($queryOUT);    

$rows = array();
    while($r = mysql_fetch_assoc($output)) {
        $rows[] = $r;
    }
    print json_encode($rows);
?>

b4a code:

B4X:
Sub Process_Globals
Dim httpC As HttpClient
'put here to obfuscate user,password,php.name and hosting [->Release(obfuscated)]
Dim indirizzo As String : indirizzo= "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx?imei="
'Dim parcheggio As String: parcheggio="http://www.yourSite.com/" '(no more needed here)
End Sub

Sub Globals
Dim p As PhoneId
Dim deviceID As String
deviceID = p.GetDeviceId
Dim m As Map

End Sub

Sub Activity_Create(FirstTime As Boolean)
deviceID = p.GetDeviceId
Log(deviceID)
If FirstTime Then
httpC.Initialize("httpC")
End If
checkTrialsRemaining
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
Activity.Finish
End Sub

Sub checkTrialsRemaining
Dim req As HttpRequest
req.InitializeGet(indirizzo&deviceID)
httpC.Execute(req,1)
ProgressDialogShow("Validation ...")

End Sub


Sub httpC_ResponseSuccess (Response As HttpResponse, TaskId As Int)
Log("Response: "&Response) '<-add this line
Dim result As String
Dim JSON As JSONParser
Dim restOpen As Int
result = Response.GetString("UTF8")
Log(result)

'Optional: Remove '[' and ']' from the response received from my server:-> array[{jsonObject}]
Dim tmp As String
Dim lungh As Int
tmp=result
lungh= tmp.Length
tmp= tmp.SubString2(1,lungh-1) 'cut first+last char
result=tmp
'-----------------------------------------------------
Log(result)

JSON.Initialize(result)
Log(result)
Dim m As Map
m=JSON.NextArray

restOpen=m.Get("startsleft")
ProgressDialogHide

If restOpen=0 Then
Msgbox("Trial expired"," Trial")
Response.Release
Activity.Finish
Else
If restOpen > 1 Then
Msgbox((restOpen - 1)&" out of 3 openings remaining"," Trial")
Else
Msgbox("Last opening of 3"," Trial")
End If
End If
Response.Release
End Sub

Sub httpC_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
'no Reason shown in order not to give the user informations about hosting and php names:
ProgressDialogHide
Msgbox("Connection error. Try later again."," Trial")

If Response <> Null Then
Log("Resp.not Null")
Response.Release
End If
'If no web connection is available, Response is naturally Null and you don't have to release a Null object
ExitApplication
End Sub
 
Last edited:

timo

Active Member
Licensed User
Longtime User
Seems correct. Just one thing: with my provider if i use:
B4X:
<?php$hst  = "localhost";
...
it doesn't work: I have to put the hole addres. Anyway, if your app writes on the db, i assume it works in your case.

You say you have an error in responsesuccess on the device. Try if the response you receive (by adding a MsgBox(Response,"")' in that sub instead of Log) is
different:
1 - By runningi in the emulator (where it seems to work)
2 - and then in the phone (when not attached to PC)
If in case 2 no strange carachter is added to the response I don't know why it gives you error. Post eventually the text of the response.
Another question: When you run it in the emulator x times: do you receive the correct countdown? (2-1-Trial expired?)
 
Last edited:

Fox

Active Member
Licensed User
Longtime User
Seems correct. Just one thing: with my provider if i use:
B4X:
<?php$hst  = "localhost";
...
it doesn't work: I have to put the hole addres. Anyway, if your app writes on the db, i assume it works in your case.

You say you have an error in responsesuccess on the device. Try if the response you receive (by adding a MsgBox(Response,"")' in that sub instead of Log) is
different:
1 - By runningi in the emulator (where it seems to work)
2 - and then in the phone (when not attached to PC)
If in case 2 no strange carachter is added to the response I don't know why it gives you error. Post eventually the text of the response.
Another question: When you run it in the emulator x times: do you receive the correct countdown? (2-1-Trial expired?)

ok i have tested it with the message box on phone i get this result:


anywheresoftware.b4a.http.HttpClientWrapper$HttpResponeWrapper@4621cf68

and in emulator this:

anywheresoftware.b4a.http.HttpClientWrapper$HttpResponeWrapper@44ee46f0

but i think thats are no json results :D

and yes the app working in emulator 2,1 trial expired! ;)
 

Fox

Active Member
Licensed User
Longtime User
thanks all you guys for your help but i will giveup at this chapter ;) sorry but i have no clue to solve it... i don't understand this..
 

timo

Active Member
Licensed User
Longtime User
Last thing, if you want;
add this line just after "JSON.Initialize(result)":

msgbox("JSON STRING : "&result,"")

to see your json string.
This should now begin with "{" and end with "}"

b4a code:

B4X:
Sub httpC_ResponseSuccess (Response As HttpResponse, TaskId As Int)
Dim result As String
Dim JSON As JSONParser
Dim restOpen As Int
result = Response.GetString("UTF8")

'Optional: Remove '[' and ']' from the response received from my server:-> array[{jsonObject}]
Dim tmp As String
Dim lungh As Int
tmp=result
lungh= tmp.Length
tmp= tmp.SubString2(1,lungh-1) 'cut first+last char
result=tmp
'-----------------------------------------------------

JSON.Initialize(result)

msgbox("JSON STRING : "&result,"")'------------------------------->add this

'...
'...etc...
End Sub
 
Last edited:
Top