2012-02-28 75 views
0

我对Java和Android有点新,并且遇到类和活动的麻烦。我正在清理我的代码,并将大量的代码从MainActivity移到不同的类中,但我只能通过创建新的活动而不是类来使应用程序工作。将活动更改为类 - Android

  • 我需要留在主视图,只是使用类的方法
  • 从主要活动按钮,倒计时,然后调用LocationActivity。
  • LocationActivity找到GPS坐标,然后将它们发送到SendActivity。

这是我能够使它工作的唯一方法,因为我只需要启动locationListener,所以我只是在onCreate部分启动它。

MainActivity.java

public class MainActivity extends Activity { 

    Button mCloseButton; 
    Button mOpenButton; 
    MultiDirectionSlidingDrawer mDrawer; 

    private Button send_button; 
    Button sendButton; 
    EditText msgTextField; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.main); 

     send_button = (Button)findViewById(R.id.button2); 

     mDrawer.open(); 

     mCloseButton.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) 
      { 
       mDrawer.animateClose(); 
      } 
     }); 

     mOpenButton.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) 
      { 
       if(!mDrawer.isOpened()) 
        mDrawer.animateOpen(); 
      } 
     }); 

     final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); 
     final String first = shared.getString("FIRSTNAME", ""); 
     final String last = shared.getString("LASTNAME", "0"); 


     ///////Profile Button//////////////// 
     Button profile = (Button) findViewById(R.id.button1); 
     profile.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       startActivity(new Intent(MainActivity.this, PreferencesActivity.class)); 
      } 
     }); 
     /////////////////////////////////// 

     //////Generate ID////////////////// 
     if (usr_id == null) { 

      char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray(); 
      Random r = new Random(System.currentTimeMillis()); 
      char[] id = new char[8]; 
      for (int i = 0; i < 8; i++) { 
       id[i] = chars[r.nextInt(chars.length)]; 
      } 
      usr_id = new String(id); 
      Editor editor = shared.edit(); 
      editor.putString("USR_ID", usr_id); 
      editor.commit(); 
     } 
     //////////////////////////////////     

     ////////Send Alert//////////////// 
     ///////Begin Timer/////////////// 
     send_button.setOnClickListener(new OnClickListener() { 

      private boolean running = false; 
      private CountDownTimer timer; 
      public void onClick(View v) { 
       if(!running) 
       { 
       running = true; 
       timer = new CountDownTimer(4000, 1000) { 

        @Override 
        public void onFinish() { 
         send_button.setText("SENT"); 
         startActivity(new Intent(MainActivity.this, LocationActivity.class)); 
         SendUserActivity.sendId(usr_id1, first, last);           
        } 

        @Override 
        public void onTick(long sec) { 
         send_button.setText("CANCEL (" + sec/1000 + ")"); 

        } 
       }.start(); 
       } 
       else 
       { 
       timer.cancel(); 
       send_button.setText("Send!"); 
       running = false; 
       } 
      } 
     }); 
    } 
    /////////////////////////////////// 


    @Override 
    public void onContentChanged() 
    { 
    super.onContentChanged(); 
    mCloseButton = (Button) findViewById(R.id.button_open); 
    mOpenButton = (Button) findViewById(R.id.button_open); 
    mDrawer = (MultiDirectionSlidingDrawer) findViewById(R.id.drawer); 
    } 
} 

LocationActivity.java

package com.alex.www; 

import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.Button; 

public class LocationActivity extends Activity { 


    private LocationManager locManager; 
    private LocationListener locListener; 


    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     startLocation(); 
    } 

    void startLocation() 
    { 

     SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); 
    final String usr_id2 = shared.getString("USR_ID", "none"); 

    //get a reference to the LocationManager 
    locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 


    //checked to receive updates from the position 
    locListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      SendActivity.send(location, usr_id2); 
     } 
     public void onProviderDisabled(String provider){ 
      //labelState.setText("Provider OFF"); 
     } 
     public void onProviderEnabled(String provider){ 
      //labelState.setText("Provider ON "); 
     } 
     public void onStatusChanged(String provider, int status, Bundle extras){ 
      Log.i("", "Provider Status: " + status); 
      } 
     }; 

     locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); 
    } 
} 

SendActivity.java

package com.alex.www; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import android.app.Activity; 
import android.content.SharedPreferences; 
import android.location.Location; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

public class SendActivity extends Activity { 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    public static void send(Location loc, String usr_id2) 
    { 

     Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude()))); 

     String lat = String.valueOf(loc.getLatitude()); 
     String lon = String.valueOf(loc.getLongitude()); 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://example.com/test/example.php"); 

     try { 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("lat", lat)); 
      nameValuePairs.add(new BasicNameValuePair("lon", lon)); 
      nameValuePairs.add(new BasicNameValuePair("id", usr_id2)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      httpclient.execute(httppost); 
     } 
     catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } 
     catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
    } 

} 
+0

尽量尊重,先学习Java,同时不要学习Android的负担。我相信你不会理解这个建议,但是一旦你对Java有了一个明确的理解,你就会明白这对你来说是最好的行动方式。 – mah 2012-02-28 12:34:38

回答

0

我编辑您的文章更加清晰,因为这个问题很有意思。这是许多新开发人员在开始使用android时遇到的困境。相信我,我看到了真正糟糕的代码。在正确的时间得到正确的建议非常重要。所以在这里。

您正处在正确的轨道上。每个视图都必须有自己的活动。不要摆脱那种习惯。如果你使用java的方式,那么你就不想使用activity,但这会让你成为一个非常糟糕的android开发者。

是的,你需要阅读更多关于如何编写Android应用程序。

如果您使用1视图1活动原则,android操作系统将支持你很多。例如,支持按顺序返回的后退按钮。

+0

碎片发生了什么? – Bostone 2012-03-03 20:30:21

+0

不明白你的问题? – 2012-03-14 06:07:20

0

一般的做法是:

让他们班(除去延伸活动),并contructors为此接受上下文参数两类。准备你的方法,并在主要活动中创建类的新实例,以便可以使用它的方法。可能你需要适应一些东西,但它不应该是一个大问题。

BTW:建议所有长操作(如位置更新,HTTP发送/收到)使用threads/background operation进行管理,所以你的用户界面是未被冻结,并且你避免ANR强制关闭..

+0

你可以给我一个例子,我的代码?只是为了让我开始。如果我从LocationActivity中删除extends Activity部分,'getSystemService'会引发一个错误,并要求我为它创建一个方法。 – mkyong 2012-02-28 12:49:31

0

活动是一类。说如果你需要做任何使用外部服务的操作或者做一些可能很长的事情,那么最好使用AsyncTask来完成它自己的线程。请详细说明refer to this article