public class MainActivity extends AppCompatActivity {
private static final int REQUEST_LOCATION=1;
public static Context gb;
static LocationManager locationManager;
public static String latitude,longitude;
public MainActivity(Context context){
this.gb = context;
}
Button getlocationBtn;
static TextView showLocationTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Add permission
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
showLocationTxt=findViewById(R.id.show_location);
getlocationBtn=findViewById(R.id.getLocation);
getlocationBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//place the following line on all operations e.g click
locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Check gps is enable or not
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
//Write Function To enable gps
OnGPS();
}
else
{
//GPS is already On then
getLocation();
}
}
});
}
public static void getLocation() {
//Check Permissions again
if (ActivityCompat.checkSelfPermission(gb,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(gb, Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions((Activity)gb,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else
{
Location LocationGps= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location LocationNetwork=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location LocationPassive=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (LocationGps !=null)
{
double lat=LocationGps.getLatitude();
double longi=LocationGps.getLongitude();
latitude=String.valueOf(lat);
longitude=String.valueOf(longi);
showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
}
else if (LocationNetwork !=null)
{
double lat=LocationNetwork.getLatitude();
double longi=LocationNetwork.getLongitude();
latitude=String.valueOf(lat);
longitude=String.valueOf(longi);
showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
}
else if (LocationPassive !=null)
{
double lat=LocationPassive.getLatitude();
double longi=LocationPassive.getLongitude();
latitude=String.valueOf(lat);
longitude=String.valueOf(longi);
showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
}
else
{
Toast.makeText(gb, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
}
}
private void OnGPS() {
final AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog=builder.create();
alertDialog.show();
}
}
==================== Calling Activity==============================
package com.example.currentlocation;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class calling extends AppCompatActivity {
Button btnLoc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
btnLoc = (Button) findViewById(R.id.getLocation);
btnLoc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.getLocation();
}
});
}
}
===============================Question================================
Greetings! I am trying to write a code in java. I want to declare all of the methods in a single class with static modifier. So that whenever required I could call that method and perform function associated with that. in the given example I am trying to toast the current location which is working perfectly fine on button click. but when I try to call this static getLocation from another activity the app crashes.
There are a couple of things wrong with this, UI elements like the TextView, shouldn’t be static. If you want to modularise functions, you are better off writing Utils classes. Don’t try to access methods from other activities, even though it is possible to access non static methods, if you instantiate that particular Activity class. Static methods are almost useless in an Activity.
The Android system instantiates the Activities and calls the life cycle methods, to display and store info for that screen. Activities are not meant to be used as conventional classes. I would suggest studying the MVC architecture and Android activity life cycle.
Related
So I am trying to add Interstitial ads to my project.
This is my what my code looks like for the current JHAActivity.java:
Note: In my project I am using my own Ad unit ID from apps.admob.com insted of ca-app-pub-1111111111111111/2222222222.
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
public class JHAActivity extends AppCompatActivity {
private Button jhaButton;
// private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712"; Test AD
private static final String AD_UNIT_ID = "ca-app-pub-1111111111111111/2222222222";
private InterstitialAd mInterstitialAd;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// R.menu.mymenu is a reference to an xml file named mymenu.xml which should be inside your res/menu directory.
// If you don't have res/menu, just create a directory named "menu" inside res
getMenuInflater().inflate(R.menu.mymenu, menu);
return super.onCreateOptionsMenu(menu);
}
// handle button activities
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.mybutton) {
// do something here
if (Locale.getDefault().getLanguage().equals("en")) { // If English
new AlertDialog.Builder(this)
.setTitle(R.string.rules)
.setMessage(rulesENG)
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
} else { // Else if not English
new AlertDialog.Builder(this)
.setTitle(R.string.rules)
.setMessage(rules)
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jha);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(AD_UNIT_ID);
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(LoadAdError adError) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when the ad is displayed.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
});
jhaButton = (Button) findViewById(R.id.button);
jhaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJHA();
}
});
}
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and restart the game.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
// Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
int counter = 0;
private void openJHA() {
counter++;
if (counter == 5) {
showInterstitial(); // Display AdMob AD
counter = 0;
}
}
}
So basically when using ca-app-pub-3940256099942544/1033173712 as Ad unit ID, it displays the test ad each time I have pressed the jhaButton 5 times, but when using my own Ad unit ID, the ad does not show up at all. In the run log it just says: D/TAG: The interstitial wasn't loaded yet.. What am I doing wrong here?
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(LoadAdError adError) {
// Code to be executed when an ad request fails.
}
your mInterstitialAd.loadAd(xxx) tried to load once but it is often that onAdFailedToLoad(LoadAdError adError) returned and if you didn't do sth like mInterstitialAd.loadAd again to get a try, it will stop and never jump to onAdLoaded(). Hence your mInterstitialAd.isLoaded() will almost return false.
Every time you want to use mInterstitialAd.showAd(), please check first if (!mInterstitialAd.isLoaded()){mInterstitialAd.showAd() } first
The big problem is that recent Admob used SDK v19.7.0 . codes related to InterestitialAd need to be modified again...And I don't know why the callback lose the function about onAdClicked.
What's wrong with this code? I am running the following code in MainActivity but I get only an empty app:
package com.example.testbar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.google.zxing.Result;
import android.util.Log;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Programmatically initialize the scanner view
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v("TAG", rawResult.getText()); // Prints scan results
// Prints the scan format (qrcode, pdf417 etc.)
Log.v("TAG", rawResult.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(rawResult.getText());
AlertDialog alert1 = builder.create();
alert1.show();
// If you would like to resume scanning, call this method below:
mScannerView.resumeCameraPreview(this);
}
#Override
public void onResume() {
super.onResume();
// Register ourselves as a handler for scan results.
mScannerView.setResultHandler(this);
// Start camera on resume
mScannerView.startCamera();
}
#Override
public void onPause() {
super.onPause();
// Stop camera on pause
mScannerView.stopCamera();
}
}
I've added the permissions in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus"/>
The code builds without errors in Android Studio but I only get an empty app... and no camera when the app runs.
You should follow Android's documentation for checking and requesting permissions.
https://developer.android.com/training/permissions/requesting
I have modified your code and this should be a working sample.
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private static final int MY_PERMISSIONS_REQUEST_CAMERA = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// Programmatically initialize the scanner view
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v("TAG", rawResult.getText()); // Prints scan results
// Prints the scan format (qrcode, pdf417 etc.)
Log.v("TAG", rawResult.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(rawResult.getText());
AlertDialog alert1 = builder.create();
alert1.show();
// If you would like to resume scanning, call this method below:
mScannerView.resumeCameraPreview(this);
}
#Override
public void onResume() {
super.onResume();
// Register ourselves as a handler for scan results.
mScannerView.setResultHandler(this);
// Start camera on resume
if (hasPermission(Manifest.permission.CAMERA)) {
startCamera();
}
}
#Override
public void onPause() {
super.onPause();
// Stop camera on pause
mScannerView.stopCamera();
}
private void startCamera() {
mScannerView.startCamera();
}
private Boolean hasPermission(String permission) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
// you need to request the permission
Log.d("TAG", "User hasn't granted permission.");
// No explanation needed for camera. request the permission
ActivityCompat.requestPermissions(this,
new String[]{permission},
MY_PERMISSIONS_REQUEST_CAMERA);
}
else {
Log.d("TAG", "User already granted permission.");
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_CAMERA:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
Log.d("TAG", "Permission denied by user...");
}
break;
}
}
}
Im in need of some help.
Secondary Activity
package archtectsproductions.scriptpyandroidwearwatchface;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import static android.graphics.Color.BLUE;
import static android.graphics.Color.GREEN;
import static android.graphics.Color.RED;
public class WatchfaceConfigActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private int mTextColor = 0xffffffff;
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watchface_config);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Wearable.API)
.build();
Button buttonOK = (Button)findViewById(R.id.buttonOK);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup radioTextColor =
(RadioGroup)findViewById(R.id.rGroup);
int selectedId = radioTextColor.getCheckedRadioButtonId();
switch (selectedId) {
default:
case R.id.rDarkpastel:
mTextColor = 0xffffffff;
break;
case R.id.Notepad:
mTextColor = GREEN;
break;
case R.id.rHarvenjark:
mTextColor = BLUE;
break;
case R.id.rVibrant:
mTextColor = RED;
break;
}
sendParamsAndFinish();
}
});
}
// sends data through Google API
private void sendParamsAndFinish() {
PutDataMapRequest putDataMapReq =
PutDataMapRequest.create("/watch_face_config_cliu");
putDataMapReq.getDataMap().putInt("text_color", mTextColor);
PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq);
finish();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
MAIN
public class WatchFaceCLiuService extends
CanvasWatchFaceService {
private static final long UPDATE_INTERVAL =
TimeUnit.SECONDS.toMillis(1);
#Override
public Engine onCreateEngine() {
return new Engine();
}
private class Engine extends CanvasWatchFaceService.Engine implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
...
private GoogleApiClient mGoogleApiClient;
private int mTextColor = 0xffffffff;
private float offsetx = (float)(-50 + 100 * Math.random());
private float offsety = (float)(-50 + 100 * Math.random());
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
...
mGoogleApiClient = new GoogleApiClient.Builder(WatchFaceCLiuService.this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
...
#Override
public void onDraw(Canvas canvas, Rect bounds) {
...
canvas.drawText(ts1, tx1, ty1, mDigitalPaint);
...
}
private void releaseGoogleApiClient() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Wearable.DataApi.removeListener(mGoogleApiClient,
onDataChangedListener);
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
Wearable.DataApi.addListener(mGoogleApiClient,
onDataChangedListener);
Wearable.DataApi.getDataItems(mGoogleApiClient).
setResultCallback(onConnectedResultCallback);
}
private void updateParamsForDataItem(DataItem item) {
if ((item.getUri().getPath()).equals("/watch_face_config_cliu")) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
if (dataMap.containsKey("text_color")) {
int tc = dataMap.getInt("text_color");
mDigitalPaint.setColor(tc);
invalidate();
}
}
}
private final DataApi.DataListener onDataChangedListener =
new DataApi.DataListener() {
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = event.getDataItem();
updateParamsForDataItem(item);
}
}
dataEvents.release();
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
};
private final ResultCallback<DataItemBuffer>
onConnectedResultCallback =
new ResultCallback<DataItemBuffer>() {
#Override
public void onResult(DataItemBuffer dataItems) {
for (DataItem item : dataItems) {
updateParamsForDataItem(item);
}
dataItems.release();
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult
connectionResult) {
}
#Override
public void onDestroy() {
mUpdateTimeHandler.removeMessages(MESSAGE_ID_UPDATE_TIME);
releaseGoogleApiClient();
super.onDestroy();
}
}
}
I really need help, I'm bashing my head against a brick wall. this just doesn't work. it wont send int across at all. Ive followed a guide. Ive done my best it just wont send, does anyone know a better way? should I make a global? would that work better but I'm not sure how id do it as I seem limited on what code I can use in the canvas watchface service.
all I want Is to send an int from one activity to another. Using a watchface service not a companion. I want to learn. so if you do answer don't just paste the code straight out, unless its easier to just paste the code and I can follow it, and decipher it.
thank you for any help .
<-- old
While I understand how to make in java a simple app that saves the users selection of a radio button and then puts it over to a separate activity to, say, change the color of text, i have hit a point where im struggling to do so in android wear.
The reason being i cant Implement the following.
#overide
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Radiogroup = (RadioGroup)findViewById(R.id.myyrad);
Radiogroup.setOnCheckedChangedListener(new OnCheckedChangedListener()) { ....
the following cant be implemented on the wallpaper service?
is there any alternative? or do i have to go the extremely confusing googleapiclient route? any help would be greatly appreciated thank you.
This was solved. Nothing wrong with the tutorial or my code. Studio was looking for a different android play service. Changed it in the gradel
I have a dialog that adds items to a listview, and when an item is added I need to reset the list adapter (because if not things get weird).
I read here that I can create an event listener and listen to it in the main activity. I tried doing so but it gives me errors.
AddMovieDialog.java:
public class AddMovieDialog extends DialogFragment {
private OnFinishListener onFinishListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setView(inflater.inflate(R.layout.add_movie_dialog, null))
.setTitle("Add a movie")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// stuff
if (!movieName.isEmpty()) {
// stuff
if (AddMovieDialog.this.onFinishListener != null)
AddMovieDialog.this.onFinisheListener.finish();
}
}
});
// Create the AlertDialog object and return it
return builder.create();
}
public void setOnFinishListener(OnFinishListener listener) {
this.onFinishListener = listener;
}
public interface OnFinishListener {
void finish();
}
}
In the MainActivity:
AddMovieDialog addMovieDialog = new AddMovieDialog();
addMovieDialog.setOnFinishListener(new OnFinishListener() {
public void finish() {
}
});
But it gives me a compilation error: "The method setOnFinishListener(new OnFinishListener(){}) is undefined for the type AddMovieDialog"
You need to call a method which is non-static using the object. You can't call it using just the class name.
Change to this
AddMovieDialog addMovieDialog = new AddMovieDialog();
addMovieDialog .setOnFinishListener(new OnFinishListener() {
public void finish() {
}
});
Also shouldn't
if (AddMovieDialog.this.onCloseListener != null)
AddMovieDialog.this.onCloseListener.finish();
be
if (AddMovieDialog.this.onFinishListener != null)
AddMovieDialog.this.onFinishListener.finish();
EDIT
Seem your import statement in MainActivity is wrong. It should be something like com.yourpackagename.AddMovieDialog.OnFinishListener
I want to reload MainActivity after data change. So I wrote this code and it working well.
This is from MainActivity, that i want to reload:
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);
}
}
But when I call this from another Class (not an activity), it doesn't work.
This is from another Class:
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;
}
}
So I want to Reload MainActivity from GPSTracker Class when onLocationChanged();
I don't find answer that will be usefull for me. So I ask this question. Don't blame me.
I just need how can I call the MainActivity to reload from GPSTracker Class.
I tried everything I know. But it isn't working and Aplication will close.
Error NullPointerException
You're trying to call a non-static method from a static context.
Either make your reload method static, or use a reference to an instance of MainActivity (e.g. MainActivity myActivity; myActivity.reload())
Alternatively, perhaps you meant for Activity2 to extend MainActivity?
You need to pass the second class a reference to MainActivity, and call reload() on that reference.
For a generic class:
public class SecondClass {
MainActivity mActivity;
// Constructor where you pass a reference to MainActivity
public SecondClass(Activity activity) {
mActivity = activity;
}
public onChange() {
mActivity.reload();
}
}
When you initialize the SecondClass in MainActivity you pass a reference to MainActivity
SecondClass secondClass = new SecondClass(this);
Then you can use onChange(), and MainActivity.reload() should get called.
secondClass.onChange();
EDIT:
Well, now that you updated your question, my answer is no longer correct. Since your second class is a Service, keeping references to your MainActivity might create memory leaks.
I would solve this with registering a BroadcastReceiver in your MainActivity. In your Service, you broadcast an Intent when an updated is needed.
This would look something like this:
In 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);
}
}
In your Service, you now have to broadcast an Intent when you want to reload 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);
}
}
what you can do just add this in the Androidmanifest.xml file where you declared your main activity inside the activity tag
android:finishOnTaskLaunch="true"
and remove finish(); from the reload method.
Now in GPSTracker class just start the activity by calling
Intent intent=new Intent(mContext,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);