私のアプリケーションには、100000msごとにhtmlページに「開始」または「停止」という単語がある場合、ウェブサーバーをチェックし続けるインテントサービスがあります。Androidインテントサービスのロケーションリスナー
「開始」を受信した場合はlocationmanager.requestUpdateLocation(..)
を開始し、「停止」を受信した場合はlocationmanager.removeUpdates(..)
で停止します。
しかし、私はこの問題を持っている:私はlocationmanager.requestUpdateLocation(..)
を呼び出すとき
私は、リスナーのonLocationChanged
(それはサービスの同じスコープで実装されます)に入力しないでください。
私はインテントサービスが永遠に生きていないことを確認しています。(私は、Androidが起動して起動する瞬間をキャプチャするレシーバーを設置しています。ユーザーがそれは自分自身を再起動します:P
しかし、それはそれは死ぬ数時間(または多分わずか30分)の後、永遠に住んでいることはありません:(
ここでは、コード理由:?は
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("Service", "Started");
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//IT NEVER ENTER HERE
Log.i("LOC", "LAT: " + location.getLatitude() +" LONG: "+location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
//NEVER ENTER ALSO HERE
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
int localizzazioneAttiva=0;
int delay = 0;
while (true) {
Log.i("SERVICE_CheckSito", "Check Sito STARTED");
String inputLine = "";
StringBuffer stringBuffer = new StringBuffer();
//Check Permission and SKD_INT
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED)
{
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
URL url;
try
{
url = new URL("http://www.sito.com/file.html");
HttpURLConnection httpURLConnection;
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
try {
while ((inputLine = bufferedReader.readLine()) != null) {
stringBuffer.append(inputLine).append("\n");
}
} finally {
bufferedReader.close();
}
}
} catch (IOException e) {
// e.printStackTrace();
}
} else return;
}
if (stringBuffer.toString().equals("start\n") && 0==localizzazioneAttiva)
{
localizzazioneAttiva=1;
delay = 1000;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, 0, locationListener);
}
if(stringBuffer.toString().equals("stop\n")) {
delay = 2000;
locationManager.removeUpdates(locationListener);
localizzazioneAttiva=0;
}
Log.i("SERVICE_CheckSito", "Message from server: " + stringBuffer.toString());
Log.i("SERVICE_CheckSito", "Check Sito FINISHED");
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
アラームを使用するのはどうですか? https://developer.android.com/training/scheduling/alarms.html –