首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于正确使用ui线程的android异步任务

问用于正确使用ui线程的android异步任务
EN

Stack Overflow用户
提问于 2012-02-01 10:30:58
回答 2查看 589关注 0票数 0

下面是我准备好的代码,它监听位置更新,一旦位置在指定区域内,它将连接到服务器,并开始发送它的位置和时间戳,直到它退出该区域。

我被告知,不同的方法可能会突出ui线程,我需要让网络连接在后台或单独的线程上运行,以防止应用程序中的速度减慢。

我在安卓文档中读到了关于异步任务的文章。

以下是我的问题:

  1. 我想我需要放一个单独的线程,在应用程序确定它在指定区域(矩形)内,以及它试图连接并发送到服务器的那一刻之后。
  2. 我该怎么做? 公共类GpsActivity扩展活动{ LocationManager lm;私有LocationListener locationListener;公共静态TelephonyManager tm;公共静态TextView tv;公共静态套接字;公共静态PrintWriter out;在第一次创建活动时调用/** *。*/ @覆盖公共onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);/** *检索引用以提供对设备*/ tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)上的电话服务的访问信息;setContentView(R.layout.main);/** *检索引用以提供对系统位置服务*/ lm =onCreate的访问criteria.setPowerRequirement(Criteria.POWER_LOW);*显式选择提供程序,创建一组标准,让/**选择最佳的提供程序*/ /**=新标准();criteria.setAccuracy(Criteria.ACCURACY_FINE);criteria.setAltitudeRequired(假);criteria.setBearingRequired(假);criteria.setCostAllowed(真);lm.getBestProvider(标准,真);/** *此方法接受四个参数: provider:注册minTime的提供者的名称:通知的最小时间间隔,以毫秒为单位。minDistance:通知的最小距离间隔,以米为单位。侦听器:为每个位置更新调用其onLocationChanged()方法的对象。*/ locationListener =新的MyLocationListener();MyLocationListener 0,0,locationListener);tv = (TextView) findViewById(R.id.textView1);tv.setText(“我目前没有位置数据”);} /** *将Android客户端连接到给定的服务器** @param名称*远程服务器的名称* @param端口*端口号,以连接到远程服务器。@引发IOException *@抛出UnknownHostException */公共静态空连接(字符串名,int端口)抛出UnknownHostException,IOException {s=新套接字(名称、端口);out =新PrintWriter(s.getOutputStream(),true);} /** *向服务器发送字符串消息。** @param msg *要发送的消息。*@抛出IOException */公共静态空发送(String)抛出IOException { if (!s.isClosed() & msg != null) { out.println( msg);if (msg.contains("CMD_QUIT")) { out.close();s.close();Log.i("ServerConnection",“客户端断开连接”);}}//用于接收来自LocationManager的通知,当位置更改时,私有类MyLocationListener实现LocationListener{ @Override ( location loc) { String txt =“Latitude:+ loc.getLatitude() + "/nLongitude:”+ loc.getLongitude();Log.i("GeoLocation“),”我当前的位置是:\n“+ txt);tv.setText(”我的当前位置是:\n“+ txt);最后字符串msg = loc.getLongitude() +“n”+ loc.getLatitude() +“n”+ loc.getTime();//确定该位置是否位于指定区域(矩形)双lat0 = 14.618572;双long0 = 120.993816;双lat1 = 14.619652;双long1 = 120.992770;双lat2 = 14.620285;双long2 = 120.993451;双lat3 = 14.619242;双long3 = 120.994497;双rel1 = (loc.getLongitude()- long0)*(lat1 - lat0)- ((loc.getLatitude()-lat0)*(long3 1-Long 0);双rel2 = (loc.getLongitude()- long1)*(lat2 - lat1)- ((loc.getLatitude()-lat1)*(long3 2-Long 1));双rel4 = (loc.getLongitude()- long3)*(lat0 - lat3)- ((loc.getLatitude()-lat3)*(long3 0-long3 3));//如果是,它将连接到服务器并发送位置和时间戳if (rel1 >= 0& rel2 >= 0& rel3 >= 0& rel4 >= 0){尝试{ connect("IP地址“,27960);发送(”CMD_HELLO“);发送(Msg);tv.setText(“位置在道路network...sending坐标到服务器”);发送(“CMD_QUIT”);} catch (UnknownHostException e) { // TODO自动生成的catch块e.printStackTrace();} catch (IOException e) { // TODO自动生成的catch块e.printStackTrace();}tv.setText(“当前位置在路网外”);}}@覆盖公共空onProviderDisabled(字符串提供程序){ // TODO自动生成的方法存根}@覆盖公共空onProviderEnabled(字符串提供程序){ // TODO自动生成的方法存根}@覆盖公共空onStatusChanged(字符串提供程序,int状态,捆绑附加){ // TODO自动生成的方法存根}
EN

回答 2

Stack Overflow用户

发布于 2012-02-09 16:46:23

能够做到这一点,它通过遵循教程的方式工作。

代码语言:javascript
复制
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 /**
  * retrieve a reference to provide access to information about the telephony services on the device     
  */
    tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
    setContentView(R.layout.main);
 /**
  * retrieve a reference to provide access to the system location services    
  */              
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);    


