从另一个类调用MainActivity函数作为MainActivity

时间:2013-02-24 12:32:30

标签: java android

我想在数据更改后重新加载MainActivity。所以我编写了这段代码并且运行良好。

这是来自MainActivity,我想重新加载:

public class MainActivity extends Activity {
private static final int RESULT_SETTINGS = 1;
LinearLayout horizontalForecast, todayForecast, tomorrowForecast;
TextView ViewSunRise, ViewSunSet, NowTatva, NextTejas, Longitude, Latitude, BeziT, TatvicForecast;
TextView Today, Tomorrow, NextTatva;
GPSTracker gps;
ImageView img;
TabHost th;

public void reload() {
    finish();
    Intent i2 = new Intent(MainActivity.this, MainActivity.class);
    startActivityForResult(i2, RESULT_SETTINGS);
}
}

但是当我从另一个类(不是活动)调用它时,它不起作用。

这是来自另一个班级:

package com.reversity.simpletatva;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

MainActivity MA;
boolean ch = false;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location = null; // location
double latitude = Double.NaN; // latitude
double longitude = Double.NaN; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

protected static final int RESULT_SETTINGS = 1;

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

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

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS");

    // Setting Dialog Message
    alertDialog.setMessage("GPS není zapnuta, lokace byla nastavena na 0. Chcete přejít do nastavení nebo nastavit vlastní?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Nastavení", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Použít vlastní", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent i = new Intent(mContext, Preference.class);
            mContext.startActivity(i);
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
    /*
    Toast changed = Toast.makeText(mContext, "Location changes", Toast.LENGTH_LONG);
    changed.show();
    MA.reload();
    startActivity(new Intent(mContext, MainActivity.class));
    invalidate();
    */
    stopUsingGPS();
    MainActivity mainActivity = new MainActivity ();
    mainActivity.reload();
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

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

public Boolean locChanged(){
    return ch;

}

}

所以我希望在MainActivity时从GPSTracker Class重新加载onLocationChanged(); 我找不到对我有用的答案。所以我问这个问题。不要怪我。

我只需要如何调用MainActivityGPSTracker Class重新加载。 我尝试了我所知道的一切。但它不起作用,Aplication将关闭。

错误NullPointerException

3 个答案:

答案 0 :(得分:2)

您正试图从静态上下文中调用非静态方法。

reload方法设为静态,或使用对MainActivity实例的引用(例如MainActivity myActivity; myActivity.reload()

或者,也许你想让Activity2扩展MainActivity?

答案 1 :(得分:2)

您需要向第二个类传递对MainActivity的引用,并在该引用上调用reload()

对于通用类:

public class SecondClass {

    MainActivity mActivity;

    // Constructor where you pass a reference to MainActivity
    public SecondClass(Activity activity) {
        mActivity = activity;
    }

    public onChange() {
        mActivity.reload();
    }
}

初始化SecondClass中的MainActivity时,您会传递对MainActivity的引用

SecondClass secondClass = new SecondClass(this);

然后您可以使用onChange(),并且应该调用MainActivity.reload()

secondClass.onChange();

修改

嗯,既然你更新了你的问题,我的答案就不再正确了。由于您的第二个类是Service,因此保留对MainActivity的引用可能会造成内存泄漏。

我会在BroadcastReceiver中注册MainActivity来解决这个问题。在Service中,当需要更新时,您广播Intent

这看起来像这样: 在MainActivity

public void MainActivity extends Activity {
    private BroadcastReceiver mReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
       .
       .
       .

       // We listen for a broadcasted Intent with 
       // action = com.example.ACTION_RELOAD_MAINACTIVITY
       IntentFilter filter = new IntentFilter();
       filter.addAction("com.example.ACTION_RELOAD_MAINACTIVITY");

       // Init the receiver
       mReceiver = new BroadcastReceiver() {
           @Override
           public void onReceive(Context context, Intent intent) {                   
               // Reload when we receive the broadcast
               MainActivity.this.reload();
           }
       }

       // Register the receiver
       registerReceiver(mReceiver, filter);
    }

    // In onDestroy() we unregister the receiver
    @Override
    public void onDestroy() {
        unregisterReceiver(mReceiver);
    }
}

Service中,当您要重新加载Intent时,您现在必须广播MainActivity

public class GPSTracker extends Service implements LocationListener {
    .
    .
    .

    @Override
    public void onLocationChanged(Location location) {
        // Create an Intent with 
        // action = com.example.ACTION_RELOAD_MAINACTIVITY
        Intent i = new Intent("com.example.ACTION_RELOAD_MAINACTIVITY");  

        // As a side note; You can use this Intent to send data to MainActivity.
        // If you want to pass the Location object of onLocationChanged() to
        // MainActivity, you would simply call i.putExtra("current_location", location) 
        // The data can then be fetched using the supplied Intent in onReceive().

        // Broadcast that Intent
        sendBroadcast(i);
    }
}

答案 2 :(得分:0)

你可以做的只是在Androidmanifest.xml文件中添加它,你在活动标记中声明了你的主要活动

  android:finishOnTaskLaunch="true"

并从重新加载方法中删除finish();

现在在GPSTracker课程中,只需通过调用

启动活动
Intent intent=new Intent(mContext,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);