mercredi 6 avril 2016

Testing method which use contest and registerReceiver

Problem Description

I'm trying to test function which is written below. Function is using context and also make some calls to get batters status.

Question

Is it possible to test this method and if yes can you please drop me an example.

Sample Code

/**
 * This function returns Battery charged level.
 * @return Battery charged level if success; otherwise -1.0f
 */
public float getBatteryLevel(final Context context) {
    // Because it's a sticky intent, you don't need to register a BroadcastReceiver—by simply
    // calling registerReceiver passing in null as the receiver as shown in the next snippet,
    // the current battery status intent is returned.
    final IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    final Intent batteryStatus = context.registerReceiver(null, ifilter);
    if (batteryStatus != null) {
        final int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        final int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        return level / (float)scale;
    }
    else {
        Logger.error(TAG, "Can't Detect Battery Level.");
    }

    return -1.0f;
}

Aucun commentaire:

Enregistrer un commentaire