package com.weatherdemo.Service;

import com.weatherdemo.DB.Config;
import com.weatherdemo.SMS.SimpleSms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver{
	private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(intent.getAction().equals(SMS_ACTION)){
			Bundle bundle = intent.getExtras();
			
			if(bundle != null){
				Object[] objects = (Object[])bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[objects.length];
				
				for(int i=0; i<objects.length; i++){
					messages[i] = SmsMessage.createFromPdu((byte[])objects[i]); 
				}
				
				String smsBody = messages[0].getDisplayMessageBody();
				String smsSenderString = messages[0].getDisplayOriginatingAddress();
				
				if(smsBody.trim().equals(Config.KeyWord) && Config.ProvideSmsService.equals("true")){
					SimpleSms simpleSms = new SimpleSms(smsSenderString, smsBody);
					WeatherService.RequerSMSService(simpleSms);
					Toast.makeText(context, "接收到服务请求短信", Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

}
