几分钟后服务会自动停止 [英] service automatically stops after several minutes

查看:67
本文介绍了几分钟后服务会自动停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个服务,该服务应在活动处于后台以及整个应用程序被销毁时起作用.

I'm creating a service which should work when the activity is in background as well as when the whole application is destroyed.

我每隔1分钟调用一次服务中的位置坐标.

I'm calling location coordinates in the service at every 1 minute interval.

但是,当我尝试这样做时,该服务会在12-15分钟后自动关闭.

However, when I try to do so, the service shuts down automatically just after 12-15 minutes.

我希望该服务能够持续工作,直到并且除非它被用户交互活动的完成所破坏.

I want the service to work endlessly until and unless it is destroyed by the completion of activity on user interaction.

我的服务类别如下:

public class SensorService extends Service {
    public int counter=0; 
    public static final int NINTY_SECONDS = 90000; 
    public static Boolean isRunning = false;
    public LocationManager mLocationManager;
    public Get_Coordinates mLocationListener;
    public GetSharedPreference sharedPreference;
    @Override
    public void onCreate() {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new Get_Coordinates(getApplicationContext());
        sharedPreference = new GetSharedPreference(getApplicationContext());
        startTimer();
        super.onCreate();
    }
    public SensorService(Context applicationContext) {
        super();
        Log.i("HERE", "here I am!");
    }

    public SensorService() {
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "ondestroy!");
        Intent broadcastIntent = new Intent("com.android.startBgService");
        broadcastIntent.putExtra("abc","abcd");
        sendBroadcast(broadcastIntent);
        stoptimertask();
    }

    private Timer timer;
    private TimerTask timerTask;
    long oldTime=0;
    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, NINTY_SECONDS, NINTY_SECONDS); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
               // Log.i("in Etro Sendor", "in timer ++++  "+ (counter++));
                if (Check_Internet_Con.isConnectingToInternet(getApplicationContext())) {

                    if (!isRunning) {
                        startListening();
                    }
                    try {
                        if (sharedPreference.getActiveUserId() > 0) {
                            mLocationListener.getLocation();
                            mLocationListener.insertCoordinatesInSqlite();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void startListening() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener, Looper.getMainLooper());

            if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener,Looper.getMainLooper());
        }
        isRunning = true;
    }
}

这是我的清单

<service
           android:name="com.lunetta.etro.e_tro.SensorService"
           android:enabled="true"></service>
       <service
           android:name="com.lunetta.etro.e_tro.SecondService"
           android:enabled="true" >
       </service>

       <receiver
           android:name=".SensorRestarterBroadcastReceiver"
           android:enabled="true"
           android:exported="true"
           android:label="RestartServiceWhenStopped">
           <intent-filter>
               <action android:name="com.android.startBgService" />
               <action android:name="android.intent.action.BOOT_COMPLETED" />
           </intent-filter>
       </receiver>

这是SensorRestarterBroadcastReceiver类

And Here is SensorRestarterBroadcastReceiver class

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
        context.startService(new Intent(context, SensorService.class));
        
    }
}

推荐答案

是的,它将停止工作,查看Google发布的新文档,它彻底改变了位置的电池性能,是的,它具有很大的优势.对性能的影响我已经完全改变了我的非常具体的任务.还要停止使用其他声称其工作错误的存储库

Yes it will stop working, check out the new Docs put up by Google, It has changed completely how location works for battery performance, and yes it having a big deal effect on performance i have changed my completely for the very specific task. Also stop using other repos that do claim that they work are wrong

通过Google检查新的更新文档

Check the new updated docs by google

https://developer.android.com/training/building-location.html

我实现您的相同要求的最佳方法是,并且可以在大约60k的设备中运行,并且可以完美地工作,具体取决于Android API的版本(使用JobService以及23和更高版本的背景服务).相应地使用LocationProvider API和Location provider Client API.

The best way I implemented your same requirement is and is live in over about 60k devices and working flawlessly is With depending on Version of Android API using JobService with 23 and higher and lower with Background service. Have use LocationProvider API and Location provider Client API accordingly.

根据我的个人经验,我会说这是一种老式的代码,它会在数小时内耗尽设备电池的电量,现在我的代码几乎没有什么用了,它一整夜只消耗了15%的总电量.那就是消费的巨大变化.

with personal experience i will say this The old style of code use to drain the device battery in few hours, now my code is hardly making a dent, its consuming only like 15 percent overnight overall usage. thats a big change in consumption.

这篇关于几分钟后服务会自动停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