0

アクティビティ 1 とアクティビティ 2 があります。アクティビティ 2 には GeoCoder クラスがあります (パブリック クラス GeoCoder は AsynTask を拡張します)。アクティビティ 1 から GeoCoder クラスを実行する方法はありますか?

screen1.java

public class screen1 extends Activity implements View.OnClickListener {

ProgressDialog dialog, dialog2, dialog3;

LayoutInflater inflater;
SharedPreferences.Editor editor;
SharedPreferences preferences;

// Strings
String username, password, firstName, lastName, lastLatitudeUpdate;
int checkedin, Minute, Hour, Time;

Timer EnableLocationonResume;

Vibrator vib;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.screen1);   
    vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);



    ///// Calls String from AgentPortalActivity class to pass through to screen1 class  //////////////////////////////////////////////////////////////////////                                                                                                                                              
    Intent i = getIntent();                                                                                                                                 //
    username = i.getExtras().getString("uid");                                                                                                              //
    password = i.getExtras().getString("pwd");                                  ////// Boolean for Check-In Button Sharedpreferences///////////             //
    firstName = i.getExtras().getString("firstName");                           preferences = getPreferences(MODE_PRIVATE);                  //             //
    lastName = i.getExtras().getString("lastName");                             final boolean tgpref; tgpref = preferences.getBoolean("tgpref", true);      //                                                          
    lastLatitudeUpdate = i.getExtras().getString("lastLatitudeUpdate");         checkinbutton.setChecked(tgpref);                            //             //
    checkedin = i.getExtras().getInt("checkedin");                              ///////////////////////////////////////////////////////////////             //  
    Minute = i.getExtras().getInt("Minute");                                                                                                                //
    Hour = i.getExtras().getInt("Hour");                                                                                                                    //
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    //////////////////////// Gets Time since last GPS Update and compares LastUpdate time to Current Time (-60 Minutes) and displays Update GPS status if nessecary //////////
    SimpleDateFormat parserSDF=new SimpleDateFormat("M/d/yyyy h:m:s a"); // <--- Correct format to read "lastLatitudeUpdate"                                                //
    try {                                                                                                                                                                   //
        Date d = parserSDF.parse(lastLatitudeUpdate);                                                                                                                       //
                                                                                                                                                                            //
        Calendar now = Calendar.getInstance();                                                                                                                              //
        // Go back 1 Hour.                                                                                                                                                  //
        now.add(Calendar.MINUTE, -60);                                                                                                                                      //
        Date HourAgo = now.getTime();                                                                                                                                       //
                                                                                                                                                                            //
        if (d.before(HourAgo))  {                                                                                                                                           //
          GPSUPDATE.setText("Please update your gps to stay current on standby list");                                                                                      //
        }                                                                                                                                                                   //
    } catch (java.text.ParseException e1) {                                                                                                                                 //
        // TODO Auto-generated catch block                                                                                                                                  //
        e1.printStackTrace();                                                                                                                                               //
    }                                                                                                                                                                       //
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


        ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     //////
        //-------------------------------------------------------Checks to see if Driver is Currently Checked-In or Checked-Out and toggles checkinbutton respectively------------------------------------------------------//
        //----------------------------------------------------------------------Also Changes "information.settext" to display either hello or goodbye-----------------------------------------------------------------------//
        if (checkedin == 0) {                                                                                                                                                                                               
            String text = "<font color=\"grey\"> You are currently Checked-Out </font>";                                                                                                                                    //
            checkin.setText(Html.fromHtml(text), BufferType.SPANNABLE);                                                                                                                         
                                                                                                                                                                                                                            //
            // Boolean Preferences for Checkinbutton ToggleButton Remembers Toggle State Checked
            editor = preferences.edit();                                                                                                                                                                                    //
            checkinbutton.setChecked(false);
            editor.putBoolean("tgpref", true);          editor.commit();                                                                                                                                                    //

            information.setText("Thank you for todays hard work, " + (firstName) + " " + (lastName) + "!" + "\n" + " You have checked out for the day ");                                                                   //
        } 
                                                                                                                                                                                                                            //
        if (checkedin == 1) {
            String text = "<font color=\"#A2E8\"> You are currently Checked-In </font>";                                                                                                                                    //
            checkin.setText(Html.fromHtml(text), BufferType.SPANNABLE);
                                                                                                                                                                                                                            //
            // Boolean Preferences for Checkinbutton ToggleButton Remembers Toggle State Checked
            editor = preferences.edit();                                                                                                                                                                                    //
            checkinbutton.setChecked(true);
            editor.putBoolean("tgpref", true);          editor.commit();                                                                                                                                                    //

            information.setText("Welcome back, " + (firstName) + " " + (lastName) + "!" + "\n" + " Your last GPS update was on " + (lastLatitudeUpdate));                                                                   //
        }//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     ///     //////





    //-------------------------------------------------------Check IN ToggleButton-------------------------------------------------------//
    checkinbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {       


            vib.vibrate(40);

            //---------------------------Only Displays Mile-in Zip-in and submitin Button---------------------------------------//
            if (checkinbutton.isChecked()) {                                                                                    //
                milein.setVisibility(View.VISIBLE);                                     mileout.setVisibility(View.GONE);       //
                submitin.setVisibility(View.VISIBLE);                                   submitout.setVisibility(View.GONE);     //                  
                CancelIN.setVisibility(View.VISIBLE);                                   CancelOUT.setVisibility(View.GONE);     //
                zipin.setVisibility(View.VISIBLE);                                      zipout.setVisibility(View.GONE);        //
                dispatch.setVisibility(View.GONE);                                      dispatchnum.setVisibility(View.GONE);   //
                donotcallus.setVisibility(View.GONE);                                   googletalk.setVisibility(View.GONE);    //
                csr.setVisibility(View.GONE);                                           csrnum.setVisibility(View.GONE);        //
                it.setVisibility(View.GONE);                                            itnum.setVisibility(View.GONE);         //
                thoughts.setVisibility(View.GONE);                                      feed.setVisibility(View.GONE);          //
                send.setVisibility(View.GONE);                                          information.setVisibility(View.GONE);   //
                checkinbutton.setEnabled(false);                                                                                //
            //------------------------------------------------------------------------------------------------------------------//  

                // Boolean Preferences for Checkinbutton ToggleButton Remembers Toggle State Checked
                editor = preferences.edit();
                preferences = getPreferences(MODE_PRIVATE);

                checkinbutton.setChecked(tgpref);                                       checkinbutton.setChecked(false);
                editor.putBoolean("tgpref", true);                                      editor.commit();

                String text = "<font color=\"#CC0000\"> Checking-In... </font>";
                checkin.setText(Html.fromHtml(text), BufferType.SPANNABLE);

            } else {
                mileout.setVisibility(View.VISIBLE);                                    milein.setVisibility(View.GONE);
                zipout.setVisibility(View.VISIBLE);                                     zipin.setVisibility(View.GONE);
                submitout.setVisibility(View.VISIBLE);                                  submitin.setVisibility(View.GONE);
                CancelOUT.setVisibility(View.VISIBLE);                                  CancelIN.setVisibility(View.GONE);
                dispatch.setVisibility(View.GONE);                                      dispatchnum.setVisibility(View.GONE);
                csr.setVisibility(View.GONE);                                           csrnum.setVisibility(View.GONE);
                it.setVisibility(View.GONE);                                            itnum.setVisibility(View.GONE);
                donotcallus.setVisibility(View.GONE);                                   googletalk.setVisibility(View.GONE);
                thoughts.setVisibility(View.GONE);                                      feed.setVisibility(View.GONE);
                send.setVisibility(View.GONE);                                          information.setVisibility(View.GONE);
                checkinbutton.setChecked(true);                                         

                vib.vibrate(80);

                //-------------------------------------------------------Custom Layout View for Check-Out Checkbox-------------------------------------------------------//
                inflater = getLayoutInflater();
                final View checkboxLayout = inflater.inflate(R.anim.verify, null);
                final CheckBox AgreeCheckBox = (CheckBox) checkboxLayout.findViewById(R.id.checkBox);

                //-------------------------------------------------------AlertDialog Meal-Periods Button Configurations-------------------------------------------------------//
                AlertDialog alertDialog = new AlertDialog.Builder(screen1.this).create();
                alertDialog.setCancelable(false);
                alertDialog.setTitle("            Rest Periods");
                alertDialog.setView(checkboxLayout);

                //-------------------------------------------------------FLAG_BLURBEHIND TO BLUR BACKGROUND-------------------------------------------------------//
                WindowManager.LayoutParams lp = alertDialog.getWindow().getAttributes(); 
                //alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // <--Blurring is no longer supported, Draws from hardware. Too many rendering issues and unresponsiveness with certain phones
                alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                lp.dimAmount = .35f;
                alertDialog.getWindow().setAttributes(lp);
                alertDialog.setButton("Agree", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                if (AgreeCheckBox.isChecked()) {
                                    // If CheckBox is Checked
                                    String text = "<font color=\"#CC0000\"> Checking-Out... </font>";
                                    checkin.setText(Html.fromHtml(text),BufferType.SPANNABLE);
                                    checkinbutton.setEnabled(false);


                                } else {
                                    // If CheckBox Isnt Checked
                                    String text = "<font color=\"#A2E8\"> You are currently Checked-In </font>";
                                    checkin.setText(Html.fromHtml(text),BufferType.SPANNABLE);

statuspage.java

 public class statuspage extends MapActivity {

//////////////////////////    Map and MapView Initializers    //////////////////////////////////////////////     
LocationManager locationManager;        MapView mapView;        Criteria criteria;      Vibrator vib;    ///
Location location;                      Geocoder gc;                                    Address address; ///
MapController mapController;            MyLocationOverlay myLocation;                                    ///
////////////////////////////////////////////////////////////////////////////////////////////////////////////

StringBuilder sb;
String username, password, bestProvider, firstName, lastName, lastLatitudeUpdate;
String LOCATION_SERVICE = "location", addressString = "Searching for nearest address";


int checkedin, Minute, Hour;
Timer EnableLocationonResume;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.statuspage);
    vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);    




public class GeoCoder extends AsyncTask<Void, Void, Void> {

    String lat = "Acquiring", lng ="Acquiring";

    // scrollview will be used to view jobs using a listview Latitude and Longitude TextView
    TextView YourLocation = (TextView) findViewById(R.id.YourLocation);
    TextView etlongitude = (TextView) findViewById(R.id.etlongitude);
    TextView etlatitude = (TextView) findViewById(R.id.etlatitude);


    @Override
    protected Void doInBackground(Void... params) {

        if (location != null) {

            //double latitude = myLocation.getMyLocation().getLatitudeE6();         double longitude = myLocation.getMyLocation().getLongitudeE6(); 
            double latitude = location.getLatitude();                               double longitude = location.getLongitude();
                    lat = ("" + (latitude));                                                lng = ("" + (longitude));


            Geocoder gc = new Geocoder(getBaseContext(),Locale.getDefault());
            try {
                List<Address> addresses = gc.getFromLocation(latitude,longitude, 1);

                sb = new StringBuilder();
                if (addresses.size() > 0) {
                    address = addresses.get(0);
                    int noOfMaxAddressLine = address.getMaxAddressLineIndex();
                    if (noOfMaxAddressLine > 0) {
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        addressString = sb.toString();
                    }
                }
            } catch (Exception e) {
                addressString = "Sorry, we are trying to find information about your location";
            }
        }
        return null;
    }


    @Override
    protected void onPostExecute(Void result) {

        /////////   Animates the map to GPS Position   ////////////////////
        myLocation.runOnFirstFix(new Runnable() {                       //
            @Override                                                  //
            public void run() {                                       //
                mapController.animateTo(myLocation.getMyLocation()); //
        //////////////////////////////////////////////////////////////
            }
        });

        runOnUiThread(new Runnable() {
            public void run() {

                ////////////////TODO TextView to display GeoCoder Address TODO///////////////////////////////////////////
                                    YourLocation.setGravity(Gravity.CENTER);                                          //
                YourLocation.setText("Your location:" + "\n" + "(Accurate to 500 meters)" + "\n" + (addressString)); //
                                                                                                                    //
                ////////TODO Latitude and Longitude TextView Display Coordinates TODO////////////////////////////////
                etlatitude.setText(lat);                                    etlongitude.setText(lng);             //
                                         Log.d("Address", (addressString));                                      //
            }   //////////////////////////////////////////////////////////////////////////////////////////////////
        });
        super.onPostExecute(result); 
        return;
    }
}                                                                                                                                                                                   

private final LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        new GeoCoder().execute();       
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};

///////////// Class EnableLocation is a Timer Created To Start GPS and GeoCode Updates ///////////////////////////////
public class EnableLocation extends TimerTask {                                                                     //
                                                                                                                    //
//*************************** Uses runOnUiThread to Keep UI updating in Background *********************************//  
    @Override                                                                                                       //
    public void run() {                                                                                             //
        runOnUiThread(new Runnable() {                                                                              //
            @Override                                                                                               //
            public void run() {                                                                                     //
                myLocation.enableMyLocation();                                                                      //
                //location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);                    //
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, locationListener);  //
                new GeoCoder().execute();                                                                           //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////          
            }
        });
    }
}

// Class DisableLocation is a Timer Created to Stop GPS Updates then Toasts NewLocation
class DisableLocation extends TimerTask {

    // Uses runOnUiThread to Keep UI updating in Background
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                myLocation.disableMyLocation();
                locationManager.removeUpdates(locationListener);

                // get your custom_toast.xml ayout
                LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.anim.custom_toast,(ViewGroup) findViewById(R.id.custom_toast_layout_id));
                // set a dummy image
                ImageView image = (ImageView) layout.findViewById(R.id.image);
                image.setImageResource(R.drawable.toastjet);

                // set a message
                TextView text = (TextView) layout.findViewById(R.id.text);
                text.setGravity(Gravity.CENTER);
                text.setText("Location has changed to" + "\n" + (addressString));

                // Toast...
                Toast location = new Toast(getApplicationContext());
                location.setDuration(Toast.LENGTH_LONG);
                location.setView(layout);
                location.show();
            }
        });
    }
}


