gpt4 book ai didi

java - 如何对 Android 中的所有 Activity 使用单一方法?

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:55 25 4
gpt4 key购买 nike

我正在使用websocket client我的应用程序。在主 Activity 中,我连接到 websocket 客户端并像抽象方法一样执行所有 onMessage、onOpen 操作。我还有两个 Activity ,称为“登录”和“注册” Activity 。我将登录 Activity 中的用户详细信息发送到服务器以进行验证。从服务器我正在 onMessage 抽象方法中的 MainActivity 中接收消息。我需要在登录 Activity 中使用该消息。请解释一下我该如何实现这一目标?如果我在这里重复我的问题,请原谅我并引导我找到正确的答案。

这是我的主要 Activity :

package org.asperohgedgetws.a7.hgadgetws;

import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;

import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;


public class MainActivity extends Activity implements View.OnClickListener {
Button bLogout;
public static TextView tvReceived;
UserLocalStore userLocalStore;
public static WebSocketClient mWebSocketClient;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
tvReceived = (TextView) findViewById(R.id.tvRecieved);

connectWebSocket();
}
@Override
protected void onStart() {
super.onStart();
if (authenticate()){
displayUserDetails();
} else{
Toast.makeText(getApplicationContext(), "Not Registered User :(", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this,Login.class));
}
}

private boolean authenticate(){
return userLocalStore.getUserLoggedIn();
}

private void displayUserDetails(){
User user = userLocalStore.getLoggedInUser();
}

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bLogout:
startActivity(new Intent(this,Login.class));
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Toast.makeText(getApplicationContext(), "Logout :)", Toast.LENGTH_SHORT).show();

break;

}
}

public void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://xxx.xxx.xxx:xxxx");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}

mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
//mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
//mWebSocketClient.send("{\"1512BD002\":\"SO@0\":\"2\"}");
}

@Override
public void onMessage(String s) {
//final String message = s;
final String WSmessage = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), WSmessage, Toast.LENGTH_SHORT).show();
tvReceived.setText(WSmessage);
Log.i("Websocket_Message", WSmessage);
//TextView textView = (TextView)findViewById(R.id.messages);
//textView.setText(textView.getText() + "\n" + message);
}
});
}

@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}

@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}

public void sendMessage(View view) {
// EditText editText = (EditText)findViewById(R.id.message);
// mWebSocketClient.send(editText.getText().toString());
//editText.setText("");
}
}

登录 Activity 包 org.asperohgedgetws.a7.hgadgetws;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import android.app.ProgressDialog;
import java.util.LinkedHashMap;
import java.util.Map;

public class Login extends AppCompatActivity implements View.OnClickListener {

Button bLogin;
EditText etUsername, etPassword;
TextView tvRegisterLink;
UserLocalStore userLocalStore;

/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
tvRegisterLink.setOnClickListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}

@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}).setNegativeButton("no", null).show();
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bLogin:
if ((Login.this.etUsername.getText().toString().trim().length() > 0) && (Login.this.etPassword.getText().toString().trim().length() > 0)) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
User user = new User(username, password);
userLocalStore.storeUserData(user);

Map obj = new LinkedHashMap();
obj.put("id", user.username);
obj.put("password", user.password);
obj.put("type", "signin");
obj.put("user.", "normal");

Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(json);
Log.i("Ordered Json", json);
ProgressDialog pd = new ProgressDialog(Login.this);
pd.setMessage("loading");
pd.show();
MainActivity.mWebSocketClient.send(json);
//Here I want to use received Message from Server to Authenticate User.
return;
}
Log.i("Login ERROR", "Username OR Password Missing");
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error")
.setMessage("Email ID or Password Missing")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
}).show();

break;
case R.id.tvRegisterLink:
Toast.makeText(getApplicationContext(), "Register :)", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, Register.class));
break;
}

}

编辑:

大家好,我刚刚浏览了 Android 服务、单例和 Android 广播接收器示例。我只是想,如果我使用 Android 服务进行网络连接(Websocket)管理、数据传输和接收并使用 Android 广播来通知特定 Activity 有新的传入消息会怎样?

最佳答案

我认为使用 Activity 来处理服务器通信是错误的方法。虽然 LoginActivity 可见,但 MainActivity 位于后台,系统可能随时终止它,导致套接字连接消失。

这似乎是应该使用服务完成的任务的完美案例。实现所需的逻辑,例如设置套接字以及在服务中发送和接收消息,并将其绑定(bind)到 Activity 中的“onCreate”方法中。一旦服务绑定(bind),您就可以询问服务用户是否已登录或请求登录用户。因为服务随后会接收消息,所以您需要一种方法来向 Activity 报告。这可以通过广播或观察者来实现。对于后一种情况,您可能需要为观察者和服务创建 AIDL 接口(interface),这实际上并不难。

如果您不在应用程序中使用不同的进程,您也可以简单地创建一个单例而不是服务,并在不同的 Activity 中使用它。如果需要,您还可以稍后将单例放入服务中。

至于例子,除了 default Service documentation 我想不出任何例子。

关于java - 如何对 Android 中的所有 Activity 使用单一方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37538972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com