gpt4 book ai didi

android - 当来自原生 android 方法 channel 的回调时,在 dart 中运行方法或函数

转载 作者:行者123 更新时间:2023-12-04 13:56:13 25 4
gpt4 key购买 nike

当方法 channel 发送回调时,我需要在后台运行一个 Dart 函数......

在下面的 Dart 代码...我想在收到任何回调或从方法 channel 返回时运行 SendData() 函数...

重要 *** => 我希望它在后台工作...即使在应用程序终止后...无需更改 UI 和所有...只需在后台调用 sendData() 函数

MainActivity.Java

package com.ashbu.flutterappbackground;

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import android.content.IntentFilter;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import android.app.Service;




public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/battery";
private static final String IncomingCall_CHANNEL = "samples.flutter.dev/IncomingCall";

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 EventChannel(flutterEngine.getDartExecutor(), IncomingCall_CHANNEL).setStreamHandler(
new StreamHandler() {
private BroadcastReceiver IncomingCallStateChangeReceiver;
@Override
public void onListen(Object arguments, EventSink events) {
IncomingCallStateChangeReceiver = createIncomingCallStateChangeReceiver(events);
registerReceiver(
IncomingCallStateChangeReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

@Override
public void onCancel(Object arguments) {
unregisterReceiver(IncomingCallStateChangeReceiver);
IncomingCallStateChangeReceiver = null;
}

}
);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
// Note: this method is invoked on the main thread.
if (call.method.equals("getBatteryLevel")) {
startAlarm();
MyBroadcastReceiver dataGEt = new MyBroadcastReceiver();
result.success(dataGEt.getData());
} else {
cancelAlarm();
}
}
);
}
private BroadcastReceiver createIncomingCallStateChangeReceiver(final EventSink events){
return new BroadcastReceiver() {
@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);
System.out.println("incomingNumber : " + incomingNumber);
Toast.makeText(context, "TeleDuce Customer " + incomingNumber,
Toast.LENGTH_LONG).show();
if (incomingNumber != null) {
events.success(incomingNumber);
} else {
events.success("Abaha");
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}
};
}


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();
}


}

Main.Dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
static const platform = const MethodChannel('samples.flutter.dev/battery');
static const EventChannel eventChannel =
EventChannel('samples.flutter.dev/IncomingCall');
// Get battery level.
String _batteryLevel = 'Unknown battery level.';
String _IncomingCallStatus = 'Battery status: unknown.';

Future<void> _getBatteryLevel() async {
String batteryLevel;
try {
final String result = await platform.invokeMethod('getBatteryLevel');
batteryLevel = 'Battery level at $result % .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}

setState(() {
_batteryLevel = batteryLevel;
});
}

Future<void> SendData() async { <--------Need to call this function in background
var param = {
'userId': 272.toString(),
'api_key': '******************',
'env': 'production',
'common_search': '',
'filter_type': 'My',
'filter_type_data': '',
'leadsourcerequest': true,
};
// Get the previous cached count and increment it.
var res = await http.post(
'https://***********.amazonaws.com/default/Leadapi',
body: json.encode(param));
Map responsejson = json.decode(res.body);
print(res);
print(responsejson['response_data'][0]);
// This will be null if we're running in the background.
}

@override
void initState() {
// TODO: implement initState
eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
super.initState();
}

void _onEvent(Object event) {
setState(() {
_IncomingCallStatus = "Battery status: $event";
SendData(); <-------- This need to be working on background
print('++++++++++++');
});
}

void _onError(Object error) {
setState(() {
_IncomingCallStatus = 'Battery status: unknown.';
});
}

实际上像电池状态,batteryCahnenl 之类的词都是因为我只是从 flutter 平台 channel 示例中复制了这段代码......请忽略

最佳答案

一路platform channels工作是 Flutter 应用程序执行一个方法来运行特定于平台的代码。然后,Flutter 应用程序等待回调,然后可以处理。
您可能希望缩小您在此问题中尝试实现的范围。比如你打算什么时候调用sendData()来自特定于平台的代码?您是否希望收听诸如 firebase_messaging 之类的通知? ?如果您想使用 Flutter 在后台运行任务,您可能需要考虑使用 Isolate .

关于android - 当来自原生 android 方法 channel 的回调时,在 dart 中运行方法或函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61949907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com