【发布时间】:2018-10-24 10:49:40
【问题描述】:
我在使用 android 服务时遇到问题。当应用程序启动时它工作正常,但如果应用程序被最小化,并且服务被破坏,当我重新打开应用程序时,我无法再次启动服务。
这里是activity中的oncreate和onstart:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//Activates the custom toolbar
setSupportActionBar(toolbar);
ActionBarDrawerToggle navigationDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(navigationDrawerToggle);
navigationDrawerToggle.syncState();
//Checks first item in the navigation drawer initially
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.fragment_camera);
//Open camera fragment initially when the app starts.
if (savedInstanceState == null) {
fragmentInterface = new FotoapparatFragment();
replaceFragment(fragmentInterface);
}
setupConnectionToService();
Intent backgroundReceiptService = new Intent(this, ReceiptService.class);
startService(backgroundReceiptService);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, ReceiptService.class);
bindService(intent, receiptConnection, Context.BIND_AUTO_CREATE);
Log.d(MAIN_LOG, "Binded With ReceiptService");
}
这里是服务中的onStartCommand:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
receiptDatabase = ReceiptDatabase.getInstance(getApplicationContext());
//Checks if the permission to use external storage on the phone has been granted
if (PermissionUtil.checkPermission(getApplicationContext(), PermissionUtil.Permissions.EXTERNAL_READ) == PackageManager.PERMISSION_GRANTED) {
callLatestReceiptData(null);
initializeFileObserver();
listInitialized = true;
}
//TODO: Needs to moved elsewhere, but are not sure where
new Thread(new Runnable() {
@Override
public void run() {
Period period = new Period();
period.setMPeriodId(1);
receiptDatabase.daoAccessPeriod().insertNewPeriod(period);
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
【问题讨论】:
-
这与重新启动应用程序有什么关系?最小化它与终止它不同
-
不,但是当应用程序最小化足够长的时间时,服务中的 onDestroy 会被调用,然后当我从最小化状态打开应用程序时,我似乎无法再次启动服务
标签: java android service minimize