打开许多应用时,服务停止工作

时间:2017-01-31 11:38:41

标签: android android-service

我只是使用这个简单的代码尝试Android中的服务:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(this, PlayerService.class));
}

PlayerService.java:

public class PlayerService extends IntentService
{
    public PlayerService()
    {
        super("PlayerService");
    }

    @Override
    protected void onHandleIntent(Intent i)
    {
        int n=0;
        while(true)
        {
            Log.i("SERVICE", "Event n." + n++);
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            { }
        }
    }

    @Override
    public void onDestroy()
    {
        Log.i("SERVICE", "Distr Service");
    }
}

我已在清单中声明了服务:

<service android:name="PlayerService"/>

当我启动此应用程序然后打开许多其他应用程序时,此应用程序停止工作(正如我在LogCat中看到的那样停止向我显示&#34;事件n ...&#34;)。为什么?

3 个答案:

答案 0 :(得分:0)

在Manifest中,声明像这样

<service
     android:name="Yourpackagename.PlayerService"
     android:enabled="true" />

由于

答案 1 :(得分:0)

使用Entity,而不是Service。根据文档,IntentService在操作完成时停止。有关IntentService的更多信息,请查看hereIntentService用于长期运行。看看here

答案 2 :(得分:0)

问题在于我必须使用前台服务。