无法实例化错误?

时间:2011-06-28 17:18:48

标签: android sms broadcastreceiver

这是我的源代码。

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" /> 

    

2 个答案:

答案 0 :(得分:1)

在setContentView(R.layout.main);

之后注册接收器

答案 1 :(得分:1)

确保您的活动已在您的androidmanefest.xml文件中注册

编辑:您不能让您的接收器在清单中的预先存在的类中注册。如果你在课堂上动态地进行操作,则无需在你的清单中使用它...将接收器拉出来,看看它是否能解决它