![](/img/trans.png)
[英]How to send data to the android native code from the flutter code in flutter
[英]How to send data to Flutter from native (Android)
我需要將數據從下面的 class 傳遞到我的 flutter 應用程序,其中數據僅在來電事件發生時可用。 我需要將此數據(手機號碼)傳遞給 flutter(如果可能的話,即使 flutter 應用程序已終止,我也需要傳遞數據)
BroadcastReciever.java
package com.ashbu.flutterappbackground;
...
public class MyBroadcastReceiver extends BroadcastReceiver {
String phoneNumber;
@Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
phoneNumber = incomingNumber;
Toast.makeText(context, "TeleDuce Customer "+ incomingNumber,
Toast.LENGTH_LONG).show();
}
},PhoneStateListener.LISTEN_CALL_STATE);
}
public String getData() {
String number = null;
if (phoneNumber != null) {
number = phoneNumber;
}else {
number = "noData";
}
return number;
}
從上面的代碼中,我需要將 incomingNumber 傳遞給 flutter。如果可能 - 即使應用程序關閉也共享數據。
MainActivity.java
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/getNumber";
AlarmManager alarmManager;
PendingIntent pendingIntent;
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, MyService.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
// Note: this method is invoked on the main thread.
if (call.method.equals("getMobileNumber")) {
startAlarm();
MyBroadcastReceiver dataGEt = new MyBroadcastReceiver();
System.out.println(dataGEt.getData());
result.success(dataGEt.getData());
} else {
cancelAlarm();
}
}
);
}
private void startAlarm() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
}
}
private void cancelAlarm() {
alarmManager.cancel(pendingIntent);
Toast.makeText(getApplicationContext(), "Alarm Cancelled", Toast.LENGTH_LONG).show();
}
}
目前,即使應用程序終止,上述代碼也能正常工作。 但我不知道 flutter 是否會在應用程序終止后接受數據
你應該在 Flutterside 中實現methodHandler
並且你應該 make static object of methodchannel
例如
class MethodChannelHelper {
static const MethodChannel channel = const MethodChannel('method_channal_name');
}
class MethodChannelCall{
static initMethodChannel({Function onCallBack}) async {
MethodChannelHelper.channel.setMethodCallHandler((MethodCall call) async {
switch (call.method) {
case 'callback_from_native':
print("This method will be called when native fire")
}
});
await MethodChannelHelper.channel.invokeMethod('call_native');
}
}
在 main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await MethodChannelCall.initMethodChannel(onCallBack: (payload) {
});
runApp(MyApp());
}
現在在Android這邊
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
when (call.method) {
"call_native" -> {
methodChannel?.invokeMethod("callback_from_native","")
}
}
我將列表作為參數從 main.dart 傳遞給 MainActivity.kt class
在 main.dart
var items =['hello', 'hii', 'flowers', 'roses','loutes'];
Future<void> _getDeviceInfo() async {
String result;
try {
platform.invokeMethod('getDeviceInfo' , items).then((items) {
result = items.toString();
setState(() {
deviceInfo = result;
});
});
} on PlatformException catch (e) {
print("_getDeviceInfo==>${e.message}");
}
}
在 MainActivity.kt class
package com.example.flutter_to_native
import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
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 = "com.example.flutter/device_info" // Unique Channel
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 == "getDeviceInfo") {
val data = call.arguments
Log.d("data1", "$data")
val intent = Intent(this, DemoActivity::class.java)
intent.putExtra("data",data.toString())
startActivity(intent)
else {
result.notImplemented()
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.