2014-01-24 4 views
1

ЭТО ОШИБКА: Метод getBroadcast(Context, int, Intent, int) в типе PendingIntent не применяется для аргументов (new View.OnClickListener(){}, int, Intent, int) ошибкаОШИБКА в смс отправки

вот код из MainActivity.java:

import android.app.Activity; 
    import android.os.Bundle; 
    import android.provider.Telephony.Sms; 
    import android.telephony.SmsManager; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.Toast; 
    import android.app.PendingIntent; 
    import android.content.BroadcastReceiver; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.content.IntentFilter; 
    public class MainActivity extends Activity 

    { 
    Button btnSendSMS; 
    EditText txtPhoneNo; 
    EditText txtMessage; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main);   

     btnSendSMS = (Button) findViewById(R.id.btnSendSMS); 
     txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); 
     txtMessage = (EditText) findViewById(R.id.txtMessage); 

     btnSendSMS.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      {     
       String phoneNo = txtPhoneNo.getText().toString(); 
       String message = txtMessage.getText().toString();     
       if (phoneNo.length()>0 && message.length()>0)     
        sendSMS(phoneNo, message);     
       else 
        Toast.makeText(getBaseContext(), 
         "Please enter both phone number and message.", 
         Toast.LENGTH_SHORT).show(); 
      } 


      private void sendSMS(String phoneNo, String message) { 
      String SENT = "SMS_SENT"; 
      String DELIVERED = "SMS_DELIVERED"; 

      PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0); // <--- THIS IS WHERE I GET THE ERROR 

      PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0); // <--- THIS IS WHERE I GET THE ERROR 

      // ---when the SMS has been sent--- 
      registerReceiver(new BroadcastReceiver() { 
       @Override 
       public void onReceive(Context arg0, Intent arg1) { 
        switch (getResultCode()) { 
         case Activity.RESULT_OK: 
          Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show(); 
          break; 
         case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 
          Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show(); 
          break; 
         case SmsManager.RESULT_ERROR_NO_SERVICE: 
          Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show(); 
          break; 
         case SmsManager.RESULT_ERROR_NULL_PDU: 
          Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); 
          break; 
         case SmsManager.RESULT_ERROR_RADIO_OFF: 
          Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show(); 
          break; 
        } 
       } 
      }, new IntentFilter(SENT)); 

      // ---when the SMS has been delivered--- 
      registerReceiver(new BroadcastReceiver() { 
       @Override 
       public void onReceive(Context arg0, Intent arg1) { 
        switch (getResultCode()) { 
         case Activity.RESULT_OK: 
          Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show(); 
          break; 
         case Activity.RESULT_CANCELED: 
          Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show(); 
          break; 
        } 
       } 
      }, new IntentFilter(DELIVERED)); 

      SmsManager sms = SmsManager.getDefault(); 
      sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI); 
     } 

    }); 
} 

}


Я пытаюсь отправить расписание автоматической рассылки sms, но я не буду далеко ходить с этими ошибками. Помощь PLEAS.

+1

У вас возникла проблема с передачей вашего контекста, как говорит ошибка. это происходит в onClickListener по какой-то причине, попробуйте заменить его с помощью getApplicationContext() –

ответ

3

У вас возникла проблема с передачей вашего контекста, как говорит ошибка. Заменить это с помощью getApplicationContext()

PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(SENT), 0); 

    PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(DELIVERED), 0); 

Просто замените эти 2 линии!

Update:

Я просто попытался это и это сработало!

package com.sm.mrecruit.activity; 

import android.app.Activity; 
import android.app.PendingIntent; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.telephony.SmsManager; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 


public class MainActivity extends Activity 

{ 
Button btnSendSMS; 
EditText txtPhoneNo; 
EditText txtMessage; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main);   

btnSendSMS = (Button) findViewById(R.id.btnSendSMS); 
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo); 
txtMessage = (EditText) findViewById(R.id.txtMessage); 

btnSendSMS.setOnClickListener(new View.OnClickListener() 
{ 
    public void onClick(View v) 
    {     
     String phoneNo = txtPhoneNo.getText().toString(); 
     String message = txtMessage.getText().toString();     
     if (phoneNo.length()>0 && message.length()>0)     
      sendSMS(phoneNo, message);     
     else 
      Toast.makeText(getBaseContext(), 
       "Please enter both phone number and message.", 
       Toast.LENGTH_SHORT).show(); 
    } 


    private void sendSMS(String phoneNo, String message) { 
    String SENT = "SMS_SENT"; 
    String DELIVERED = "SMS_DELIVERED"; 

    PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(SENT), 0); // <--- THIS IS WHERE I GET THE ERROR 

    PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(DELIVERED), 0); // <--- THIS IS WHERE I GET THE ERROR 

    // ---when the SMS has been sent--- 
    registerReceiver(new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      switch (getResultCode()) { 
       case Activity.RESULT_OK: 
        Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 
        Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_NO_SERVICE: 
        Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_NULL_PDU: 
        Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_RADIO_OFF: 
        Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show(); 
        break; 
      } 
     } 
    }, new IntentFilter(SENT)); 

    // ---when the SMS has been delivered--- 
    registerReceiver(new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context arg0, Intent arg1) { 
      switch (getResultCode()) { 
       case Activity.RESULT_OK: 
        Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show(); 
        break; 
       case Activity.RESULT_CANCELED: 
        Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show(); 
        break; 
      } 
     } 
    }, new IntentFilter(DELIVERED)); 

    SmsManager sms = SmsManager.getDefault(); 
    sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI); 
} 

}); 
} 

Thats it! Попробуй это !

+0

. Я заменил обе строки. но я все равно получаю ту же ошибку – Chisah

+0

Работает на моем конце! Проверить обновленный код –

+0

Это уже не так. Спасибо. Но теперь у меня новая проблема. Он не посылает и не показывает тосты. – Chisah

0

Проблема такая же для обеих линий. Метод getBroadcast() ожидает контекста как первого аргумента. Когда вы вызываете этот метод, вы находитесь внутри анонимного внутреннего класса, в этом случае класс onClickListener. Когда вы предоставили ключевое слово в качестве первого аргумента, this относится к классу onClickListener. Вместо этого вам нужно захватить контекст приложения, в котором вы сейчас находитесь, и предоставить этот метод. Вы можете добиться этого, изменив ошибку, вызывающую такие строки.

PendingIntent sentPI = PendingIntent.getBroadcast(MainActivity.getApplication(), 0, new Intent(SENT), 0); 
PendingIntent deliveredPI = PendingIntent.getBroadcast(MainAcitivty.getApplication(), 0, new Intent(DELIVERED), 0); 

Заменить this с MainActivity.getApplication().

+0

Я заменил обе строки. но я все равно получаю те же ошибки – Chisah

+0

Являются ли ошибки все еще на тех же строках? Если да, проверьте мой обновленный ответ. – csmckelvey

+0

сейчас нет. Но это не отправка. – Chisah

Смежные вопросы