繁体   English   中英

某些设备上的Android复制服务

[英]Android duplicating service in some devices

我正在开发一个使用服务的简单计时表应用程序(即使该应用程序已关闭,它也可以使计时表保持运行状态)。

计时码表逻辑由服务处理,而我的Fragment仅绑定到服务以获取数据。 我的问题是,当我启动计时器并关闭应用程序时。 当我再次打开它时,计时器将绑定到该服务的新实例,因此它认为它没有运行。

这仅发生在我测试过的一台设备中(在模拟器中,其他四台设备也可以正常工作)。 怎么可能发生?

这是一些代码:

片段onStart

public void onStart() {
    super.onStart();
    Intent intent = createServiceIntent();
    getActivity().startService(intent);
    getActivity()
        .bindService(
            intent,
            mServiceConnection,
            Context.BIND_ABOVE_CLIENT
        );

}

服务构造函数onCreateonStartonBindonUnbind

public ChronometerService() {
    Log.d(Config.APP_TAG, "CREATING CHRONOMETER SERVICE INSTANCE");
}

@Override
public void onCreate()
{
    super.onCreate();
    this.mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    this.mBinder = new ChronometerBinder();
    this.mPauses = new LinkedList<>();
}

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

@Override
public IBinder onBind(Intent intent) {
    Log.d(Config.APP_TAG, "SERVICE BIND. AND WAS" + (mRunning ? "" : "N'T") + " RUNNING");
    if( ! mRunning ) {
        this.mPauseLength = 0;
        this.mStoppedAt = 0;
        this.mBase = 0;
    }
    return mBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    if( ! mRunning) {
        stopForeground(true);
        stopSelf();
    }
    return true;
}

在“片段”中点击“开始”按钮时,将调用服务中的以下方法:

public void start() {
    if(this.mBase == 0) {
        reset();
        this.mBase = now();
    }else{
        mPauseLength += now() - mStoppedAt;
    }
    Intent i = new Intent(this, MainActivity.class);
    i.putExtra(MainActivity.CURRENT_FRAGMENT, MainActivity.CHRONOMETER_TAG);
    PendingIntent intent = PendingIntent.getActivity(this, SERVICE_ID, i, PendingIntent.FLAG_UPDATE_CURRENT);

    mNotificationBuilder = new NotificationCompat.Builder(this);
    mNotificationBuilder.setContentTitle(getResources().getString(R.string.chronometer_title))
        .setSmallIcon(R.drawable.ic_timer_white_48dp)
        .setContentIntent(intent);

    Notification n = mNotificationBuilder.build();
    startForeground(SERVICE_ID, n);
    mRunning = true;
    update();
}

在应用运行正常的设备中,在日志中,我得到:

CREATING CHRONOMETER SERVICE INSTANCE
SERVICE BIND. AND WASN'T RUNNING
(Closing the app)
SERVICE BIND. AND WAS RUNNING

在设备中不起作用,我得到:

CREATING CHRONOMETER SERVICE INSTANCE
SERVICE BIND. AND WASN'T RUNNING
(Closing the app)
CREATING CHRONOMETER SERVICE INSTANCE
SERVICE BIND. AND WASN'T RUNNING

希望您能够帮助我。

解决了:

毕竟问题不是我的代码。 问题是净化

这正在杀了我。 将我的应用添加到白名单后,问题得以解决。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM