Android Service+socket Networking Interaction

Source: Internet
Author: User
Tags getmessage
In Android, the networking operation has two broad categories: HTTP connection and socket connection. Due to the project needs, we are taking the socket connection. In view of the frequent connection, so put the socket connection to the service, need to obtain data from the server, as long as the corresponding method of the call service.

Service General structure is:

public class Internetservice extends Service implements Runnable {

private socket socket;

Private BufferedReader reader;//

Private PrintWriter writer;//

Private Binder Binder;

Private thread td;//thread, getting message sent from server side

Private String workstatus;//Current working condition, null means processing, success indicates successful processing, failure indicates processing failure

Private String curraction; Marks the current request header information and validates it after obtaining the server-side feedback, so that there is no inconsistency between the feedback information and the current request. For example, send a second request now, but the server side responds to the first request at this time

/**
* Send a request to the server
*
* @param action
*
*/
public void SendRequest (String action) {
try {
Workstatus = null;
Jsonobject json = new Jsonobject ();
Json.put ("Action", action);
Curraction=action;
SendMessage (JSON);
catch (Exception ex) {
Workstatus = constant.tag_failure;
Ex.printstacktrace ();
}
}
/**
* Returns the value of the current Workstatus
* /
Public Stringgetworkstatus ()
{
return workstatus;
}

/**
* Processing server-side feedback data
*
* @param JSON
*
*/
private void Dealuploadsupervisetask (Jsonobject json)
{
try{
Workstatus=json.getstring ("result");
}catch (Exception ex)
{
Ex.printstacktrace ();
Workstatus=constant.tag_failure;
}
}

/**
* Close the socket connection when exiting the program
*/
public void CloseConnection () {

Jsonobject json = new Jsonobject ();//Send disconnect request to server side
try {
Json.put ("Action", "exit");
SendMessage (JSON);//Send disconnect request to server side
LOG.V ("Qlq", "the request is" + json.tostring ());
catch (Exception ex) {

Ex.printstacktrace ();
}
}

/**
* Connect to Server
*/
private void Connectservice () {
try {
Socket = new socket ();
SocketAddress socaddress = new Inetsocketaddress (127.0.0,
8000));
Socket.connect (socaddress, 3000);

reader = new BufferedReader (New InputStreamReader (
Socket.getinputstream (), "GBK"));

writer = new PrintWriter (New BufferedWriter new OutputStreamWriter (
Socket.getoutputstream (), "GBK")), true);

catch (SocketException ex) {
LOG.V ("Qlq", "socketexception");
Ex.printstacktrace ();
Workstatus = constant.tag_connectfailure;//If the network connection is wrong, the network connection error is prompted
Return
catch (Sockettimeoutexception ex) {
Ex.printstacktrace ();
Workstatus = constant.tag_connectfailure;//If the network connection is wrong, the network connection error is prompted
Return
catch (Exception ex) {
Ex.printstacktrace ();
Workstatus = constant.tag_connectfailure;//If the network connection is wrong, the network connection error is prompted
Return
}
}
/**
* Send incoming JSON data information to the server
*
* @param JSON
*/
private void SendMessage (Jsonobject json) {
if (!isnetworkconnected ())//If the current network connection is not available, directly prompts the network connection is not available and exits execution.
{
LOG.V ("Qlq", "Workstatus is not connected!111");
Workstatus = constant.tag_connectfailure;
Return
}
if (socket = = NULL)//If not connected to the server, create a connection
Connectservice ();
if (! InternetService.this.td.isAlive ())//If the current thread is not in a live state, restart the thread
(TD = New Thread (internetservice.this)). Start ();
if (!socket.isconnected () | | (socket.isclosed ())) IsConnected () returns whether the connection has been made, isclosed () returns whether it is in the closed state, and the network is connected only when isconnected () returns false to True,isclosed ()
{
LOG.V ("Qlq", "Workstatus is not connected!111222");
for (int i = 0; i < 3 && workstatus = null; i++) {//If the connection is turned off, retry three times, if the connection is OK, jump out of the loop
socket = NULL;
Connectservice ();
if (socket.isconnected () && (!socket.isclosed ()) {
LOG.V ("Qlq", "Workstatus is not connected!11333");
Break
}
}
if (!socket.isconnected () | | (socket.isclosed ())) If the connection is still not correct, prompt for an error, and jump out of the loop
{
Workstatus = constant.tag_connectfailure;
LOG.V ("Qlq", "Workstatus is not connected!111444");
Return
}

}

if (!socket.isoutputshutdown ()) {//Input output stream is closed
try {
Writer.println (Json.tostring ());
catch (Exception e) {
TODO auto-generated Catch block
LOG.V ("Qlq", "Workstatus is not connected!55555666666");
E.printstacktrace ();
Workstatus = constant.tag_failure;
}
} else {
Workstatus = constant.tag_connectfailure;
}
}

/**
* Processing the message from the server side, and passing the action header information to the corresponding processing method
*
* @param str
*/
private void GetMessage (String str) {
try {
Jsonobject json = new Jsonobject (str);
String action = json.getstring ("action");//Extract JSON action information to get the action of the current JSON response.
if (!curraction.equals (action))
Return
if (Action.equals ("GetCategory")) {
Dealuploadsupervisetask (JSON);
}
catch (Exception ex) {
Ex.printstacktrace ();
Workstatus=constant.tag_failure;
}
}



public class Interbinder extends Binder {

Public Internetservice GetService () {
return internetservice.this;
}
}

@Override
Public IBinder Onbind (Intent Intent) {
TODO auto-generated Method Stub
Binder = new Interbinder ();
TD = New Thread (internetservice.this);//Start threads
Td.start ();

return binder;
}

@Override
public void OnCreate () {
Super.oncreate ();
Connectservice ();
}

@Override
public void OnStart (Intent Intent, int startid) {
Super.onstart (Intent, Startid);
}

@Override
public void OnDestroy () {
Super.ondestroy ();
LOG.V ("Qlq", "Service is on Destroy");
}

@Override
public boolean onunbind (Intent Intent) {
LOG.V ("QLQ", "Service on Onunbind");
return Super.onunbind (Intent);
}

/**
* loops, receiving data from the server side
*/
public void Run () {
try {
while (true) {
Thread.Sleep (500);//Hibernate 0.5s
if (socket!= null &&!socket.isclosed ()) {//If the socket is not closed
if (socket.isconnected ()) {//Determine whether the socket is connected successfully
if (!socket.isinputshutdown ()) {
String content;
if (content = Reader.readline ())!= null) {
GetMessage (content);
}
}
}
}
}
catch (Exception ex) {

try {
Socket.close ();
catch (Exception e) {
E.printstacktrace ();
}
Workstatus = constant.tag_connectfailure;//If an exception occurs, the network connection is prompted for a problem.
Ex.printstacktrace ();
}
}

}
On the foreground page, you need to bind the service using the Bindservice method because of the data interaction between the foreground and the background.
Internetservice Innetservice;
Public serviceconnection internetserviceconnection = new Serviceconnection () {

public void onserviceconnected (componentname arg0, IBinder service) {
Innetservice = ((internetservice.interbinder) service). GetService ();
}

public void onservicedisconnected (ComponentName arg0) {

Innetservice = null;
}

};

And then in the OnCreate, execute
Bindservice (New Intent (Basicactivity.this, Internetservice.class),
Internetserviceconnection, context.bind_auto_create);//basicactivity is the base class that I define for all activity, and this code is also written in basicactivity.

Code should be added to the OnDestroy because it must be lifted after the service is bound
Unbindservice (internetserviceconnection);

Workstatus is defined to let the foreground know if the current networking operation is successful.
The definition of curraction, is to identify the current request content, because the server-side feedback information also has the action header information to identify the current return of the data corresponding to what kind of request, so, when sending the request to set Curraction, receive server-side feedback data, Validation and curraction are consistent and, if inconsistent, are not processed, indicating "not waiting for desired data" and, if they are consistent, the next step. This prevents data-matching errors.
As for the definition of basicactivity, it is because many pages in the software in addition to the middle of the content, the Head button bar and so on, in addition to a lot of common code, and so on, so define a basicactivity, as their parent class, reduce the amount of code, This is also a reflection of Java polymorphism.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.