Creating an Android trial application that expires

2019-01-02 22:13发布

I have an application which I want to hit the market as a Paid app. I would like to have other version which would be a "trial" version with a time limit of say, 5 days?

How can I go about doing this?

13条回答
迷人小祖宗
2楼-- · 2019-01-02 22:22

I come across this question while searching for the same problem, i think we can utilize free date api like http://www.timeapi.org/utc/now or some other date api to check for expiry of trail app. this way is efficient if you wish to deliver the demo and worried about payment and require fix tenure demo. :)

find the code below

public class ValidationActivity extends BaseMainActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
protected void onResume() {
    processCurrentTime();
    super.onResume();
}

private void processCurrentTime() {
    if (!isDataConnectionAvailable(ValidationActivity.this)) {
        showerrorDialog("No Network coverage!");
    } else {
        String urlString = "http://api.timezonedb.com/?zone=Europe/London&key=OY8PYBIG2IM9";
        new CallAPI().execute(urlString);
    }
}

private void showerrorDialog(String data) {
    Dialog d = new Dialog(ValidationActivity.this);
    d.setTitle("LS14");
    TextView tv = new TextView(ValidationActivity.this);
    tv.setText(data);
    tv.setPadding(20, 30, 20, 50);
    d.setContentView(tv);
    d.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            finish();
        }
    });
    d.show();
}

private void checkExpiry(int isError, long timestampinMillies) {
    long base_date = 1392878740000l;// feb_19 13:8 in GMT;
    // long expiryInMillies=1000*60*60*24*5;
    long expiryInMillies = 1000 * 60 * 10;
    if (isError == 1) {
        showerrorDialog("Server error, please try again after few seconds");
    } else {
        System.out.println("fetched time " + timestampinMillies);
        System.out.println("system time -" + (base_date + expiryInMillies));
        if (timestampinMillies > (base_date + expiryInMillies)) {
            showerrorDialog("Demo version expired please contact vendor support");
            System.out.println("expired");
        }
    }
}

private class CallAPI extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String urlString = params[0]; // URL to call
        String resultToDisplay = "";
        InputStream in = null;
        // HTTP Get
        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream());
            resultToDisplay = convertStreamToString(in);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
        return resultToDisplay;
    }

    protected void onPostExecute(String result) {
        int isError = 1;
        long timestamp = 0;
        if (result == null || result.length() == 0 || result.indexOf("<timestamp>") == -1 || result.indexOf("</timestamp>") == -1) {
            System.out.println("Error $$$$$$$$$");
        } else {
            String strTime = result.substring(result.indexOf("<timestamp>") + 11, result.indexOf("</timestamp>"));
            System.out.println(strTime);
            try {
                timestamp = Long.parseLong(strTime) * 1000;
                isError = 0;
            } catch (NumberFormatException ne) {
            }
        }
        checkExpiry(isError, timestamp);
    }

} // end CallAPI

public static boolean isDataConnectionAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    if (info == null)
        return false;

    return connectivityManager.getActiveNetworkInfo().isConnected();
}

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

}
}

its working solution.....

查看更多
爷、活的狠高调
3楼-- · 2019-01-02 22:30

The easiest and best way to do this is the implement BackupSharedPreferences.

The preferences are preserved, even if the app is uninstalled and reinstalled.

Simply save the install date as a preference and you are good to go.

Here's the theory: http://developer.android.com/reference/android/app/backup/SharedPreferencesBackupHelper.html

Here's the example: Android SharedPreferences Backup Not Working

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-02 22:31

Currently most developers accomplish this using one of the following 3 techniques.

The first approach is easily circumvented, the first time you run the app save the date/time to a file, database, or shared preferences and every time you run the app after that check to see if the trial period has ended. This is easy to circumvent because uninstalling and reinstalling will allow the user to have another trial period.

