我的应用程序有一个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 –