我正在为我的应用程序使用websocket client程序。在主要的Activity I中,我连接到websocket客户端并执行所有onMessage,onOpen就像抽象mathod一样。我还有两个名为Login and Register活动的活动。我将Login ativity中的用户详细信息发送到服务器以进行验证。来自服务器I在onMessage抽象方法中接收MainActivity中的消息。我需要在Login Activity中使用该消息。请解释我如何实现这一目标?如果我在这里复制我的问题,请原谅我,并指导我做出正确答案。
这是我的 MainActivity :
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("");
}
}
LoginActivity 包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 Service,Singleton和Android Broadcast接收器的例子。我只是想到,如果我使用Android服务进行网络连接(Websocket)管理,数据传输和接收并使用Android Broadcast来通知特定的Activity有新的传入消息怎么办?答案 0 :(得分:0)
我认为使用Activities来处理服务器通信是错误的方法。当LoginActivity可见时,MainActivity在后台,并且系统可能会在套接字连接消失时随时将其终止。
这似乎是应该使用服务完成的任务的完美案例。实现所需的逻辑,如设置套接字以及在服务中发送和接收消息,并将其绑定到活动中的“onCreate”方法。一旦服务绑定,您就会询问服务用户是否已登录或请求登录用户。因为服务然后收到消息,您需要一种方法来报告活动。这可以通过广播或观察者来实现。对于后一种情况,您可能需要为Observer和Service创建和AIDL-Interface,这实际上并不那么难。
如果您不在应用程序中使用不同的进程,您可能只需创建一个Singleton而不是Service,并在不同的Activities中使用它。如果需要,您也可以稍后将Singleton放入服务中。
之外我什么也想不到