简体   繁体   中英

How to use single method for all activity in Android?

I am using a websocket client program for my application. In main Activity I'm connecting to websocket client and doing all onMessage,onOpen like abstract mathod. I have two more activity called Login and Register activity. I'm sending User details in Login ativity to server to make it verify. from server I'm Receiving Message in MainActivity in onMessage abstract mathod. I need to use that message in Login Activity. DO explain me how can i achieve this? If I'm Duplicating my question here then pardon me and direct me towards right answer.

Here Is My 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("");
}
}

And LoginActivity package 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;
    }

}

EDIT:

Hi Guys, I just go through Android Service,Singleton and Android Broadcast receiver example. I just Thought that, what if I use Android Service for network connection(Websocket) Management,data transfer and receive and use Android Broadcast to inform the particular Activity for a new incoming Message ?

I think using Activities to handle the server communication is the wrong approach here. While the LoginActivity is visible the MainActivity is in the background and the system might kill it anytime making the socket connection gone.

This seems to be the perfect case for a task that should be done with a Service. Implement the required logic like setting up the socket as well sending and receiving messages in a Service and bind it in the 'onCreate' methods in the Activities. As soon as the Service is bound you then ask the service if a user is logged in or request to log in a user. Because the Service then receives the messages you'll need a way to report back to the Activities. This can be achieved with Broadcasts or with an Observer. For the later case you might need to create and AIDL-Interface for the Observer and the Service which is actually not that hard.

If you don't use different processes in the application you might also simply create a Singleton instead of a Service and use it in the different Activities. If required you also can put the Singleton in an Service later on.

As for examples, I can't think of anything but the default Service documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM