如何让Android客户端连接到服务器甚至在活动的变化,将数据发送到服务器?服务器、发送到、连接到、客户端

2023-09-04 11:28:00 作者:我在回忆里等你

我首先实施在我的活性的异步任务,它发送数据到服务器。但是,当我改变活动连接中断。为了避免这种情况我的方法是实施了集中的网络运营和将数据发送到服务器和$ C $下此服务被赋予以下

服务

 进口java.io.BufferedWriter中;
进口java.io.OutputStreamWriter中;
进口的java.io.PrintWriter;
进口的java.net.InetAddress;
进口的java.net.Socket;

进口android.app.Service;
进口android.content.Intent;
进口android.os.Binder;
进口android.os.IBinder;
进口android.util.Log;
进口android.widget.Toast;

公共类SocketService延伸服务{
  公共静态最后弦乐SERVERIP =; //你的计算机的IP地址应该在这里写
  公共静态最终诠释SERVERPORT = 5000;
  PrintWriter的了;
  Socket套接字;
  InetAddress类serverAddr;

@覆盖
公众的IBinder onBind(意向意图){
    // TODO自动生成方法存根
    的System.out.println(我在的IBinder onBind方法);
      返回myBinder;
}

  私人最终的IBinder myBinder =新LocalBinder();
  的TcpClient mTcpClient =新的TcpClient();

  公共类LocalBinder扩展粘合剂{
        公共SocketService的getService(){
            的System.out.println(我在Localbinder);
            返回SocketService.this;

        }
    }

  @覆盖
    公共无效的onCreate(){
        super.onCreate();
        的System.out.println(我在创作);
    }

  公共无效IsBoundable(){
        Toast.makeText(这一点,我绑定如黄油,Toast.LENGTH_LONG).show();
    }

  公共无效的sendMessage(字符串消息){
        如果(满分= NULL和放大器;!&安培;!out.checkError()){
            的System.out.println(中的sendMessage+消息);
            通过out.println(消息);
            了out.flush();
        }
    }

    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        super.onStartCommand(意向,标志,startId);
        的System.out.println(我在开始);
      // Toast.makeText(本,服务创造......,Toast.LENGTH_LONG).show();
        Runnable接口连接=新connectSocket();
        新的线程(连接)。启动();
        返回START_STICKY;
    }


    类connectSocket实现Runnable {

        @覆盖
        公共无效的run(){


            尝试 {
                 //在这里你必须把你的计算机的IP地址。
                serverAddr = InetAddress.getByName(SERVERIP);
                Log.e(TCP客户端,C:连接...);
                //创建一个插座,使与服务器的连接

                插座=新的Socket(serverAddr,SERVERPORT);

                 尝试 {


                     //将消息发送到服务器
                     OUT =的新PrintWriter(新的BufferedWriter(新OutputStreamWriter(socket.getOutputStream())),TRUE);


                     Log.e(TCP客户端,C:发送。);

                     Log.e(TCP客户端,C:完成。);


                    }
                 赶上(例外五){

                     Log.e(TCP,S:错误,E);

                 }
            }赶上(例外五){

                Log.e(TCP,C:错误,E);

            }

        }

    }


    @覆盖
    公共无效的onDestroy(){
        super.onDestroy();
          尝试 {
              socket.close();
          }赶上(例外五){
              // TODO自动生成的catch块
              e.printStackTrace();
          }
          插座= NULL;
      }


    }
 

Rotator.java是我的活动我绑定到该服务。以下是几件code,从我的活动。

 私人ServiceConnection mConnection =新ServiceConnection(){
            //编辑的零件
    @覆盖
    公共无效onServiceConnected(组件名名称,服务的IBinder){
        // TODO自动生成方法存根
         mBoundService =((SocketService.LocalBinder)服务).getService();

    }

    @覆盖
    公共无效onServiceDisconnected(组件名名){
        // TODO自动生成方法存根
         mBoundService = NULL;
    }

  };


   私人无效doBindService(){
       bindService(新意图(Rotator.this,SocketService.class),mConnection,Context.BIND_AUTO_CREATE);
       mIsBound = TRUE;
       如果(mBoundService!= NULL){
       mBoundService.IsBoundable();
       }
   }


   私人无效doUnbindService(){
       如果(mIsBound){
           //分离我们的现有连接。
           unbindService(mConnection);
           mIsBound = FALSE;
       }
   }

