我使用react-native创建了一个应用程序,但是我需要从android小部件触发一个react事件。这是我目前的设置:
public class IsHetAlBierTijdWidget extends AppWidgetProvider {
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.app_name);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.is_het_al_bier_tijd_widget);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
sendEventToReactApp(context);
}
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
public void sendEventToReactApp(Context context) {
WritableMap event = Arguments.createMap();
event.putString("message", "MyMessage");
ReactApplicationContext reactApplicationContext = new ReactApplicationContext(context);
MSREventBridgeModule msrEventBridgeModule = new MSREventBridgeModule(reactApplicationContext);
msrEventBridgeModule.emitEvent("Widget_Update",event);
}
}
反应代码:
class Home extends Component {
constructor(){
super();
this.onWidgetUpdate.bind(this);
}
onWidgetUpdate(){
console.log("widget update...");
}
componentWillMount() {
this.props.fetchBierTijd()
DeviceEventEmitter.addListener('Widget_Update', this.onWidgetUpdate);
}
componentWillUnmount() {
DeviceEventEmitter.removeListener('Widget_Update', this.onWidgetUpdate);
}
render() {
return (
<View style={{flex: 1, justifyContent:'center', alignItems:'center'}}>
<Countdown
style={{marginTop: 80}} fontSize="40"
isBiertijd={this.props.isBierTijd}
timeLeft={this.props.timeLeft}
/>
</View>
)
}
}
const mapStateToPros = state => ({
fetching: state.bierTijd.fetching,
isBierTijd: state.bierTijd.isBierTijd,
nextBierTijd: state.bierTijd.next,
timeLeft: moment(state.bierTijd.next).diff(moment())
})
const mapDispatchToProps = dispatch => {
return bindActionCreators({...bierTijdActions,}, dispatch)
}
export default connect(mapStateToPros, mapDispatchToProps)(Home)
是否可以执行此操作,或者是否需要从主要活动触发事件?从原生到本土的反应的良好解释也将受到赞赏。
答案 0 :(得分:0)
绝对可以,您可以在这里找到指南:
您必须创建一个BroadcastReceiver(即WidgetProvider)和一个HeadlessJS任务来将两者通信。也许还有其他方法,但至少这个方法有效!