1

我一直在尝试让我的类BatteryPost在我的 onCreate 方法中被警报管理器调用:

BatteryPost.java:

public class BatteryPost extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    HttpClient httpclient = new DefaultHttpClient();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String batteryText = prefs.getString("battery", null);
    String id = prefs.getString("id", null);
    String URL = "http://mysite.com/checkin/index.php?device_uid="+id+"&bat="+batteryText; 
    {
    try{
    String uri = URL.replace(" ", "%20"); //replace spaces with %20
    Log.d("Checkin", uri);
    HttpPost httppost = new HttpPost(uri); //post object
    @SuppressWarnings("unused")
    HttpResponse response = httpclient.execute(httppost); //execution
    } catch (ClientProtocolException e) {
        Log.d("Checkin", "ClientProtocolException");
    } catch (IOException i) {
        Log.d("Checkin", "IOException");
    }
   }

 }
}

在我的 onCreate() 中应该被 AlarmManager 击中:

public void onCreate(Bundle savedInstanceState) {
        /*
         * Our onCreate block...
         */
        super.onCreate(savedInstanceState); 
        Context context = getApplicationContext();  
        setContentView(R.layout.activity_main);
        Button submit = (Button)findViewById(R.id.submitButton);
        submit.setOnClickListener(submitListener); //Initialization of the view and objects
        this.registerReceiver(this.mBatInfoReceiver, 
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, 1);
        Intent intent = new Intent(context, BatteryPost.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 600000, sender);

}

当我点击按钮时,我注册手动将电池电量更新到它工作的服务器,因此这些值被正确存储,但 AlarmManager 无法每分钟调用 BatteryPost(只是每分钟进行测试,之后会更长)。

我一直在查看 SO 上的其他帖子以尝试找到类似的代码,但实现这一点变得很棘手。

谢谢。

4

1 回答 1

1

我注意到的第一件事是你让它检查每600000毫秒。这不是 60 秒,而是 600 秒,也就是 10 分钟。这可能是问题吗?

于 2012-07-25T18:38:09.397 回答