我必须不断运行服务,直到我的应用程序被卸载,在此服务中,我必须每隔一分钟连续发送lat long值
问题是我的服务只运行了几天,因为它正在摧毁我没有得到我错误的地方
我的活动..........
使用闹钟管理器调用我的服务
public void SrartService() {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(MAinActivity.this, BootReciver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MAinActivity.this, 7, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar StartTime = Calendar.getInstance();
Log.d("trackin", "tracking here");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, StartTime.getTimeInMillis(), 1000 * 60 * 60, pendingIntent);
}
.......我的BootReciver
public void onReceive(Context context, Intent intent) {
...
context.startService(new Intent(context,LongService.class));
..}
我的长期服务................
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("first launch", "first oncreate launch");
dbHandler = new DbHandler(LongService.this);
buildGoogleApiClient();
createLocationRequest();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "KiteEye Tracking is Destroyed Please Open it Again ", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
SharedPreferences bb = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Saved_Vehicle_ID = bb.getString("VehicleId", "");
VehicleName = bb.getString("VehicleName", "");
handler.postDelayed(new Runnable() {
public void run() {
Count = Count + 1;
insertDB(str1, str2, date);
if (isConnectingToInternet(LongService.this)) {
SendOfflineLatLongToServer();
}
Log.e(TAG, "count" + Count);
Log.e(TAG, "(running.!!!!!!!)" + Saved_Vehicle_ID + Saved_interval);
Log.e(TAG, "(Cuurent location.!!!!!!!)" + Current_Address + Saved_interval);
if (Count >=60) {
Log.e(TAG, "count reached to Maximum ");
if(Current_Address!=null) {
if (date1 != null) {
sendMessageToActivity(getApplicationContext(), Current_Address, date1);
KeyguardManager km = (KeyguardManager) getApplicationContext()
.getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km
.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getApplicationContext()
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
Count = 0;
}
}
}
sendMessageToActivity(getApplicationContext(), Current_Address, date1);
handler.postDelayed(this, 60000);
}
}, 60000);
}
private static void sendMessageToActivity(Context context, String loc, String time) {
Intent intent = new Intent("CurrentLocation");
Bundle b = new Bundle();
b.putString("Location", loc);
b.putString("Time", time);
intent.putExtra("Location", b);
intent.putExtra("Time", b);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
private void insertDB(String str1, String str2, String date) {
...
}
String S_id, S_lat, S_lon, S_time;
private void SendOfflineLatLongToServer() {
...
}
public void SendLatLongToServer(final String _mid, final String lat, final String lon, final String time) {
...
}
public static boolean isConnectingToInternet(Context _context) {
.....
}
public synchronized void buildGoogleApiClient() {
...
}
/**
* Creating location request object
*/
public void createLocationRequest() {
..
}
protected void startLocationUpdates() {
..
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
..
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
// Displaying the new location on UI
displayLocation();
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 7);
if (addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String address1 = addresses.get(0).getSubLocality();
String address2 = addresses.get(0).getLocality();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(address);
stringBuilder.append(",");
stringBuilder.append(address1);
stringBuilder.append(",");
stringBuilder.append(address2);
Current_Address = stringBuilder.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
str1 = String.valueOf(latitude);
str2 = String.valueOf(longitude);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date CuurentTime = new Date(mLastLocation.getTime());
date = format.format(CuurentTime);
DateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date CuurentTime1 = new Date(mLastLocation.getTime());
date1 = format1.format(CuurentTime1);
Log.d(TAG, "location" + str1 + "\t" + str2);
Log.d(TAG, "location" + "date and time" + date);
app_preferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
editor = app_preferences.edit();
editor.putString("date", date);
editor.putString("CurrentAddress", Current_Address);
editor.commit();
MyApplication.getInstance().getPrefManager().setTime(date);
MyApplication.getInstance().getPrefManager().setCurrentLocation(Current_Address);
// if (Count==0) {
// sendMessageToActivity(getApplicationContext(), Current_Address, date);
// }
} else {
Log.e(TAG, "(Couldn't get the location. Make sure location is enabled on the device)");
}
}
private void displayLocation1() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
str1 = String.valueOf(latitude);
str2 = String.valueOf(longitude);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date CuurentTime = new Date(mLastLocation.getTime());
date = format.format(CuurentTime);
Log.d(TAG, "loc" + str1 + "\t" + str2);
Log.d(TAG, "loc" + "date & time" + date);
insertDB(str1, str2, date);
} else {
Log.e(TAG, "(Couldn't get the location. Make sure location is enabled on the device)");
}
}
public void removeDB(String id) {
...
}
答案 0 :(得分:0)
正如@PratikDasa指出的那样,Android可能会不时清理长时间运行的后台服务以回收系统资源。因此,如果您需要在后台持续运行服务,请实施方法onStartCommand
。从当前的onStart
方法中删除完整的代码并放入onStartCommand
(OnStart
已被弃用。) onStartCommand
必须返回一个值,这就是诀窍所在。从中返回START_STICKY
。您可以在Android Service API
当您从START_STICKY
返回onStartCommand
时,您基本上会要求Android系统在每次停止后显式重启您的服务。现在您可以在上面的链接上阅读一些警告。所有警告中最重要的一点是,当系统显式重新启动您的服务时,传递的意图可能为NULL(除非有一些意图等待启动服务),因此您应该在代码中相应地处理它们。
进行这些更改并进行一些基本测试。我希望事情应该正常。