如何在Activity和Class之间共享这些变量?

时间:2016-03-29 16:29:56

标签: java android

我有一个使用服务的应用。但由于某种原因,该服务无法识别变量“placeArrayList”,“latitudeArrayList”,“longitudeArrayList”和“destination”。
我能在这做什么?

MainActivity.java

public class MainActivity extends AppCompatActivity {
PlacePicker.IntentBuilder builder;
int PLACE_PICKER_REQUEST;
ListView placeListView;
ArrayList<String> placeArrayList;
ArrayList<String> latitudeArrayList;
ArrayList<String> longitudeArrayList;
ArrayAdapter<String> arrayAdapter;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
ArrayList<Double> latitudeList;
Integer counter;
LocationManager locationManager;
String provider;
double lat;
double lng;
Place place;
static Set<String> set;
static Set<String> set1;
static Set<String> set2;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
placeListView = (ListView) findViewById(R.id.placeListView);
latitudeList = new ArrayList<>();
placeArrayList = new ArrayList<String>();
latitudeArrayList = new ArrayList<String>();
longitudeArrayList = new ArrayList<String>();



LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), false);


if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    //    ActivityCompat#requestPermissions
    // here to request the missing permissions, and then overriding
    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
    //                                          int[] grantResults)
    // to handle the case where the user grants the permission. See the documentation
    // for ActivityCompat#requestPermissions for more details.
    return;
}
final Location location = locationManager.getLastKnownLocation(provider);


final Location destination = new Location(provider);
destination.setLatitude(location.getLatitude());
destination.setLongitude(location.getLongitude());
Log.e("shit", String.valueOf(location.distanceTo(destination)));


ListView listView = (ListView) findViewById(R.id.placeListView);

SharedPreferences sharedPreferences = this.getSharedPreferences("bro", Context.MODE_PRIVATE);

set = sharedPreferences.getStringSet("names", null);

set1 = sharedPreferences.getStringSet("lats", null);
set2 = sharedPreferences.getStringSet("lngs", null);


placeArrayList.clear();
latitudeArrayList.clear();
longitudeArrayList.clear();

if (set != null) {

    placeArrayList.addAll(set);
    latitudeArrayList.addAll(set1);
    longitudeArrayList.addAll(set2);

} else {

    placeArrayList.add("Hold to delete");
    set = new HashSet<String>();
    set.addAll(placeArrayList);
    sharedPreferences.edit().putStringSet("names", set).apply();
    latitudeArrayList.add(String.valueOf("66.56083"));
    set1 = new HashSet<String>();
    set1.addAll(latitudeArrayList);
    sharedPreferences.edit().putStringSet("lats", set1).apply();
    longitudeArrayList.add(String.valueOf("39.3232"));
    set2 = new HashSet<String>();
    set2.addAll(longitudeArrayList);
    sharedPreferences.edit().putStringSet("lngs", set2).apply();

}



arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, placeArrayList);

listView.setAdapter(arrayAdapter);





placeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {


        new AlertDialog.Builder(MainActivity.this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Are you sure?")
                .setMessage("Do you want to delete this place?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                        placeArrayList.remove(position);

                        latitudeArrayList.remove(position);

                        SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences("bro", Context.MODE_PRIVATE);

                        if (set == null) {

                            set = new HashSet<String>();
                            set1 = new HashSet<String>();
                            set2 = new HashSet<String>();

                        } else {

                            set.clear();
                            set1.clear();
                            set2.clear();

                        }


                        set.addAll(placeArrayList);
                        set1.addAll(latitudeArrayList);
                        set2.addAll(longitudeArrayList);
                        sharedPreferences.edit().remove("names").apply();
                        sharedPreferences.edit().remove("lats").apply();
                        sharedPreferences.edit().remove("lngs").apply();
                        sharedPreferences.edit().putStringSet("names", set).apply();
                        sharedPreferences.edit().putStringSet("lats", set1).apply();
                        sharedPreferences.edit().putStringSet("lngs", set2).apply();
                        arrayAdapter.notifyDataSetChanged();


                    }
                })
                .setNegativeButton("No", null)
                .show();


        return false;
    }
});




final android.os.Handler handler = new android.os.Handler();
Runnable run = new Runnable() {
    @Override
    public void run() {

        if (location != null) {


            lat = location.getLatitude();

            lng = location.getLongitude();


            if (placeArrayList.size() != 0) {
                for (int i = 0; i < placeArrayList.size(); i++) {


                    Log.e("hello", String.valueOf(Float.parseFloat(latitudeArrayList.get(i))));

                    destination.setLatitude(Double.parseDouble(latitudeArrayList.get(i)));
                    destination.setLongitude(Double.parseDouble(longitudeArrayList.get(i)));
                    Log.e("distancemeters", String.valueOf(location.distanceTo(destination)));

                    if (location.distanceTo(destination)<100) {




                        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

                        audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);


                    } else {



                    }

                }


            }
        }


        handler.postDelayed(this, 10000);
    }
};
handler.post(run);










arrayAdapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        PLACE_PICKER_REQUEST = 1;
        builder = new PlacePicker.IntentBuilder();
        pickPlace();

    }
});
}


public void pickPlace() {

try {
    startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
    e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
    e.printStackTrace();
}


}




@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PLACE_PICKER_REQUEST) {
    if (resultCode == RESULT_OK) {
        place = PlacePicker.getPlace(data, this);
        // String toastMsg = String.format("Place: %s", place.getName());
        //Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();



        placeArrayList.add(String.valueOf(place.getName()));
        latitudeArrayList.add(String.valueOf(place.getLatLng().latitude));
        longitudeArrayList.add(String.valueOf(place.getLatLng().longitude));
        arrayAdapter.notifyDataSetChanged();
        startService(new Intent(getBaseContext(), myService.class));

        SharedPreferences sharedPreferences = getSharedPreferences("bro", Context.MODE_PRIVATE);

        if (set == null) {

            set = new HashSet<String>();
            set1 = new HashSet<String>();
            set2 = new HashSet<String>();

        } else {

            set.clear();
            set1.clear();
            set2.clear();

        }


        arrayAdapter.notifyDataSetChanged();
        set.addAll(placeArrayList);
        set1.addAll(latitudeArrayList);
        set2.addAll(longitudeArrayList);
        sharedPreferences.edit().remove("names").apply();
        sharedPreferences.edit().remove("lats").apply();
        sharedPreferences.edit().remove("lngs").apply();
        sharedPreferences.edit().putStringSet("names", set).apply();
        sharedPreferences.edit().putStringSet("lats", set1).apply();
        sharedPreferences.edit().putStringSet("lngs", set2).apply();





    }

}
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
    return true;
}

return super.onOptionsItemSelected(item);
}


}

myService.java

public class myService extends Service implements LocationListener {
Double lat;
Double lng;
@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;


}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}

@Override
public void onLocationChanged(Location location) {

if (location != null) {


   lat = location.getLatitude();

    lng = location.getLongitude();


    if (placeArrayList.size() != 0) {
        for (int i = 0; i < placeArrayList.size(); i++) {


            Log.e("hello", String.valueOf(Float.parseFloat(latitudeArrayList.get(i))));

            destination.setLatitude(Double.parseDouble(latitudeArrayList.get(i)));
            destination.setLongitude(Double.parseDouble(longitudeArrayList.get(i)));
            Log.e("distancemeters", String.valueOf(location.distanceTo(destination)));

            if (location.distanceTo(destination)<100) {




                AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

                audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);


            } else {



            }

        }


    }
}

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

3 个答案:

答案 0 :(得分:1)

不要将变量设为静态。因为它可能导致内存泄漏。这根本不是一个好主意。 更好的方法是编写一个接口并在MainActivity类中实现它。 此接口将具有为变量分配新值的方法。 并从您的服务中调用Interface方法。

答案 1 :(得分:0)

由于Service是一个单独的类,因此它无法访问MainAcitivity的字段,因为它们超出了“myService”的范围。

如果要在调用Activity和被调用的服务之间共享信息,您将能够通过intent传递键值存储中的数据。

您可以将键值直接放入Intent:

 CGAL::Qt::GraphicsViewNavigation* navFilter = new  CGAL::Qt::GraphicsViewNavigation(view);
 view->viewport()->installEventFilter(navFilter);

您可以构建一个Bundle并将其添加到intent中。 Bundle有一些方法可以更容易地将丰富的数据放入其中。

Intent intent = new Intent(getBaseContext(), myService.class);
itent.putExtra(key, value);

通过文档查看有关Bundle的更多信息:http://developer.android.com/reference/android/os/Bundle.html

如果您对传递大量无法在键值对中轻松表示的数据感兴趣,那么您可能希望将数据组织到您自己的Parceable类中,该类也可以通过Intent传递。查看有关通过文档制作自己的Parceable的更多信息:http://developer.android.com/reference/android/os/Parcelable.html 并通过这个答案 How to send an object from one Android Activity to another using Intents?

答案 2 :(得分:0)

您可以将变量设为静态 然后通过在Activity名称前加上它们来引用它们。