我的應用程序有一個Intent服務,如果每隔100000ms在html頁面上有「開始」或「停止」單詞,它會一直檢查Web服務器。Android Intent服務的位置監聽器
如果它收到「開始」,它將啓動一個locationmanager.requestUpdateLocation(..)
,如果它收到「停止」,它將以locationmanager.removeUpdates(..)
停止它。
但我有這樣的問題:當我打電話locationmanager.requestUpdateLocation(..)
我從來沒有進入
我的聽衆的onLocationChanged
(即在相同的服務範圍來實現)。
然後,我觀察到我的Intent服務不會永遠生活:(我把一個接收器捕獲Android啓動並啓動它的時刻(以及這項工作),以及一個當我的Intent服務關閉時用戶將重新啓動自己: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 –