在最小化应用程序然后再次将其打开后,如何再次启动服务?

时间:2018-10-24 10:49:41

标签: java android service minimize

我对android中的服务有疑问。在启动该应用程序时它可以正常工作,但是如果将该应用程序最小化并且该服务被破坏了,那么当我重新打开该应用程序时,我将无法再次启动该服务。

这是活动中的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);
}

3 个答案:

答案 0 :(得分:0)

使用ServiceConnection。

playerIntent = new Intent(ActPlayMusic.this, MusicPlayerService.class);

                    startService(playerIntent);
                    bindService(playerIntent, mConnection, Context.BIND_AUTO_CREATE);


  private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            MusicPlayerService.LocalBinder binder = (MusicPlayerService.LocalBinder) service;
            try {
                playerService = binder.getServiceInstance();
                playerService.registerClient(ActPlayMusic.this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
    }
};




 @Override
    protected void onResume() {
          bindService(playerIntent, mConnection, Context.BIND_AUTO_CREATE);
        super.onResume();
    }
    @Override
    protected void onStop() {
        unbindService(mConnection);
        super.onStop();
    }

答案 1 :(得分:0)

好,因此在您的Service类中,您需要重写onStartCommand()并返回标志START_STICKY,这将重新启动您的服务。有关更多信息,请访问有关此服务主题的Android开发人员页面。

Opening /dev/ttyS2 at 115200 bauds (N, 8, 1)
Connected
[01][03][00][00][00][05][85][C9]
Waiting for a confirmation...
ERROR Connection timed out: select
Error reading registers: Connection timed out

答案 2 :(得分:0)

我认为您想从后台开始服务,对吧?我已经使用这种方法来完成我的跟踪要求。

您可以将BroadcastReceiverService一起使用。在服务中 onStartCommand 上使用return Service.START_STICKY

onDestroy onTaskRemoved 中,您可以编写以下发送开始广播的接收器[在kotlin中]。

override fun onTaskRemoved(rootIntent: Intent?) {
    super.onTaskRemoved(rootIntent)
    Log.e("Api service on Task Removed Send Location Service")
    if (Global.getPreference(Constant.IS_USER_LOGIN, false)!!) {
        val broadcastIntent = Intent("com.myapp.project.restartSendLocationService")
        sendBroadcast(broadcastIntent)
    }
}

在接收器中,您可以按照[在Kotlin中的说明]再次启动服务。

class SendLocationReceiver : BroadcastReceiver() {

override fun onReceive(_context: Context?, intent: Intent?) {
    if (_context != null) {
        val context = _context.applicationContext
        val intentDemo = Intent(_context.applicationContext, SendLocationService::class.java)
        Log.e("Smart Sales", "UpdateLocationService \$status")
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                context.startService(intentDemo)
            } else {
                context.startForegroundService(intentDemo)
            }
        } catch (e: Exception) {
            Log.e("Smart Sales", e.toString())
        }
    }
}

}

别忘了添加清单。

<receiver
        android:name=".ServiceStuff.kotlin.SendLocationReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.myapp.project.restartSendLocationService" />
        </intent-filter>
    </receiver>

注意:在某些自定义OS服务中,该服务不会在后台运行。