如何保持登录抛出活动?

发布于 2024-10-03 02:48:48 字数 84 浏览 0 评论 0原文

我在我的主要活动中进行登录。 如果登录正确,我想查看我的个人资料并从服务器下载一些数据,但如果我更改活动,我将无法保持连接。

我该怎么做?

I make login in my main activity.
If the login is correct, I wanna see my profile and download some data from server, but I cannot keep the connection, if I change activity.

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幸福不弃 2024-10-10 02:48:48

一旦您验证登录正确(通过测试与服务器的连接并
身份验证),您可以将登录详细信息存储在 SharedPreferences 或类似的内容中。

然后,您可以使用这些登录详细信息发出后续请求(无论您处于哪个活动)。当然,这是假设服务器接受这种方式的身份验证。

Once you verify the login is correct (by testing the connection to the server and
authenticating), you can store the login details in SharedPreferences or something similar.

Then you can just make subsequent requests using those login details (no matter which activity you are in). This is, of course, assuming the server accepts authentication this way.

风尘浪孓 2024-10-10 02:48:48

您还可以使用服务。服务是通过“活动”运行的长时间运行的后台任务。

在您的登录表单中,您可以发送类似于启动新活动的 startService 意图。这会调用 Service 类上的 onStartCommand ,您可以在其中创建连接并将其存储在 Service 对象本身中。当您需要来自连接的信息时,可以使用 bindService 调用获取服务实例。

下面是一个改编自 Google 基本示例的基本登录服务示例。

public class LocalService extends Service {

    private MyConnection conn;

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent i = new Intent("my.service.connected");
        try {
            conn = new MyConnection(
                intent.getStringExtra("username"),
                intent.getStringExtra("password"));
            i.putExtra("succeeded", true);
            sendBroadcast(i);
        } catch (ConnectionException ex) {
            i.putExtra("succeeded", false);
            sendBroadcast(i);
        }
        return START_STICKY;
    }

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

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();
}

Android.Manifest.xml 还需要 内的 元素。

但服务也有其缺点。通常,您应该在 Intent 中传递启动参数,这意味着它们需要可序列化或可打包。这会阻止您在活动中创建连接、检查登录是否成功并将其发送到服务。* 相反,您需要将登录参数发送到服务并在那里执行登录。

当您需要确定连接是否成功并且您应该继续执行下一个活动,或者如果连接失败并且您应该显示一条错误消息时,就会出现复杂的情况。有多种解决方案,但它们都需要一些设置。特别是当您考虑到用户可能在按“登录”和实际登录之间暂停您的活动时。

如上所示,一种选择是通过从服务发送广播来通知活动。下面是启动上述服务并收听广播的活动。以下活动未考虑活动可能随时暂停的可能性。

public class LoginActivity extends Activity {
    class MyReceiver extends BroadcastReceiver {
        @Override
        public final void onReceive(Context ctx, Intent i) {
            if (i.getBooleanExtra("succeeded", false)) {
                startMyMainActivity();
            } else {
                showErrorMessage();
            }
        }
    }
    private BroadcastReceiver bcReceiver;

    private void doLogin(String username, String password) {
        // Register receiver that listens for connected messages.
        bcReceiver = new MyReceiver();
        IntentFilter ifilter = new IntentFilter("my.service.connected");
        registerReceiver(bcReceiver, ifilter);

        // Send command to start service (connects)
        Intent i = new Intent(this, LocalService.class);
        i.putExtra("username", username);
        i.putExtra("password", password);
        startService(i);
    }

    @Override
    protected void onPause() {
        if (bcReceiver != null) unregisterReceiver(bcReceiver);
        super.onPause();
    }
}

当活动应该优雅地处理暂停的活动时,您应该在共享变量中跟踪其状态。如果它之前处于跟踪服务的状态,则它应该绑定到服务并在恢复时检查其状态。如果服务仍在连接(而不是连接或断开连接),则应重新注册广播侦听器。

You could also use a Service. Services are long running background tasks that live through Activities.

In your login form you could send a startService intent similar to starting a new activity. This calls onStartCommand on the Service class where you can create the connection and store it in the Service object itself. When you require information from the connection, you can acquire the service instance using bindService call.

Below is an example of a basic login service adapted from Google's basic example.

public class LocalService extends Service {

