当应用程序被杀时,它会终止服务。有没有办法让应用程序在Android nougat被杀死后在backgroud上运行服务。
请找到以下代码: 它适用于marshmellow。
package com.example.espl.pluzpluz.locationService;
import static android.support.v4.app.NotificationCompat.PRIORITY_MAX;
public class MyService extends Service
{
static final int NOTIFICATION_ID = 543;
public static boolean isServiceRunning = false;
SharedPreferences sharedPref;
JSONArray jsonArray;
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE =0 ;
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
sharedPref = getApplicationContext().getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String jsonString = sharedPref.getString(getString(R.string.jsonString),"");
try {
jsonArray=new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("lat",String.valueOf(location.getLatitude()));
jsonObject.put("long",String.valueOf(location.getLongitude()));
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(getString(R.string.jsonString),jsonArray.toString());
editor.commit();
System.out.println("jsonString"+jsonString);
}
@Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
if (intent != null && intent.getAction().equals("start_service")) { C.ACTION_START_SERVICE
startServiceWithNotification();
}else if(intent != null && intent.getAction().equals("stop_service")){
stopMyService();
}
return START_STICKY;
}
void stopMyService() {
stopForeground(true);
stopSelf();
isServiceRunning = false;
}
public void onCreate()
{
startServiceWithNotification();
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
void startServiceWithNotification() {
if (isServiceRunning) return;
isServiceRunning = true;
Intent notificationIntent11 = new Intent(this, DashboardActivity.class);
notificationIntent11.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent11.setAction("action_main");
notificationIntent11.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentPendingIntent11 = PendingIntent.getActivity(this, 0, notificationIntent11, 0);
Notification notification0 = new NotificationCompat.Builder(this)
.setGroup("12345")
.setGroupSummary(true)
.setContentIntent(contentPendingIntent11)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
android.R.drawable.ic_dialog_email))
.setContentTitle("Bundled Notifications Content Title")
.setContentText("Content Text for group summary")
.setStyle(new NotificationCompat.InboxStyle()
.setSummaryText("This is my inbox style summary."))
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
.setVibrate(new long[]{800, 800, 800, 800})
.setDefaults(Notification.DEFAULT_SOUND)
.setOngoing(true)
.setDeleteIntent(contentPendingIntent11)
.setPriority(PRIORITY_MAX)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification0.flags = notification0.flags | Notification.FLAG_NO_CLEAR;
notification0.flags |= Notification.FLAG_FOREGROUND_SERVICE;
notification0.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, notification0);
}
@Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}