微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我的 Moto G6 屏幕关闭时,我的后台服务停止

如何解决当我的 Moto G6 屏幕关闭时,我的后台服务停止

我创建了一个可以在我的 Moto G6 安卓设备上运行的应用。基本上,这个应用程序启动本地服务以定期访问网站。一切看起来都不错,但是当屏幕关闭时,服务会暂停。当屏幕打开时,它会再次激活。我在论坛和建议的内容中发现了很多关于这种行为的讨论,以下是我尝试过的:

  1. 我尝试将省电模式设置为关闭。结果相同。
  2. 我尝试使用 workmanager 而不是服务。我的工作人员也像我的服务一样暂停。
  3. 我尝试在我的服务中使用电源管理器来获取 PARTIAL_WAKE_LOCK,但它仍然没有改变任何东西。

Moto G6 有什么特别之处吗?...这是我的清单文件

?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.coininverst">
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.CoinInverst">
        <service android:name=".CoinGeckoService" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.CoinInverst.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我启动服务的方式(在主要活动中):

mServiceIntent = new Intent(this,CoinGeckoService.class);
startService(mServiceIntent);
bindService(mServiceIntent,Connection,Context.BIND_AUTO_CREATE);

仍在主要活动中,嵌套类:

private ServiceConnection Connection = new ServiceConnection()
{
    @Override
    public void onServiceConnected(ComponentName className,IBinder service)
    {
        // We've bound to LocalService,cast the IBinder and get LocalService instance
        CoinGeckoService.LocalBinder oBinder = (CoinGeckoService.LocalBinder) service;
        mService = oBinder.getService();
        mBound   = true;
    }

    @Override
    public void onServicedisconnected(ComponentName arg0)
    {
        mBound = false;
    }
};

服务端:

    public class CoinGeckoService extends Service
    {
        private Looper                        m_oServiceLooper     = null;
        private ServiceHandler                m_oServiceHandler    = null;
        private HandlerThread                 m_oHandlerThread     = null;
        private boolean                       m_bExitFlag          = false;
        private boolean                       m_bExitEcho          = false;
        private int                           m_iSnapshotPeriodSec = 300;
        private final IBinder                 m_oBinder            = new LocalBinder();
        private Intent                        m_oIntent            = null;
        private Thread                        m_oStillRunningProc  = null;
        private Message                       m_oHandleMessage     = null;
        private PowerManager                  m_oPowerManager      = null;
        private PowerManager.WakeLock         m_oWakeLock          = null;
        private Context                       m_oContext           = null;
    
        // Handler that receives messages from the thread
        private final class ServiceHandler extends Handler
        {
            public ServiceHandler(Looper oLooper)
            {
                super(oLooper);
            }
            @Override
            public void handleMessage(Message msg)
            {
                m_oHandleMessage = msg;
    
                m_oStillRunningProc = new Thread()
                {
                    public void run()
                    {
                        InfiniteProcees();
                    }
                };
                m_oStillRunningProc.start();
            }
        }
        private void InfiniteProcees()
        {
            while (!m_bExitFlag)
            {
                long lStartTimeMs         = System.currentTimeMillis();
                long lelapsedtimeMs       = 0L;
                long lWakeLockTimeoutMSec = 10 * 60 * 1000L;
    
                m_oWakeLock.acquire(lWakeLockTimeoutMSec);
    
    ....
    
                m_oWakeLock.release();
    
                lelapsedtimeMs = (System.currentTimeMillis() - lStartTimeMs);
    
                if ((m_iSnapshotPeriodSec * 1000) > (int)lelapsedtimeMs)
                    SleepMSec((m_iSnapshotPeriodSec * 1000) - (int)lelapsedtimeMs);
                //do
                //{
                //    SleepMSec(1000);
                //    lelapsedtimeMs = (System.currentTimeMillis() - lStartTimeMs);
                //}
                //while (!m_bExitFlag && (lelapsedtimeMs < (m_iSnapshotPeriodSec * 1000)));
            }
            // Stop the service using the startId,so that we don't stop
            // the service in the middle of handling another job
            stopSelf(m_oHandleMessage.arg1);
    
            m_bExitEcho = m_bExitFlag;
        }
    
        public void onCreate()
        {
            int iNbPage = 3;
            // Start up the thread running the service. Note that we create a
            // separate thread because the service normally runs in the process's
            // main thread,which we don't want to block. We also make it
            // background priority so cpu-intensive work doesn't disrupt our UI.
            m_oLogPath      = getExternalFilesDir(null) + "/CoinDBase" ;
            m_oImgPath      = getExternalFilesDir(null) + "/CoinImages";
            m_aoPages       = new String[iNbPage];
            m_oSyncExport   = new Object();
            m_oContext      = this;
            m_oPowerManager = (PowerManager)m_oContext.getSystemService(Context.POWER_SERVICE);
            m_oWakeLock     = m_oPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"CoinGeckoService:WakeLock");

....    
            m_oHandlerThread = new HandlerThread("ServiceStartArguments",Process.THREAD_PRIORITY_BACKGROUND);
            m_oHandlerThread.start();
    
            // Get the HandlerThread's Looper and use it for our Handler
            m_oServiceLooper  = m_oHandlerThread.getLooper();
            m_oServiceHandler = new ServiceHandler(m_oServiceLooper);
        }
    
        @Override
        public int onStartCommand(Intent intent,int flags,int startId)
        {
            Toast.makeText(this,"CoinGeckoService starting",Toast.LENGTH_SHORT).show();
    
            m_oIntent = intent;
    
            // For each start request,send a message to start a job and deliver the
            // start ID so we kNow which request we're stopping when we finish the job
            Message msg = m_oServiceHandler.obtainMessage();
            msg.arg1 = startId;
            m_oServiceHandler.sendMessage(msg);
    
            // If we get killed,after returning from here,restart
            return START_STICKY;
        }
    
        @Override
        public IBinder onBind(Intent intent)
        {
            return m_oBinder;
        }
    
        @Override
        public void onDestroy()
        {
            super.onDestroy();
    
            m_bExitFlag = true;
    
            int iTimeoutMsec = 2000;
            while (!m_bExitEcho && (iTimeoutMsec > 0) && SleepMSec(100))
            {
                iTimeoutMsec -= 100;
            }
            //Toast.makeText(this,"CoinGeckoService done",Toast.LENGTH_SHORT).show();
    
            Intent obroadcastIntent = new Intent();
            obroadcastIntent.setAction("RestartService");
            obroadcastIntent.setClass(this,ServiceRestarter.class);
            this.sendbroadcast(obroadcastIntent);
        }
        public class LocalBinder extends Binder
        {
            CoinGeckoService getService()
            {   // Return this instance of LocalService so clients can call public methods
                return CoinGeckoService.this;
            }
        }
    }

请注意,当应用程序关闭时,服务始终会停止。即使这不是预期的,但我现在可以接受。 每一个建议或评论将不胜感激。 提前致谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。