    private MyConnection conn;

    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent i = new Intent("my.service.connected");
        try {
            conn = new MyConnection(
                intent.getStringExtra("username"),
                intent.getStringExtra("password"));
            i.putExtra("succeeded", true);
            sendBroadcast(i);
        } catch (ConnectionException ex) {
            i.putExtra("succeeded", false);
            sendBroadcast(i);
        }
        return START_STICKY;
    }

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

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();
}

The Android.Manifest.xml also needs <service android:name="LocalService"></service> element inside the <application />.

Services don't come without their downsides though. Generally you should pass the startup parameters in an Intent which means they need to be serializable or parcelable. This prevents you from creating the connection in your Activity, checking that login succeeded and sending it the service.* Instead you need to send the login parameters to the service and perform the login there.

The complications come when you need to resolve whether the connection succeeded and you should proceed to the next activity or if it failed and you should show an error message. There are several solutions, but all of them require some setup. Especially when you consider that the user may pause your activity between pressing 'Login' and actually logging in.

As shown above, one option is to notify the activity by sending broadcasts from the Service. Below is an activity that launches the above service and listens to the broadcasts. The below activity does not take into account the possibility that the activity may be paused at any moment.

public class LoginActivity extends Activity {
    class MyReceiver extends BroadcastReceiver {
        @Override
        public final void onReceive(Context ctx, Intent i) {
            if (i.getBooleanExtra("succeeded", false)) {
                startMyMainActivity();
            } else {
                showErrorMessage();
            }
        }
    }
    private BroadcastReceiver bcReceiver;

    private void doLogin(String username, String password) {
        // Register receiver that listens for connected messages.
        bcReceiver = new MyReceiver();
        IntentFilter ifilter = new IntentFilter("my.service.connected");
        registerReceiver(bcReceiver, ifilter);

        // Send command to start service (connects)
        Intent i = new Intent(this, LocalService.class);
        i.putExtra("username", username);
        i.putExtra("password", password);
        startService(i);
    }

    @Override
    protected void onPause() {
        if (bcReceiver != null) unregisterReceiver(bcReceiver);
        super.onPause();
    }
}

When the Activity should handle paused activity gracefully you should keep track of its state in a shared variable. If it was previously in a state where it tracked the Service it should bind to the Service and check its state when resuming. If the service is still connecting (as opposed to connected or disconnected) it should re-register the broadcast listener.

风月客 2024-10-10 02:48:48

我想知道为什么你需要保持连接。也许您可以重新打开连接并再次登录?

但如果您确实需要保持连接打开:您可以在应用程序中保持连接。但请确保当用户离开您的应用程序时关闭连接!我真的不推荐这个。或者设置关闭连接的超时时间,例如 5 分钟不活动后。

http://developer.android.com/reference/android/app/Application.html

您必须在 AndroidManifest 中说明您的应用程序使用哪个应用程序。
http://developer.android.com/guide/topics/manifest /application-element.html#nm(参见 andriod:name)。

然后你可以通过:getApplication()从activity中获取应用程序。不要忘记投射它。然后添加可以登录的功能等等。

编辑:

更详细一点:

您必须创建一个扩展应用程序的类。您在清单中的应用程序的 android:name 中输入的此类名称。在该类中,您可以编写用于处理连接的函数。像:startConnection() doLogin() stopConnection() ...在您调用的活动中:

NameOfYouApplication app = (NameOfYouApplication) getApplication();
app.startConnection();
app.doLogin();

有点像那样。但请注意,即使活动关闭,您的应用程序仍将保持活动状态。你最好找个合适的时间来关闭连接。

I wonder why you need to keep the connection. Maybe you can just reopen the connection and login again?

But if you really need to keep the connection open: You could can keep the connection in the Application. But make sure you close the connection when the user goes away from your app! I really don't recommend this. Or set a timeout for the connection to be closed like after 5 minutes of inactivity.

http://developer.android.com/reference/android/app/Application.html

You will have to say in the AndroidManifest which Application your App uses.
http://developer.android.com/guide/topics/manifest/application-element.html#nm (see andriod:name).

Then you can get the application from the activity through: getApplication(). Don't forget to cast it. Than add functions where you can login and so on.

Edit:

A little more detailed:

You will have to create a class extending Application. The name of this class you enter in the android:name of the application in the manifest. In that class you write functions with which you handle the connection. Like: startConnection() doLogin() stopConnection() ... In the Activities you call:

NameOfYouApplication app = (NameOfYouApplication) getApplication();
app.startConnection();
app.doLogin();

kind of like that. But beware that even if the Activity is closed your Application will stay alive. You better find a good time to close the connection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文