当我有一个在后台运行的服务/应用程序被杀后,我收到错误。但是在OPPO,VIVO,MIUI设备中无效。关闭唤醒锁定,onTaskRemoved。完成所有设置自动启动,电池,安全等
public class MyService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = MyService.class.getSimpleName();
GoogleApiClient mLocationClient;
LocationRequest mLocationRequest = new LocationRequest();
private PowerManager mPowerManager;
private PowerManager.WakeLock mWakeLock;
public Location location;
public static final long INTERVAL = 20000;//variable to execute services every 10 second
private Handler mHandler = new Handler(); // run on another Thread to avoid crash
private Timer mTimer = null; // timer handling
public static final String ACTION_LOCATION_BROADCAST = MyService.class.getName() + "LocationBroadcast";
public static final String EXTRA_LATITUDE = "extra_latitude";
public static final String EXTRA_LONGITUDE = "extra_longitude";
DataBaseHandler dataBaseHandler;
private static final int MY_NOTIFICATION_ID = 1;
NotificationManager notificationManager;
Notification myNotification;
public static Location mCurrentLocation, lStart, lEnd;
double speed;
@Override
public void onCreate() {
// cancel if service is already existed
if (mTimer != null)
mTimer.cancel();
else
mTimer = new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, INTERVAL);// schedule task
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
dataBaseHandler = new DataBaseHandler(getApplicationContext());
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
EventBus.getDefault().unregister(this);
EventBus.getDefault().register(this);
mLocationRequest.setSmallestDisplacement(9);
mLocationRequest.setInterval(2000);
mLocationRequest.setFastestInterval(1000);
// onTaskRemoved(intent);
int priority = LocationRequest.PRIORITY_HIGH_ACCURACY; //by default
//PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER are the other priority modes
mLocationRequest.setPriority(priority);
mLocationClient.connect();
//Make it stick to the notification panel so it is less prone to get cancelled by the Operating System.
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* LOCATION CALLBACKS
*/
@Override
public void onConnected(Bundle dataBundle) {
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.
Log.d(TAG, "== Error On onConnected() Permission not granted");
//Permission not granted by user so cancel the further execution.
return;
}
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
Log.d(TAG, "Connected to Google API");
} catch (Exception e) {
}
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(getApplicationContext(), "Location off", Toast.LENGTH_LONG).show();
Log.d(TAG, "Connection suspended");
}
//to get the location change
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Location changed");
if (location != null) {
this.location = location;
mCurrentLocation = location;
if (lStart == null) {
lStart = mCurrentLocation;
lEnd = mCurrentLocation;
} else {
lEnd = mCurrentLocation;
}
updateUI(location);
Preferences.getInstance(getApplicationContext()).setLatitude(String.valueOf(location.getLatitude()));
Preferences.getInstance(getApplicationContext()).setLongitude(String.valueOf(location.getLongitude()));
Log.d(TAG, "== location != null");
String lat = String.valueOf(location.getLatitude());
String lng = String.valueOf(location.getLongitude());
if (FlightModeReceiver.isFlight()) {
return;
}
if (!GpsReceiver.isGps(this)) {
return;
}
}
if (Preferences.getInstance(this).getService().equals("1")) {
showNotification();
}
}
public String CompareTime(String strTimeToCompare)
{
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
Calendar cal = Calendar.getInstance();
int dtHour;
int dtMin;
int iAMPM;
String strAMorPM = null;
Date dtCurrentDate;
try {
Date TimeToCompare = sdf.parse(strTimeToCompare);
dtMin = cal.get(Calendar.MINUTE);
dtHour = cal.get(Calendar.HOUR);
iAMPM = cal.get(Calendar.AM_PM);
if (iAMPM == 1)
{
strAMorPM = "pm";
}
if (iAMPM == 0)
{
strAMorPM = "am";
}
dtCurrentDate = sdf.parse(dtHour + ":" + dtMin + " " + strAMorPM);
// Toast.makeText(getApplicationContext(), String.valueOf(dtCurrentDate),Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), String.valueOf(TimeToCompare),Toast.LENGTH_LONG).show();
if (dtCurrentDate.after(TimeToCompare))
{
return "1";
}
if (dtCurrentDate.before(TimeToCompare))
{
return "2";
}
if (dtCurrentDate.equals(TimeToCompare))
{
return "3";
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "4";
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(getApplicationContext(), "Location off", Toast.LENGTH_LONG).show();
Log.d(TAG, "Failed to connect to Google API");
}
private void updateUI(Location location) {
speed = location.getSpeed() * 18 / 5;
// Toast.makeText(getApplicationContext(),String.valueOf(lStart.distanceTo(lEnd)-lEnd.getAccuracy()),Toast.LENGTH_LONG).show();
if (lStart.distanceTo(lEnd)-lEnd.getAccuracy()>0&&lStart.distanceTo(lEnd)>9) {
Preferences.getInstance(getApplicationContext()).setDistance(String.valueOf(Double.valueOf(Preferences.getInstance(getApplicationContext()).getDistance()) + (lStart.distanceTo(lEnd) / 1000.00)));
Main2Activity.endTime = System.currentTimeMillis();
try {
Main2Activity.tempDist.setText(new DecimalFormat("#.##").format(Double.valueOf(Preferences.getInstance(getApplicationContext()).getDistance())) + " Km.");
} catch (Exception e) {
}
lStart = lEnd;
Main2Activity.startTime = Main2Activity.endTime;
}
}
private void showNotification() {
try {
myNotification = new NotificationCompat.Builder(this)
.setContentTitle("mTrack")
.setContentText(String.valueOf(new DecimalFormat("#.##").format(Double.valueOf(Preferences.getInstance(getApplicationContext()).getDistance())) + " Km."))
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
// .setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.mtrack_icon)
.build();
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
} catch (Exception e) {
}
}
答案 0 :(得分:0)
要在应用程序在后台运行服务,您需要指定该服务应保留在前台:
df = df[df['a b'] == 5]
正如文件所述:
注意:如果您的应用针对API级别26或更高级别,系统会强制执行 当应用程序本身没有时,运行后台服务的限制 在前台。在大多数情况下,您的应用应该使用 预定的工作。
我不知道上述说明是否适用于您的用例