2011-06-28 275 views
1

這是我的源代碼。無法實例化錯誤?

public class MainActivity extends Activity { 
    private static String content; 
    private static String phone; 
    private String number; 
    private String message; 

    private BroadcastReceiver receiver = new BroadcastReceiver(){ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     //---get the SMS message passed in--- 
     Bundle bundle = intent.getExtras();   
     SmsMessage[] msgs = null; 

     if (bundle != null) 
     { 
      number = ""; 
      message = ""; 
      //---retrieve the SMS message received--- 
      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]);     
       number = msgs[i].getOriginatingAddress();      

       message = msgs[i].getMessageBody(); 


      } 
      //---display the new SMS message--- 
      Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 
      SendMe(); 
    } 
    } 


}; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    IntentFilter filter = new IntentFilter(); 
    registerReceiver(receiver, filter); 
    setContentView(R.layout.main); 



    } 


      public void SendMe(){ 


    PendingIntent pi = PendingIntent.getActivity(this, 0, 
       new Intent(this, MainActivity.class), 0); 
    SmsManager sms = SmsManager.getDefault(); 
    sms.sendTextMessage(number, null, message, pi, null); 

} 
} 

我不斷收到此錯誤的logcat的

06-28 17:11:23.241:ERROR/AndroidRuntime(1311): 了java.lang.RuntimeException:無法實例化接收機 COM .ftt.autospond.MainActivity:java.lang.ClassCastException: com.ftt.autospond.MainActivity

這裏是我的清單

<?xml version="1.0" encoding="utf-8"?> 

<application android:icon="@drawable/icon" android:label="@string/app_name"> 
    <activity android:name=".MainActivity" 
       android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
      <receiver android:name="com.ftt.autospond.MainActivity"> 
     <intent-filter> 
      <action android:name= 
       "android.provider.Telephony.SMS_RECEIVED" /> 

回答

1

請確保您的活動在您的androidmanefest.xml文件中註冊

編輯:你不能有你的接收器一樣,在您的清單中預先存在的類進行註冊。如果你在你的類動態地做到這一點,沒有必要把它在你的清單......那個拉出來接收器,看看是否有需要照顧它

+0

我補充說了。我貼我的表現在編輯的上方,你們可以看..也許我有一個問題在那裏。 – theITRanger22

+0

你不能有你的接收器進行註冊一樣,在你的清單,如果你這樣做動態你們班有沒有必要有它在你的清單... 扳指接收機出來,看看是否能照顧它 – Mutmatt

+0

@Mutmatt做到了!但唯一的問題是......沒有什麼事情發生在廣播接收器內部......當接收到文本時,不會顯示敬酒。它像它不知道它已經收到了一個文本。 – theITRanger22

1

寄存器的setContentView(R.layout.main)之後的接收器;

+0

它仍然強行關閉男人.. =( – theITRanger22

+0

什麼是「<接收機的android:name =「com.ftt.autospond.MainActivity」>「在您的清單xml。它是否存在,如果是的話,它是否擴展BroadcastReceiver。如果你不使用這個接收器,請從xml中刪除條目,你的錯誤應該去了。 –

相關問題