我想在 BroadCast receiver 類中獲取一個全局數據。
我用的下面的代碼,進入BroadCast receiver 類
public class Global extends Application{
String mobileNumber;
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
Receiver 類
public class TextMessageReceiver extends BroadcastReceiver{
Global global;
Context context;
int count;
String number;
public void onReceive(Context context, Intent intent)
{
global=(Global)context;
number = global.getMobileNumber();
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
if(msg.getOriginatingAddress().endsWith(number))
{
SMS.updateMessageBox(msg.getOriginatingAddress(),msg.getMessageBody(),context);
/*SMS.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody()+"\n");*/
/*((SMS) context).delete();*/
abortBroadcast();
}
}
}
我需要從 getter setter 獲取電話號碼,如何獲取?
把代碼 global=(Global)context;
改成 global=(Global)context.getApplication();
現在訪問 Global Class 的字段。