我想创建一个小应用程序,它在后台记录数据。所以我尝试了一次绑定服务。这很好,但是如果我关闭应用程序,服务也会停止。
所以,我的问题是:这是一种用即时服务来实现这个目标的好方法吗?当应用程序关闭时,我如何保持服务在后台运行(我也想在引导后启动它)?
发布于 2014-07-22 15:25:02
你可以试试这个:
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 ) );
}
}发布于 2014-07-22 15:03:09
查看系统应用程序上的此链接。
如果应用程序不是系统应用程序,那么Android可以在内存不足的情况下破坏进程,这包括服务。否则,签出应用程序服务的startForeground()。
https://stackoverflow.com/questions/24890459
复制相似问题