【问题标题】:Background service后台服务
【发布时间】:2014-07-22 14:42:26
【问题描述】:

我想创建一个在后台记录数据的小应用程序。所以我尝试使用绑定服务。这工作正常,但如果我关闭应用程序,服务也会停止。
所以,我的问题是:通过即时服务执行此操作是否是一种好方法? 以及如何在应用关闭时保持服务在后台运行(我也想在启动后启动它)?

【问题讨论】:

标签: android service background


【解决方案1】:

你可以试试这个:

public class ServiceBackground extends Service {


    @Override
    public IBinder onBind( final Intent arg0 ) {
        return null;
    }

    @Override
    public void onCreate() {

        final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1 ); // Number of threads keep in the pool

        executor.scheduleAtFixedRate( new Runnable() {

            @Override
            public void run() {

                Log.i( "LocalService", "service running" );

                if (stopCondition == true ) {
                    executor.shutdownNow();
                }

            }
        }, 1, 1000, TimeUnit.MILLISECONDS );
        super.onCreate();
    }

    @Override
    public int onStartCommand( final Intent intent, final int flags, final int startId ) {
        return Service.START_STICKY;
    }

}

记得在AndroidManifest.xml中注册服务

更多关于ScheduledThreadPoolExecutor的信息

启动服务

public class MainActivity extends Activity {

    @Override
    protected void onCreate( final Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        this.setContentView( R.layout.activity_main );

        this.startService( new Intent( this, ServiceBackground.class ) );

    }

}

【讨论】:

【解决方案2】:

在系统应用程序上查看this link

如果应用程序不是系统应用程序,Android 可以在内存不足的情况下销毁进程,这包括服务。否则,请查看 startForeground() 以获取应用程序服务。

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2013-02-19
    • 2015-08-16
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多