• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Android Network Programming?

Does anyone know the right way to write a networking program for Android?

I attempted to send an object from my phone to a regular socketServer. It uses a ObjectOutputStream & the Socket.accept() method.

The android client seems to be working. It seems to send the object.
However, the server doesnt seem to accept the object.

Does anyone know if its possible to create a networking program in this way for Android?

Here's the client
Code:
package com.example.Plus;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import java.net.*;
import java.io.*;


public class PlusRemote extends Activity {
    
    private EditText text;
    //InetAddress address;
    Socket s;
    OutputStream out=null;
    ObjectOutputStream oos=null;
    String cmd ="";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        text = (EditText) findViewById(R.id.defaultIp);
    }
    public void myClickHandler(View view) {        
        switch (view.getId()){
        case R.id.CON:
            cmd = "Connect";
            //Connect to Server
            try{
                this.text.setText("Connecting....");
            
                //substitute x's for your real ip address
                s=new Socket("xxx.xxx.xxx.xxx", 1234);
                out=s.getOutputStream(); 
                oos=new ObjectOutputStream(out);
                oos.writeObject(new String(cmd));
                oos.flush();
                oos.close();
                s.close();
            }catch(Exception e){
                this.text.setText(e.toString());
                    }
            //SET status "Connected Success!"
            this.text.setText(R.string.EditText01);
            
            break;
        case R.id.REW:
    Toast.makeText(this, "REWIND ", Toast.LENGTH_LONG).show();
            break;
        case R.id.STOP:
            Toast.makeText(this, "STOP", Toast.LENGTH_LONG).show();
            break;
        case R.id.PLAY:
            Toast.makeText(this, "PLAY", Toast.LENGTH_LONG).show();
            break;
        case R.id.FWD:
            Toast.makeText(this, "FOWARD", Toast.LENGTH_LONG).show();
            break;
        }
     }


}
And heres the server
Code:
//PlusServer.java
//Server that takes commands from Android Client, executes commands & finally returns result.

import java.net.*;
import java.io.*;

public class PlusServer
{
    //instance variables
    static Boolean finished = false;

    
    //Main method
    public static void main(String[] args)
        {
        System.out.println(" 000 Entered Main method");
        //Disable Security Manager
        //System.setSecurityManager(null);
            try
            {
        ServerSocket listener = new ServerSocket(1234);
        System.out.println("0 setup ServerSocket on port 1234");

            while(!finished)
                {
          
                Socket client = listener.accept();//wait for connection
        
                InputStream in = client.getInputStream();
                OutputStream out = client.getOutputStream();
             
                //read cmd
                ObjectInputStream oin = new ObjectInputStream(in);

                String cmd = (String)oin.readObject();

                if (cmd.equals("Connect"))
                    {
       
                    client.close();
                    finished=true;
                    }
                //Send results
                // blah, blah, blah

                    
                
                }
            
            listener.close();    
            }
            catch(Exception e){System.out.println("Error: "+e);}
        }
}
 
I just did something very similar using bluetooth instead of HTTP, but instead of using ObjectInputStream, I used a regular ol' InputStream and used a regular ol' OutputStream on the other end. I have also got it working using BufferedInputStream/BufferedOutputStream, but when just sending a simple string of text, the differences were negligible, so I was able to cut out a lot of code by just using a regular Input/OutputStream. Might try that as I really don't see a need to read in an object.
 
Upvote 0
Android network programming involves developing applications that interact with network services and APIs on Android devices. It allows you to establish network connections, send and receive data over the network, and handle various network-related tasks.

Here are some key concepts and components related to Android network programming:

  1. Networking APIs: Android provides a set of networking APIs to facilitate network communication. The primary networking classes are part of the java.net package and include classes like URL, URLConnection, HttpURLConnection, Socket, and ServerSocket.
  2. Internet permission: To access the network in your Android application, you need to declare the INTERNET permission in the Android manifest file.
  3. AsyncTask: When performing network operations, it's crucial to avoid blocking the main UI thread. The AsyncTask class allows you to perform background network tasks asynchronously and update the UI when the task completes.
  4. HTTP communication: Android supports HTTP communication through the HttpURLConnection class or third-party libraries like OkHttp or Volley. You can use these classes to make HTTP requests (GET, POST, PUT, DELETE) to a remote server and process the responses.
  5. JSON and XML parsing: Often, network responses are in JSON or XML format. Android provides libraries such as JSONObject, JSONArray, and XmlPullParser to parse and extract data from these formats.
  6. WebSockets: WebSockets enable full-duplex communication between a client and a server over a single, long-lived connection. The java.net package provides classes like WebSocket and WebSocketFactory for WebSocket programming.
  7. Network security: Android offers features to ensure secure network communication, including support for SSL/TLS encryption, certificate pinning, and secure connection protocols.
  8. Network connectivity and status monitoring: You can check the network connectivity status using the ConnectivityManager class. This allows you to handle scenarios when the device switches between different network types or loses connectivity.
  9. Background services: For long-running network operations, you might consider using background services or foreground services, depending on the requirements of your application.
  10. Networking libraries: Several third-party libraries, like Retrofit, Volley, and OkHttp, provide higher-level abstractions and simplify network programming in Android by offering features such as request queuing, caching, and easier API integration.
When working with network programming in Android, it's essential to handle network-related tasks asynchronously, handle exceptions gracefully, and ensure proper error handling to provide a smooth user experience.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones