I want to develope a receiver class which will listen Phone state. And I want to work on doSomething() using incoming phone number.
And my need is that my receiver should work between some time interval (like 12:30PM to 01:00PM), other than this time interval my receiver should not work.
What I did yet :
This is my BroadcastReceiver class :
public class MyTest extends BroadcastReceiver {
protected AudioManager audioManager;// = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
protected Context context;
private ITelephony telephonyService;
@Override
public void onReceive(Context context, Intent intent) {
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
this.context = context;
String action = intent.getAction();
if(action.equalsIgnoreCase("android.intent.action.PHONE_STATE")){
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
//Incoming call
doSomething(intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
}
}
else {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage message = SmsMessage.createFromPdu((byte[])pdus[0]);
if(!message.isEmail())
doSomething(message.getOriginatingAddress());
}
}
}
And I am using it as in my activity :
registerReceiver(new MyTest(), new IntentFilter("android.intent.action.PHONE_STATE"));
In manifest I declaired it as
<receiver android:name=".MyTest"></receiver>
Problem :
Its working if my application is running on foreground, but when I closes my application its not working. I didn't write any code on onPause() or other methods of Activity life cycle.
开发者_开发知识库What am I doing wrong? Is there any other way to this?
Register your receiver in your manifest file like this:
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
精彩评论