2016-03-30 6 views
1

SMSからOTPを自動検出し、EditTextでOTPを入力しようとしています。私はレシーバサービスを通してこれをアーカイブしようとしていますが、それはEditText(etLastOtp)を自動的に満たすのではなく、「それはヌルです」というログを与えています。ここで AndroidでSMSを自動検出する

は私のサービスクラスです:

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.support.v4.content.LocalBroadcastManager; 
import android.telephony.SmsMessage; 
import android.util.Log; 

public class SmsListener extends BroadcastReceiver { 

    public OnSmsReceivedListener listener = null; 
    public Context context; 

    public SmsListener() 
    { 

    } 

    public void setOnSmsReceivedListener(Context context) { 
     Log.d("Listener","SET"); 
     this.listener = (OnSmsReceivedListener) context; 
     Log.d("Listener","SET SUCCESS"); 
    } 

    public interface OnSmsReceivedListener { 
     public void onSmsReceived(String otp); 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 

     if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){ 
      Bundle bundle = intent.getExtras();   //---get the SMS message passed in--- 
      SmsMessage[] msgs = null; 
      String msg_from; 
      if (bundle != null){ 
       //---retrieve the SMS message received--- 
       try{ 
        Object[] pdus = (Object[]) bundle.get("pdus"); 
        msgs = new SmsMessage[pdus.length]; 
        for(int i=0; i<msgs.length; i++){ 
         msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
         msg_from = msgs[i].getOriginatingAddress(); 
         String msgBody = msgs[i].getMessageBody(); 

         Log.d("MsgBody", msgBody); 

          String otpSMS=msgBody.substring(36,36+4); 


         if (listener != null) { 
          listener.onSmsReceived(otpSMS); 
         } 
         else 
         { 
          Log.d("Listener", "Its null"); 
         } 

        } 
       }catch(Exception e){ 
        Log.d("Exception caught", e.getMessage()); 
       } 
      } 
     } 
    } 
} 

そして、ここに私のActivityクラスです:

import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.support.v4.content.LocalBroadcastManager; 
import android.support.v7.app.AppCompatActivity; 
import android.telephony.PhoneStateListener; 
import android.telephony.SmsMessage; 
import android.telephony.TelephonyManager; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageButton; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gms.analytics.GoogleAnalytics; 
import com.google.android.gms.analytics.HitBuilders; 
import com.google.android.gms.analytics.Tracker; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.HashMap; 

public class MobileVerifySMS extends AppCompatActivity implements SmsListener.OnSmsReceivedListener { 

    ImageButton btnBack; 
    private boolean mIsInForegroundMode; 

    Button btnVerify; 
    String userName,email,password,currency,role,isind,timeZone; 
    TextView tvTryAgain; 
    public EditText etLastOTP; 
    String lastOTP; 
    Button btnSkip; 
    TLConstants tlConstants; 
    DatabaseHandler databaseHandler; 
    TLAPI tlapi; 

    private SmsListener receiver; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_mobile_verifysms); 

     receiver = new SmsListener(); 
     receiver.setOnSmsReceivedListener(this); 


     btnBack=(ImageButton)findViewById(R.id.btnBack); 

     etLastOTP=(EditText)findViewById(R.id.etOtpEnd); 
     btnVerify=(Button)findViewById(R.id.btnVerify); 
     btnSkip=(Button)findViewById(R.id.btnSkip); 
     tvTryAgain=(TextView)findViewById(R.id.tryAgain); 

     btnVerify.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       if(etLastOTP.getText().toString().length()==4) { 

//verify otp 
       } 
       else 
       { 
        Toast.makeText(getApplicationContext(),"Enter 4 digit OTP",Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }); 

     mIsInForegroundMode=true; 
    } 

    @Override 
    public void onSmsReceived(String otp) { 
     try 
     { 
      etLastOTP.setText(otp); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 


    @Override 
    protected void onPause() { 
     super.onPause(); 

     mIsInForegroundMode = false; 
    } 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     mIsInForegroundMode = true; 

    } 

    @Override 
    public void onBackPressed() { 
     super.onBackPressed(); 
     this.finish(); 
     overridePendingTransition(R.anim.hj_enter_left_anim_2, R.anim.hj_exit_left_anim); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_mobile_verify, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 
+0

36 + 4の代わりに40を直接書き込むことはできませんか? –

+0

@VivekMishra - それを40に変更しましたが、それは問題ではありません。 –

+0

私は知っているが、他の人が理解しやすいようにできるだけ簡単にコードを投稿しようとしている。 –

答えて

2

あなたのBroadcastReceiverを登録する任意のコードが表示されませんので、私は行くつもりですあなたはSMSの受信時に起動するBroadcastReceiverのマニフェストエントリに<intent-filter>を追加したと推測します。これはあなたの問題を説明するでしょう。

あなたBroadcastReceiverため<intent-filter>を持っている場合は、SMSを受信したときに、Androidは自動的にBroadcastReceiverの新しいインスタンスを作成し、その新しいインスタンスにonReceive()を呼び出します。このインスタンスは、Androidによって作成されたもので、リスナーが設定されていません。

この問題を解決するには、<intent-filter>をマニフェストから削除し、作成後にBroadcastReceiverを動的に登録する必要があります。 Activityでは、BroadcastReceiverを作成した後、registerReceiver()に電話してください。受け取るブロードキャストIntentを記述するIntentFilterを作成する必要があります。

+1

Bravo!あなたは私の一日を救った!これはうまくいった!ありがとう@ダビッド。 –

関連する問題