简体   繁体   中英

Problems using an Android Service for network connection in an AsyncTask

I want to use a Service to build up my connection using a AsyncTask. I want to have a reference in every activity to variable m_netLinkIp which is created during the setup of the connection.

At the moment my Service looks like this:

package de.bertrandt.bertrandtknx;

import de.bertrandt.bertrandtknx.Controls.Dimmer;
import tuwien.auto.calimero.link.KNXNetworkLinkIP;
import tuwien.auto.calimero.process.ProcessCommunicator;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class ConnectionService extends Service {

    private static final String TAG = "ConnectionService";
    private static KNXNetworkLinkIP m_netLinkIp = null;
    private static ProcessCommunicator m_pc = null;
    private static boolean connection_ok;

           @Override
           public IBinder onBind(Intent intent) {
              return null;
           }

           @Override
           public void onCreate() {
              //code to execute when the service is first created
               new Connect().execute();
           }

           @Override
           public void onDestroy() {
              //code to execute when the service is shutting down
               new Disconnect().execute();
           }

           @Override
           public void onStart(Intent intent, int startid) {
              //code to execute when the service is starting up
           }

    /**
     * Connect Async
     * */
    private class Connect extends AsyncTask<String, Void, String> {
          ProgressDialog dialog;
          boolean ok;
          @Override
          protected String doInBackground(String... params) {
              try {
                  //get local IP address
                  String ipAddress = getIpAddr();
                  System.out.println("WiFi address is " + ipAddress);

                  m_netLinkIp = Calimero.Util.connect(ipAddress, "192.168.0.2");

                  if (m_netLinkIp == null){

                      System.out.println("Can not connect to Demobard");
                      ok = false;
                  }
                  else{
                      System.out.println("Connected to Demoboard");
                      ok = true;

                      }
               } catch (Exception e) {         
                   e.printStackTrace(); 
               }
               return null;
          }      

          @Override
          protected void onPostExecute(String result) { 
            //dialog.dismiss();
            Toast.makeText(getApplicationContext(),
                    "Verbindung mit Demoboard " +
                            ((ok == true) ? "hergestellt" : "fehlgeschlagen"), Toast.LENGTH_LONG).show();
            if(ok == false){
                //show reconnect dialog
                //reconnect_dialog();
            }
          }

          @Override
          protected void onPreExecute() {
           // Setup Progress Dialog
           dialog = new ProgressDialog(Dimmer.this);
           dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
           dialog.setMessage("Bitte warten, verbinde mit KNX-Board");
           dialog.setIndeterminate(true);
           dialog.show();
          }
    }

    /**
     * GetIPAddress Async
     * */
    public String getIpAddr() {
           WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
           WifiInfo wifiInfo = wifiManager.getConnectionInfo();
           int ip = wifiInfo.getIpAddress();

           String ipString = String.format(
           "%d.%d.%d.%d",
           (ip & 0xff),
           (ip >> 8 & 0xff),
           (ip >> 16 & 0xff),
           (ip >> 24 & 0xff));

           return ipString.toString();
    }

    /**
     * Disconnect Async
     * */
    private class Disconnect extends AsyncTask<String, Void, String> {
          @Override
          protected String doInBackground(String... params) {
                    try {
                        Calimero.Util.disconnect(m_netLinkIp);
                    } catch (Exception e) {
                        e.printStackTrace(); 
                    }
                return null;
          }      

    }

}

So here are my questions:

1.) How can I call the Service in any of my activity and get a reference to the m_netLinkIp variable so that I do not have to re-connect in every activity? At the moment I call it like this: startService(new Intent(this, ConnectionService.class));

SOLUTION : I changed the global variable inside my Service class to public static KNXNetworkLinkIP m_netLinkIp = null; and now I can call it in every activity like this: m_netLinkIp= ConnectionService.m_netLinkIp;

2.) How can I show the ProgressBar in every activity? I have to add the activity in the declaration: dialog = new ProgressDialog(Dimmer.this);

Thank you!

I have the very same issue with a downloading service. Initially, I had an included layout with a lot of boilerplate code to respond to the binder's callback events. Now I have a self-contained fragment that I add to each activity which needs to display the progress.

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