后台服务始终运行

时间:2019-02-26 11:29:06

标签: java android web-services

我有一些代码可以创建后台服务,使其始终正常工作。
该应用程序销毁后,该服务将正常运行。 我测试了20多个代码示例,并且此代码可在模拟器中运行,但无法在我的手机棉花糖android 6中运行。

这是我的应用程序的服务文件

public class locationService extends Service implements LocationListener {
    private LocationManager _locMgr;
    com.parse.groupbox.tools.locationTools loc;
    Random RND = new Random();
    Timer timer = new Timer();

    @Override
    public void onCreate() {
        super.onCreate();
        loc = new com.parse.groupbox.tools.locationTools(this);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        try {
            gpsSetup();
            timer.cancel();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    updateGps();
                }
            }, 5000, 10);
        } catch (Exception ex) {
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            gpsSetup();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    updateGps();
                }
            }, 5000, 10);
        } catch (Exception ex) {
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
        return Service.START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        try {
            gpsSetup();
            timer.cancel();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    updateGps();
                }
            }, 5000, 10);
        } catch (Exception ex) {
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(this, "task service start", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            gpsSetup();
            timer.cancel();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    updateGps();
                }
            }, 5000, 10);
        } catch (Exception ex) {
            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
        Toast.makeText(this, "service destroyed", Toast.LENGTH_SHORT).show();
    }

    public void gpsSetup() {
        try {
            _locMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
            Criteria locationCriteria = new Criteria();
            locationCriteria.setAccuracy(Criteria.ACCURACY_FINE);
            locationCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
            String locationProvider = _locMgr.getBestProvider(locationCriteria, true);
            if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            _locMgr.requestLocationUpdates(locationProvider, 1, 1, this);

            Toast.makeText(this, "start service", Toast.LENGTH_SHORT).show();
        }
        catch (Exception Ex)
        {
            Toast.makeText(this, Ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public void updateGps(){
        try{
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            String locationProvider = LocationManager.NETWORK_PROVIDER;
            _locMgr.requestLocationUpdates(locationProvider, 1, 1, this);
        }catch (Exception Ex){
            Toast.makeText(this, Ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        int result = RND.nextInt(100);
        if(result > 30){
            try{
                loc.LocationSyncToServer(location);
                Toast.makeText(this, "location", Toast.LENGTH_LONG).show();
            }catch (Exception Ex){
                Toast.makeText(this, Ex.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

请阅读我的代码并给我答案以解决它。

这是运行服务的代码:

Intent background = new Intent(getApplicationContext(),   com.parse.groupbox.services.locationService.class);
startService(background);

2 个答案:

答案 0 :(得分:2)

尝试

将此代码放在您要停止服务的位置

Intent intent = new Intent(getApplicationContext(),com.parse.groupbox.services.locationService.class);
intent.setAction(Constants.ACTION.STOPTFOREGROUND_ACTION);
stopService(intent);

在您的服务中onStartCommand()

if(intent.getAction()==Constants.ACTION.STOPTFOREGROUND_ACTION){
 stopForeground(true);
 stopSelf();
 }

创建一个常量类

public class Constants {
public interface ACTION {
  String STOPFOREGROUND_ACTION = "com.package.packageName.action.stopforeground";
   }
 }

答案 1 :(得分:0)

Android M引入了Doze和App Standby,它们限制了后台服务以节省电池。可以在here android开发者网站上找到如何处理Doze的方法。