I want to check the SIM state every time android device start
I'm writing an app开发者_运维知识库lication to automatically sends an SMS when I replace my existing SIM card with a new SIM card. I can use the subscriber id of the SIM card to check this but how I check it every time android device start. thanks...
Write a startup broadcast receiver. This runs every time the device starts up. Add the following intent to your manifest:
<receiver android:name=".StartupReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
with something like the following code:
public class StartupReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(...);
context.startActivity(intent );
}
}
dhaag23's answer covers how to set up a startup receiver. However, it doesn't mention that the application must have Boot Complete permission, or anything about your SIM card requirement
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
For checking the SIM card value, I've set up to store the device's phone number in an app setting. Note that this can be cleared by the user in teh app settings, and you must carefully handle the case of first initialization. If you detect a mismatch from the current phone number and the previously stored value in the setting, then you can conclude that it is a new SIM.
Here's the method I use to get the current phone #:
public static String getPhoneNumber(Context context) {
TelephonyManager phoneManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = phoneManager.getLine1Number();
return phoneNumber;
}
Method for getting SIM serial.
public static String getSimSerialNumber(Context context) {
TelephonyManager phoneManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = phoneManager.getSimSerialNumber();
return phoneNumber;
}
If there is a way to explicitly check the prescence of a new / missing SIM card, I am not sure what it is. The method I have above for getting the phone number apparently isn't reliable on all carriers. Also, getting the SIM serial only works on SIM card phones.
精彩评论