The second approach is harder to circumvent, but still circumventable. Use a hard coded time bomb. Basically with this approach you will be hard code an end date for the trial, and all users that download and use the app will stop being able to use the app at the same time. I have used this approach because it is easy to implement and for the most part I just didn't feel like going through the trouble of the third technique. Users can circumvent this by manually changing the date on their phone, but most users won't go through the trouble to do such a thing.

The third technique is the only way that I have heard about to truly be able to accomplish what you want to do. You will have to set up a server, and then whenever your application is started your app sends the phones unique identifier to the server. If the server does not have an entry for that phone id then it makes a new one and notes the time. If the server does have an entry for the phone id then it does a simple check to see if the trial period has expired. It then communicates the results of the trial expiration check back to your application. This approach should not be circumventable, but does require setting up a webserver and such.

It is always good practice to do these checks in the onCreate. If the expiration has ended popup an AlertDialog with a market link to the full version of the app. Only include an "OK" button, and once the user clicks on "OK" make a call to "finish()" to end the activity.

查看更多
Ridiculous、
5楼-- · 2019-01-02 22:32

By definition, all paid Android apps on the market can be evaluated for 24 hours after purchase.

There's an 'Uninstall and Refund' button which changes to 'Uninstall' after 24 hours.

I'd argue this button is way too prominent!

查看更多
走好不送
6楼-- · 2019-01-02 22:33

This is an old question but anyways, maybe this will help someone.

In case you want to go with the most simplistic approach(which will fail if the app is uninstalled/reinstalled or user changes device's date manually), this is how it could be:

private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
private final long ONE_DAY = 24 * 60 * 60 * 1000;

@Override
protected void onCreate(Bundle state){
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    String installDate = preferences.getString("InstallDate", null);
    if(installDate == null) {
        // First run, so save the current date
        SharedPreferences.Editor editor = preferences.edit();
        Date now = new Date();
        String dateString = formatter.format(now);
        editor.putString("InstallDate", dateString);
        // Commit the edits!
        editor.commit();
    }
    else {
        // This is not the 1st run, check install date
        Date before = (Date)formatter.parse(installDate);
        Date now = new Date();
        long diff = now.getTime() - before.getTime();
        long days = diff / ONE_DAY;
        if(days > 30) { // More than 30 days?
             // Expired !!!
        }
    }

    ...
}
查看更多
Bombasti
7楼-- · 2019-01-02 22:33

I've developed a Android Trial SDK which you can simply drop into your Android Studio project and it will take care of all the server-side management for you (including offline grace periods).

To use it, simply

Add the library to your main module's build.gradle

dependencies {
  compile 'io.trialy.library:trialy:1.0.2'
}

Initialize the library in your main activity's onCreate() method

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Initialize the library and check the current trial status on every launch
    Trialy mTrialy = new Trialy(mContext, "YOUR_TRIALY_APP_KEY");
    mTrialy.checkTrial(TRIALY_SKU, mTrialyCallback);
}

Add a callback handler:

private TrialyCallback mTrialyCallback = new TrialyCallback() {
    @Override
    public void onResult(int status, long timeRemaining, String sku) {
        switch (status){
            case STATUS_TRIAL_JUST_STARTED:
                //The trial has just started - enable the premium features for the user
                 break;
            case STATUS_TRIAL_RUNNING:
                //The trial is currently running - enable the premium features for the user
                break;
            case STATUS_TRIAL_JUST_ENDED:
                //The trial has just ended - block access to the premium features
                break;
            case STATUS_TRIAL_NOT_YET_STARTED:
                //The user hasn't requested a trial yet - no need to do anything
                break;
            case STATUS_TRIAL_OVER:
                //The trial is over
                break;
        }
        Log.i("TRIALY", "Trialy response: " + Trialy.getStatusMessage(status));
    }

};

To start a trial, call mTrialy.startTrial("YOUR_TRIAL_SKU", mTrialyCallback); Your app key and trial SKU can be found in your Trialy developer dashboard.

查看更多
登录 后发表回答