-3

我想在数据更改后重新加载 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 ClassonLocationChanged(); 我找不到对我有用的答案时,我想重新加载。所以我问这个问题。不要怪我。

我只需要如何调用MainActivityGPSTracker Class. 我尝试了我所知道的一切。但它不起作用,应用程序将关闭。

错误NullPointerException

4

3 回答 3

2

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

要么使您的reload方法静态,要么使用对 MainActivity 实例的引用(例如MainActivity myActivity; myActivity.reload()

或者,也许您的意思是让 Activity2 扩展 MainActivity?

于 2013-02-24T12:42:46.120 回答
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();
    }
}

当您初始化SecondClassin时,MainActivity您将引用传递给MainActivity

SecondClass secondClass = new SecondClass(this);

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

secondClass.onChange();

编辑:

好吧,既然你更新了你的问题,我的答案不再正确。由于您的第二类是 a 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);
    }
}
于 2013-02-24T13:01:32.877 回答
0

您可以做什么只需将其添加到您在活动标签内声明主要活动的 Androidmanifest.xml 文件中

  android:finishOnTaskLaunch="true"

finish();从 reload 方法中删除。

现在在 GPSTracker 类中只需调用

Intent intent=new Intent(mContext,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
于 2013-02-24T13:27:06.403 回答