代码之家  ›  专栏  ›  技术社区  ›  Mr. B.

应用类后台服务

  •  1
  • Mr. B.  · 技术社区  · 6 年前

    我想经营一家 但在我之后 阅读文档 我有点困惑。

    SDK版本27 ,这意味着我不能 BroadcastReceiver AndroidManifest.xml 并且需要在 Application 班级, 阿法克 .)

    在我开始之前 IntentService 广播接收机 ,我首先使用 PendingIntent ,它是由 AlarmManager onCreate() .

    它起作用了,但我不确定那是不是 良好做法

    服务应该运行 永远 并启动它自己的线程进行操作,这些操作最多需要一分钟,完成后再运行一次(+5秒)。

    服务目的伪码

    MyService // starts on Application creation an runs "forever"
        threads = []
        itemIds = []
    
        async loop manageThreads // start / kill
            itemIds = getItemIdsFromDatabase()
    
            loop itemIds vs threads
                if noThreadRunningForCurrentItemId
                    threads.push(new ItemThread(itemId).start())
    
    
            loop threads vs itemIds
                if threadRunsForNoneExistingItemId
                   threads[currentItemId].kill()
    
            sleep(20000) // manage threads every 20 seconds
    
    
        ItemThread(int itemId)
            doSomething()
            sleep(5000) 
            ItemThread(itemId) // restart thread every 5 seconds
    

    我想避免这个服务被Android杀死,阻塞其他线程或者导致内存泄漏。

    这个用例的最佳实践是什么,知道吗?

    java应用程序

    public class App extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            // Start MyService to run in the background
            Intent service = new Intent(this, MyService.class);
            this.startService(service);
        }
    }
    

    public class MyService extends IntentService {
        public MyService() { 
            super("MyService") 
        }
    
        @Override
        protected void onHandleIntent(@Nullable Intent intent) {       
            try {
                int i = 0;
                while(true) {
                    Log.d("MyService", "i = " + String.valueOf(i));
                    i++;
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }              
        }
    }
    
    0 回复  |  直到 6 年前