1

BatteryPostonCreate メソッドのアラームマネージャーによってクラスが呼び出されるようにしようとしています。

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 に答える