【问题标题】:Auto Logout Users in AndroidAndroid中的自动注销用户
【发布时间】:2016-12-27 12:06:08
【问题描述】:

我看过几个例子,但我不知道我做错了什么。

Auto logout after 15 minutes due to inactivity in android

看了那个例子之后,我创建了一个扩展 Service 的 LogoutService 类。另外,我是否还必须有一个调用我的登录活动的意图?像这样的:

Intent intent = new Intent(getBaseContext(), LoginActivity.class);
startActivity(intent);

我的 LogoutService 类

public class LogoutService extends Service {
public static CountDownTimer timer;
private final String TAG="Service";
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        timer = new CountDownTimer(1 * 60 * 1000, 1000) {
            public void onTick(long millisUntilFinished) {
                //Some code
                Log.v(TAG, "Service Started");
            }

            public void onFinish() {
                Log.v(TAG, "Call Logout by Service");
                // TODO should I create an Intent
                // my Login method here?
                stopSelf();
            }
        };
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

把它放在我所有的其他类中:

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    try {
        LogoutService.timer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    LogoutService.timer.cancel();
}

但由于以下原因,我不断收到空指针异常 LogoutService.timer.cancel();

我用一个 if 语句包围它,检查它是否为空,但没有任何反应,不知道我应该做什么。

【问题讨论】:

    标签: android


    【解决方案1】:

    由于LogoutService.timer.cancel()得到空指针异常;

    因为LogoutService 扩展了Service 类但没有使用startService 方法启动它,所以onCreate 方法没有被调用并且timernull

    执行以下操作:

    1. 使用startServicestopService 方法启动/停止服务

    2. onDestory() of Service 中取消计时器。

    3. LogoutService 类添加为AndroidManifest.xml 中的服务

    【讨论】:

    • 启动/停止方法应该去哪里?在 LogoutService 类中?另外,为什么是 onDestroy 而不是 onStop?
    • @Spider:代替LogoutService.timer.start();LogoutService.timer.cancel();
    • 不确定那会做什么。所以只是创建一个这样的新方法并调用它? public void startService() { Logout.timer.start(); }
    • 嘿,你能解释一下你的意思吗?还是想不通
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多