0

我有一个儿童应用程序,我想阻止他们访问电话功能。它不必坚如磐石,只需避免意外退出即可。

我使用的方法是启动一个服务来监视我的 Activity 何时失去焦点,然后重新启动它。我在这里遵循了指南:

http://nathanael.hevenet.com/android-dev-detecting-when-your-app-is-in-the-background-across-activities/

这个想法是您的活动在 onStart 中绑定到服务,并在 onStop() 期间取消绑定。当最后一个活动解除绑定时,在服务中调用 onUnbind,我从中重新启动活动。

继承人的活动:

public class GameActivity extends Activity {

    @Override
    public void onStart() {
        super.onStart();
        // Next call always returns true
        bindService( new Intent( this, LockService.class ),
                mConnection, Context.BIND_AUTO_CREATE );
    }

    @Override
    public void onStop() {
        super.onStop();
        unbindService( mConnection );
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected( ComponentName cn, IBinder service ) {}
        public void onServiceDisconnected( ComponentName cn ) {}
    };
}

这是服务:

public class LockService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        refocus();
    }

    private void refocus() {
        // Launch the monitored Activity
        Intent intent = new Intent(getBaseContext(), GameActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public boolean onUnbind( Intent intent ) {
        // Relaunch
        refocus();
        return false;
    }

    @Override
    public IBinder onBind( Intent intent ) {
        return mBinder;
    }

    public class LocalBinder extends Binder {
        LockService getService() {
            return LockService.this;
        }
    }

    private final IBinder mBinder = new LocalBinder();
}

这有效,但只有一次。当 GameActivity 关闭或最小化时, LockService.onUnbind 被调用。

这会重新启动 GameActivity,它会再次尝试绑定到服务。它返回 true,但 LockService.onBind 不会再次发生,因此 LockService.onUnbind 不会在 Activity 停止时发生。链接丢失。

现在,我肯定已经完成了这项工作,但我改变了一些东西并把它弄坏了。也许我重新启动活动的方式?我希望我能在它工作时将它检查到 SVN 中!

感激地收到任何帮助。

谢谢

编辑:这是我从 MenuActivity 启动服务的方式:

public static void StartLockService() {
    Context context = getApplicationContext();
    Intent intent = new Intent(context, LockService.class);
    context.startService(intent);
}
4

1 回答 1

0

好的,我明白了,感谢Android 服务:onBind(Intent) 和 onUnbind(Intent) 只调用一次

看起来我需要从 onUnbind 返回 true 以表明我想要 onRebind 通知。

然后我可以在 onRebind 中重新关注我的应用程序。

于 2014-04-11T12:40:04.233 回答