我想發送短信當電池電量達到Service
的特定值時。我沒有收到任何錯誤,但SMS未被髮送。Android從服務中發送短信?
我的代碼:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class BatteryStatus extends Service {
int scale = -1;
int level = -1;
int voltage = -1;
int temp = -1;
String batteryNumber = "";
String moderate=" Battery Level is 50 ";
String low = "Battery Level is low. Need to be charged immediately";
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(),"Service Running", Toast.LENGTH_SHORT).show();
//BATTERY STATUS
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
Log.e("BatteryManager", "level is "+level+"/"+scale+", temp is "+temp+", voltage is "+voltage);
Log.e("NumberBattery ", "Number is "+batteryNumber);
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, filter);
if(batteryNumber!=null && level==49){
SmsManager bat = SmsManager.getDefault();
bat.sendTextMessage(batteryNumber,null,moderate,null,null);
}else if(batteryNumber!=null && level==20){
SmsManager bat = SmsManager.getDefault();
bat.sendTextMessage(batteryNumber, null,low, null, null);
}
}
}
的logcat:
03-09 03:41:40.390: E/BatteryManager(11086): level is 49/100, temp is 321, voltage is 7574
03-09 03:41:40.390: E/NumberBattery(11086): Number is
你能告訴什麼是錯的她呢?
笑,你不明白你自己的代碼...'如果(batteryNumber = NULL &&水平== 49!)'中的onCreate – Selvin 2012-03-09 13:10:32
被叫只有一次發送短信的代碼應該在你的BroadcastReceiver中,例如您打印的地方登錄。 – zapl 2012-03-09 13:10:55