I am creating just a simple android app which will respond to received. I am using braodcastreceiver to receive sms. Code for activity is
package com.om;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
public class MyTest extends Activity {
public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
/** Called when the activity is first created. */
BroadcastReceiver smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context _context, Intent _intent) {
System.out.println("SMS Received");
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(SMS_RECEIVED);
registerReceiver(smsReceiver, filter);
}
}
When I run this activity on SDK 2.1 AVD and sends SMS to that port it says Force close. Please tell me what is error in code. 开发者_StackOverflow中文版Thanks in advance.
Hi Thanks for Answers This code works fine
package com.om;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
public class MyTest extends Activity { public class SmsReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
String msg = "SMS Received.....";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, msg, duration);
toast.show();
}
}
public static final String SMS_RECEIVED =
"android.provider.Telephony.SMS_RECEIVED";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter inf = new IntentFilter(SMS_RECEIVED);
SmsReceiver sr = new SmsReceiver();
registerReceiver(sr, inf);
}
}
I have given permissions correctly. But when i tried to register broadcastreceiver in Manifest It force closing the app, I don't know how to give Logs, if someone please tell me.
Did you remember to give it the proper permission?
I believe for SMS in your manifest, you must have something like:
android.permission.RECEIVE_SMS
精彩评论