簡體   English   中英

將活動更改為班級-Android

[英]Changing Activities to Classes - Android

我對Java和Android有點陌生,並且在類和活動方面遇到了麻煩。 我正在清理代碼,並將其中的很多代碼從MainActivity移到了不同​​的類,但是我只能通過創建新的活動而不是類來使應用程序正常工作。

  • 我需要保留在主視圖中,僅使用類的方法
  • 在主活動中,單擊一個按鈕,遞減計數,然后調用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
         }
    }

}

由於這個問題很有趣,因此我對您的帖子進行了更清晰的編輯。 這是許多新開發者在使用android時遇到的難題。 相信我,我看到了非常糟糕的代碼。 在正確的時間獲得正確的建議很重要。 所以去。

您走在正確的軌道上。 每個視圖都必須具有自己的活動。 不要擺脫這種習慣。 如果您采用Java方式,那么您很容易不使用活動代碼,但這會使您成為非常糟糕的android開發人員。

是的,您確實需要閱讀更多有關如何編寫android應用程序的信息。

如果您使用1視圖1活動原則,Android OS將為您提供很多支持。 例如,將支持按順序返回的后退按鈕。

一般方法是:

使它們成為類(除去Activity的擴展 ),並為兩個接受上下文作為參數的類構造構造函數。 准備您的方法,並在主要活動中創建類的新實例,以便您可以使用它的方法。 可能您需要進行一些調整,但這不是一個大問題。

btw:建議所有長操作(例如位置更新,http發送/接收)都使用線程/后台操作進行管理,因此您的UI不會凍結,並且避免ANR強制關閉。

活動是一門課。 說,如果您需要執行任何使用外部服務的操作或執行可能很長的操作,那么最好使用在自己的線程上執行此操作的AsyncTask。 參閱本文以了解詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM