android - 几分钟后服务自动停止

标签 android broadcastreceiver android-service timertask

我正在创建一个服务,该服务应该在 Activity 在后台以及整个应用程序被销毁时正常工作。

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

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

我希望该服务无休止地工作,直到且除非它因用户交互 Activity 的完成而被破坏。

我的服务类如下:

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;
    }
}

这是我的 list

<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 类

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));
        
    }
}

最佳答案

https://developer.android.com/guide/components/bound-services.html

“绑定(bind)服务通常仅在为另一个应用程序组件提供服务时存在,并且不会无限期地在后台运行。”

要使其无限期运行,您需要将服务绑定(bind)到无限期存在的 UI 组件。您可以使用 Android 通知。这是一个前台服务。

https://developer.android.com/guide/components/services.html#Foreground

关于android - 几分钟后服务自动停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090007/

相关文章:

java - 如何指定android窗口大小

android - 将位图传递给在 logcat 上获取消息的其他 Activity FAILED BINDER TRANSACTION

android - 我为什么要使用绑定(bind)服务?

android - 如何在 Android 中的 Activity 之间共享套接字类实例?

android - BroadcastReceiver 上下文注册不起作用

android - 如何在多线程中处理服务

java - Android 1.5 和 dom4j - 属性名称解析不正确

android - 如何在没有外部应用程序的情况下打开/显示 pdf?

Android:为什么我没有收到 BOOT_COMPLETED Intent ?

android:来自市场 Activity 的响应