Last active
June 5, 2021 18:38
-
-
Save apoorvpandey0/f22856c91020d9cceaa79bc2af2cc202 to your computer and use it in GitHub Desktop.
Flutter method channel with kotlin code snippet 2021
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.flutter_application_1 | |
import android.content.Context | |
import android.content.ContextWrapper | |
import android.content.Intent | |
import android.content.IntentFilter | |
import android.os.BatteryManager | |
import android.os.Build.VERSION | |
import android.os.Build.VERSION_CODES | |
import androidx.annotation.NonNull | |
import io.flutter.embedding.android.FlutterActivity | |
import io.flutter.embedding.engine.FlutterEngine | |
import io.flutter.plugin.common.MethodChannel | |
class MainActivity: FlutterActivity() { | |
private val CHANNEL = "samples.flutter.dev/battery" | |
private fun getBatteryLevel(): Int { | |
val batteryLevel: Int | |
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) { | |
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager | |
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) | |
} else { | |
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) | |
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) | |
} | |
return batteryLevel | |
} | |
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { | |
super.configureFlutterEngine(flutterEngine) | |
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { | |
// Note: this method is invoked on the main thread. | |
call, result -> | |
if (call.method == "getBatteryLevel") { | |
val batteryLevel = getBatteryLevel() | |
if (batteryLevel != -1) { | |
result.success(batteryLevel) | |
} else { | |
result.error("UNAVAILABLE", "Battery level not available.", null) | |
} | |
} else { | |
result.notImplemented() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the flutter code for this:
This example is taken from official flutter.dev site