@Override
protected void onResume() {
    super.onResume();
    myLocation.enableMyLocation();

    // Fires GPS Updates
    EnableLocationonResume = new Timer();
    EnableLocation myTimerTask1 = new EnableLocation();
    EnableLocationonResume.scheduleAtFixedRate(myTimerTask1, 100, 10000);

    overridePendingTransition(R.anim.fadein, R.anim.fadeout);

}

@Override
protected void onPause() {
    super.onPause();


    EnableLocationonResume.cancel();
    myLocation.disableMyLocation();
    locationManager.removeUpdates(locationListener);

    //////////////////// Fires GPS Updates ///////////////////////////////
    Timer EnableLocationonPause = new Timer();                          //
    EnableLocation myTimerTask = new EnableLocation();                  //
    EnableLocationonPause.scheduleAtFixedRate(myTimerTask, 0, 2280000); //
    //////////////////////////////////////////////////////////////////////

    //////////////////// Kills GPS Updates ///////////////////////////////////////
    Timer DisableLocationonPause = new Timer();                                 //
    DisableLocation disableLocation = new DisableLocation();                    //
    DisableLocationonPause.scheduleAtFixedRate(disableLocation, 10000, 2370000);//
    //////////////////////////////////////////////////////////////////////////////


    overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}

@Override
public void onBackPressed() {

    EnableLocationonResume.cancel();
    myLocation.disableMyLocation();
    locationManager.removeUpdates(locationListener);

    // 2280000 Milliseconds = 38 Minutes
    // 2370000 Milliseconds = 39.5 Minutes
    // 2400000 Milliseconds = 40 Minutes
    // 2490000 Milliseconds = 41.5 Minutes
    // 2520000 Milliseconds = 42 Minutes
    // 2700000 Milliseconds = 45 Minutes
    // 2790000 Milliseconds = 46.5 Minutes
    // 2820000 Milliseconds = 47 Minutes
    // 2850000 Milliseconds = 47.5 Minutes

    ///////////////// Fires GPS Updates //////////////////////////
    Timer EnableLocation = new Timer();                         //
    EnableLocation EnableLocationTask = new EnableLocation();   //
    EnableLocation.scheduleAtFixedRate(EnableLocationTask, 0, 2280000);// <--- 2280000 = 38 Minutes
    //////////////////////////////////////////////////////////////

    ///////////////////// Kills GPS Updates ////////////////////////////////
    Timer DisableLocation = new Timer();                                  //
    DisableLocation disableLocation = new DisableLocation();              //
    //---------------------------------------------Delays for 10,000 Milliseconds (10 Seconds) to Continue to Poll for  GPS--------------------------------------------//
    DisableLocation.scheduleAtFixedRate(disableLocation, 10000, 2370000); // <--- 2370000 = 39.5 Minutes
    ////////////////////////////////////////////////////////////////////////


    vib.vibrate(40);

    // Send username and password strings into screen1 class
    Intent i = new Intent(statuspage.this, screen1.class);
    i.putExtra("uid", username);    i.putExtra("pwd", password);    i.putExtra("firstName", firstName);     i.putExtra("lastName", lastName);   
    i.putExtra("checkedin", checkedin); i.putExtra("lastLatitudeUpdate", lastLatitudeUpdate);   i.putExtra("Minute", Minute);   i.putExtra("Hour", Hour);   startActivity(i);
    startActivity(i);


    /** Fading Transition Effect */
    overridePendingTransition(R.anim.fadein, R.anim.fadeout);

    return;

}

}

編集:基本的に、screen1.javaからGeoCoderクラスを実行できる方法があるかどうか疑問に思っていました

4

2 に答える 2

0

次のようにアクセスできます。

Activity1.GeoCoder coder = new Activity1.GeoCoder();

または適切なコンストラクターを使用する

于 2012-06-08T16:40:24.500 に答える
0

あなたGeoCoderは ではないのでstatic、最初にオブジェクトをインスタンス化しActivity2てアクセスする必要があります。

内部Activity1:

Activity2 myActivity2 = new Activity2();
GeoCoder myGeoCoder = myActivity2.new GeoCoder();

GeoCoderただし、 asを作成するstaticと、次の方法でアクセスできます。

GeoCoder myGeoCoder = new Activity2.GeoCoder();

編集: anAsyncTaskから anotherを呼び出すことはお勧めしませんActivityAsyncTaskは、接続先の に密接に結び付けられるように設計されてActivityいます。代わりに、 の別のサブクラスを宣言AsyncTaskしますActivity1

于 2012-06-08T16:42:58.997 に答える