我想在本机反应中使用Google Sms验证api。在项目开始时,SMSReceiver使用SMSReceiverModule的上下文进行了初始化,但是当我收到短信时,SMSReceiver将再次在没有上下文的情况下进行初始化,并且如果我在SMSReceiver中删除空的构造函数,我的项目将崩溃。如何避免在秒时间内初始化SMSReceiver
public class SMSReceiver extends BroadcastReceiver {
private ReactApplicationContext mContext;
private static final String EVENT = "SMS_RECEIVED";
public SMSReceiver() {
}
public SMSReceiver(ReactApplicationContext context) {
mContext = context;
}
@Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch (status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
processMessage(message);
break;
case CommonStatusCodes.TIMEOUT:
break;
}
}
}
private void processMessage(String message) {
if (mContext == null) {
return;
}
if (!mContext.hasActiveCatalystInstance()) {
!hasActiveCatalystInstance", message);
return;
}
WritableNativeMap map = new WritableNativeMap();
map.putString("message", message);
mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(EVENT, map);
}
}
我的react模块如下所示:
public class SMSReceiverModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
private BroadcastReceiver mBroadcastReceiver;
private boolean isReceiverRegistered = false;
private Context _context;
public SMSReceiverModule(ReactApplicationContext context) {
super(context);
this._context = context;
mBroadcastReceiver = new SMSReceiver(context);
getReactApplicationContext().addLifecycleEventListener(this);
SmsRetrieverClient client = SmsRetriever.getClient(context);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Successfully started retriever, expect broadcast intent
// ...
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Failed to start retriever, inspect Exception for more details
// ...
}
});
}
private void registerReceiver() {
String filter = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) ?
Telephony.Sms.Intents.SMS_RECEIVED_ACTION :
"android.provider.Telephony.SMS_RECEIVED";
if (getCurrentActivity() != null) {
getCurrentActivity().registerReceiver(mBroadcastReceiver, new IntentFilter(filter));
isReceiverRegistered = true;
}
}
private void unregisterReceiver() {
if (isReceiverRegistered && getCurrentActivity() != null) {
getCurrentActivity().unregisterReceiver(mBroadcastReceiver);
isReceiverRegistered = false;
}
}
@Override
public String getName() {
return "SMSReceiverModule";
}
@Override
public void onHostResume() {
registerReceiver();
}
@Override
public void onHostPause() {
unregisterReceiver();
}
@Override
public void onHostDestroy() {
unregisterReceiver();
}
}