這裏是我的源代碼和它保持強制關閉,每次我運行它...如何註冊廣播接收器?
public class MainActivity extends Activity {
private static String content;
private static String phone;
private String number;
private String message;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(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();
}
}
}, null);
}
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 14:39:00.331: ERROR/AndroidRuntime(396): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ftt.autospond/com.ftt.autospond.MainActivity}: java.lang.NullPointerException
06-28 14:39:00.331: ERROR/AndroidRuntime(396): at android.app.ActivityManagerProxy.registerReceiver(ActivityManagerNative.java:1504)
06-28 14:39:00.331: ERROR/AndroidRuntime(396): at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:807)
06-28 14:39:00.331: ERROR/AndroidRuntime(396): at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:318)
06-28 14:39:00.331: ERROR/AndroidRuntime(396): at com.ftt.autospond.MainActivity.onCreate(MainActivity.java:29)
當你問一個力關閉它確實有助於包括與異常堆棧跟蹤 – antlersoft
@antlersoft我剛纔編輯上面的代碼,包括logcat中的logcat的。一探究竟。謝謝 – theITRanger22