@覆盖
公共无效的onCreate(包savedInstanceState)
{
      super.onCreate(savedInstanceState);
      gestureDetector =新GestureDetector(这一点,新GestureListener());
      的setContentView(R.layout.activity_rotator);


      //活动绑定到服务执行客户端 - 服务器操作
      //开始创建服务
        startService(新意图(Rotator.this,SocketService.class));
        doBindService();
                  ...........
                  ...........
}


@覆盖
保护无效的onDestroy(){
    super.onDestroy();
    doUnbindService();
}
 

现在,因为该服务在后台运行,如果我想一些数据发送给我用下面的服务器

 如果(mBoundService!= NULL)
{
    mBoundService.sendMessage(正确);
}
 
android客户端与本地服务器的访问 服务器本地图片怎么转化成http格式让安卓手机访问

解决方案

在code是正确的。唯一的错误是,我是想在onServiceConnected启动服务()方法一次两次,另一次在的onCreate()方法。

我改变了我的code启动该服务的启动活动仅在的onCreate()方法。该活动的其余部分通过doBindService直接绑定到service()方法

I initially implemented an async task in my activity which sends data to the server. But when i changed activities the connection was lost. To avoid this my approach was to implement a service that centralizes the network operation and sends data to the server and the code for this service is given below

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class SocketService extends Service {
  public static final String SERVERIP = ""; //your computer IP address should be written here
  public static final int SERVERPORT = 5000;
  PrintWriter out;
  Socket socket;
  InetAddress serverAddr;

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    System.out.println("I am in Ibinder onBind method");
      return myBinder;
}

  private final IBinder myBinder = new LocalBinder();
  TCPClient mTcpClient = new TCPClient();

  public class LocalBinder extends Binder {
        public SocketService getService() {
            System.out.println("I am in Localbinder ");
            return SocketService.this;

        }
    }

  @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("I am in on create");     
    }

  public void IsBoundable(){
        Toast.makeText(this,"I bind like butter", Toast.LENGTH_LONG).show();
    }

  public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            System.out.println("in sendMessage"+message);
            out.println(message);
            out.flush();
        }
    }

    @Override
    public int onStartCommand(Intent intent,int flags, int startId){
        super.onStartCommand(intent, flags, startId);
        System.out.println("I am in on start");
      //  Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
        Runnable connect = new connectSocket();
        new Thread(connect).start();
        return START_STICKY;
    }


    class connectSocket implements Runnable {

        @Override
        public void run() {


            try { 
                 //here you must put your computer's IP address.
                serverAddr = InetAddress.getByName(SERVERIP);
                Log.e("TCP Client", "C: Connecting...");
                //create a socket to make the connection with the server

                socket = new Socket(serverAddr, SERVERPORT);

                 try {


                     //send the message to the server
                     out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);


                     Log.e("TCP Client", "C: Sent.");

                     Log.e("TCP Client", "C: Done.");


                    } 
                 catch (Exception e) {

                     Log.e("TCP", "S: Error", e);

                 }
            } catch (Exception e) {

                Log.e("TCP", "C: Error", e);

            }

        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
          try {
              socket.close();
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          socket = null;
      }


    }

Rotator.java is my activity which I bind to this service. Following are few pieces of code from my activity.

private ServiceConnection mConnection = new ServiceConnection() {
            //EDITED PART
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // TODO Auto-generated method stub
         mBoundService = ((SocketService.LocalBinder)service).getService();

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
         mBoundService = null;
    }

  };


   private void doBindService() {
       bindService(new Intent(Rotator.this, SocketService.class), mConnection, Context.BIND_AUTO_CREATE);
       mIsBound = true;
       if(mBoundService!=null){
       mBoundService.IsBoundable();
       }
   }


   private void doUnbindService() {
       if (mIsBound) {
           // Detach our existing connection.
           unbindService(mConnection);
           mIsBound = false;
       }
   }

@Override
public void onCreate(Bundle savedInstanceState)
{
      super.onCreate(savedInstanceState);
      gestureDetector = new GestureDetector(this, new GestureListener());
      setContentView(R.layout.activity_rotator);


      //Binding the activity to the service to perform client-server operations
      //start service on create
        startService(new Intent(Rotator.this,SocketService.class));
        doBindService();
                  ...........
                  ...........
}   


@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

Now as this service runs in the background, If i want to send some data to the server i use the following

 if(mBoundService!=null)
{
    mBoundService.sendMessage("right");
}

解决方案

The code is right. The only mistake was that I was trying to start the service twice once in onServiceConnected() method and the other in onCreate() method.

I changed my code to start the service only in onCreate() method in the launcher activity. The rest of the activities directly bind to the service by using doBindService() method