/**
explicitly select the GPS provider, create a set of Criteria and let android choose 
the best provider available
 */

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = lm.getBestProvider(criteria, true);
/**
 * This method takes in four parameters:
provider: The name of the provider with which you register
minTime: The minimum time interval for notifications, in milliseconds.
minDistance: The minimum distance interval for notifications, in meters.
listener: An object whose onLocationChanged() method will be called for each location update.
 */
locationListener = new MyLocationListener();
lm.requestLocationUpdates(provider, 1000, 1, locationListener);

tv = (TextView) findViewById(R.id.textView1);
tv.setText("I currently have no Location Data.");

}

/**
 * Connects the Android Client to a given server
 * 
 * @param name
 *            The name of the remote server
 * @param port
 *            Port number to connect to at the remote server.
 * @throws IOException
 * @throws UnknownHostException
 */
 public static void connect(String name, int port)
        throws UnknownHostException, IOException
{

    s = new Socket(name, port);
    out = new PrintWriter(s.getOutputStream(), true);
}

/**
 * Sends a string message to the server.
 * 
 * @param msg
 *            The message to be sent.
 * @throws IOException
 */
 public static void send(String outmsg) throws IOException
{
    if (!s.isClosed() && outmsg != null)
    {
        out.println(outmsg);
        out.close();
        s.close();
        }}



  //Used for receiving notifications from the LocationManager when the location has changed

private class MyLocationListener implements LocationListener{


    @Override
    public void onLocationChanged(Location loc) {
        String txt = "Latitude:" + loc.getLatitude() + "/nLongitude:" + loc.getLongitude();
        Log.i("GeoLocation", "My current location is:\n " + txt);
        tv.setText("My current location is:\n" + txt);
        String msg=loc.getLongitude() + "\n" + loc.getLatitude() + "\n"
        + loc.getTime();
        tv1 = (TextView) findViewById(R.id.textView2);
        tv2 = (TextView) findViewById(R.id.textView3);  
        //determines if the location is within a designated area (rectangle)
        double lat0 = 14.609794;
        double long0 = 120.986018;
        double lat1 = 14.608966;
        double long1 = 120.986037;
        double lat2 = 14.609031;
        double long2 = 120.984991;
        double lat3 = 14.609877;
        double long3 = 120.985069;
        double rel1 = (loc.getLongitude()- long0)*(lat1 - lat0)- ((loc.getLatitude()-lat0)*(long1-long0));
        double rel2 = (loc.getLongitude()- long1)*(lat2 - lat1)- ((loc.getLatitude()-lat1)*(long2-long1));
        double rel3 = (loc.getLongitude()- long2)*(lat3 - lat2)- ((loc.getLatitude()-lat2)*(long3-long2));
        double rel4 = (loc.getLongitude()- long3)*(lat0 - lat3)- ((loc.getLatitude()-lat3)*(long0-long3));

        // if yes, it will connect to server and send the location and timestamp

       if (rel1 >= 0 && rel2 >= 0 && rel3 >= 0 && rel4 >= 0 )
        {
           tv1.setText("Location is inside the road network...");
           **new connectSend().execute(msg);**  
           }


        else
        {
            tv1.setText("Current location is outside the road network");

        }
        }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    **public class connectSend extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... msg) {
            // TODO Auto-generated method stub
            String result;

            try
            {
            connect("ip address", port);

            send(msg[0]);

            result = "SUCCESSFUL coordinates sent to server";

            } catch (UnknownHostException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result = "NOT SUCCESSFUL ";
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                result = "NOT SUCCESSFUL ";
            }
            return result;}

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            tv2.setText("result");

            }**


}


    }

}
票数 0
EN

Stack Overflow用户

发布于 2012-02-09 16:56:42

您可以使用runnOnUIThread(Runnable )来更改文本。

无论如何,使用AsyncTask更好,因为在连接时不冻结UI。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9094298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档