I am working on an Android application that could recognize if the device is connected to a Network. If not, application display an AlertDialog and give the chance to the user to go to the device settings and open the wifi.
I have create a BroadcastReceiver for this job but i dont know how i can create an AlertDialog and give the option to the user to enable the the wifi.
Here is the code of BroadcastReceiver.
public class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false
);
if (noConnectivity) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
} else {
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
}
}
}
Please note, the below code is just for your reference. You could update/change this code based on your requirement.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerNetworkBroadcastForNougat();
}
private void registerNetworkBroadcastForNougat() {
mNetworkReceiver = new NetworkChangeReceiver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
try
{
if (!isOnline(context)) {
showDialog(context);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void showDialog(final Context context) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("You must have internet connection");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder1.create();
builder1.show();
}
private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
}
Related
I need to implement a QR Code scanner on an android project. I implemented the QR Code, however, I do not know how to switch to another action after QR is read.
I want to create an Intent to move to new action but I do not know where to add it.
I need the app to switch to another action as soon as it detects and reads QR Code.
code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_test);
CodeScannerView scannerViewTest = findViewById(R.id.scanner_view_test);
codeScannerTest = new CodeScanner(this, scannerViewTest);
askPermission();
if(CameraPermission) {
scannerViewTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
codeScannerTest.startPreview();
}
});
codeScannerTest.setDecodeCallback(new DecodeCallback() {
#Override
public void onDecoded(#NonNull Result result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanTest.this, result.getText(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
private void askPermission(){
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(ScanTest.this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERM);
}else {
codeScannerTest.startPreview();
CameraPermission = true;
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == CAMERA_PERM){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
codeScannerTest.startPreview();
CameraPermission = true;
}else{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)){
new AlertDialog.Builder(this)
.setTitle("Permission")
.setMessage("Please provide the camera permission for using all the features of the app")
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(ScanTest.this, new String[]{ Manifest.permission.CAMERA}, CAMERA_PERM);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else {
new AlertDialog.Builder(this)
.setTitle("Permission")
.setMessage("You have denied some permissions. Allow all permissions at [Settings] > [Permissions]")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent settings_intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getPackageName(), null));
settings_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(settings_intent);
finish();
}
}).setNegativeButton("No, Exit app", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).create().show();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onPause() {
if(CameraPermission){
codeScannerTest.releaseResources();
}
super.onPause();
}
You need to add it at the onDecoded method
codeScannerTest.setDecodeCallback(new DecodeCallback() {
#Override
public void onDecoded(#NonNull Result result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = Intent(this, YouNextActivity.class);
intent.putExtra("barcode", result.getText());
startActivity(intent);
//Toast.makeText(ScanTest.this, result.getText(), Toast.LENGTH_SHORT).show();
}
});
}
});
You can use the Intent.getExtra("barcode") and can get the value in your next Activity.
I need to make an app that sends an SMS message after showing a progress bar in increments of 10. I have the action bar set up and I think I should use AsyncTask? The user is inputing number and message into the main activity, and that's where I have the SendSMS method set up, not sure how to make this work so that it forwards to AsyncTask and calls on that method there.
public class MainActivity extends AppCompatActivity {
private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
private static final String SMS_SENT = "SMS_SENT";
private static final String SMS_DELIVERED= "SMS_DELIVERED";
private EditText etPoruka;
private EditText etBroj;
private ProgressDialog progressDialog;
private Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECEIVE_SMS},
MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
}
private void initWidgets() {
etPoruka = findViewById(R.id.etPoruka);
etBroj = findViewById(R.id.etBroj);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_send:
MyAsyncTask<Void, Void, Void> updateTask = new MyAsyncTask<Void, Void, Void>(context);
updateTask.execute();
break;
case R.id.action_sent:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
// BROADCAST RECEIVER ??
break;
case R.id.action_received:
Toast.makeText(this, R.string.add_test, Toast.LENGTH_LONG).show();
//BROADCAST RECEIVER ??
//BOUND SERVICE
break;
case R.id.action_exit:
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Close app");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return true;
}
public void sendSMS() {
try{
SmsManager smgr = SmsManager.getDefault();
smgr.sendTextMessage(etBroj.getText().toString(),null,etPoruka.getText().toString(),null,null);
Toast.makeText(MainActivity.this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
ASYNCTASK
public class MyAsyncTask extends
AsyncTask {
private final String DIALOG_MESSAGE = "Sending message";
private ProgressDialog mDialog = null;
private void setDialog(Context context) {
this.mDialog = new ProgressDialog(context);
this.mDialog.setMessage(DIALOG_MESSAGE);
this.mDialog.setCancelable(false);
}
public MyAsyncTask(Context context) {
this.setDialog(context);
}
#Override
protected void onPreExecute() {
this.mDialog.show();
}
#Override
protected Result doInBackground(Params... arg0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Result result) {
if (this.mDialog.isShowing()) {
this.mDialog.dismiss();
}
} }
You can create an Interface and implement in your MainActivity.
For More Details Please check these answers:
how do i send data back from onPostExecute in an AsyncTask?
How to pass data from an asynchronous task to an activity that called it?
This is my code it is working fine it scans Qr/Barcode, but I want scanned data to insert in fire-base database. This app is connected with fire-base and using ML kit for barcode scanning. This app also has login signup connected with fire-base auth and scanner app. but I don't know how to push scanned data in fire-base realtime database in android studio.
public class MainActivity extends AppCompatActivity {
View view;
CameraView camera_view;
boolean isDetected= false;
Button btn_start_again;
private static final String TAG = "MainActivity";
FirebaseVisionBarcodeDetectorOptions options;
FirebaseVisionBarcodeDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Dexter.withActivity(this)
.withPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
setupCamera();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
}
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
private void setupCamera()
{
btn_start_again= (Button)findViewById(R.id.btn_again);
btn_start_again.setEnabled(isDetected);
btn_start_again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
camera_view = (CameraView)findViewById(R.id.cameraView);
camera_view.setLifecycleOwner(this);
camera_view.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame)
{
processImage(getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private void processImage(FirebaseVisionImage image){
if(!isDetected)
{
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes){
if (firebaseVisionBarcodes.size()>0)
{
isDetected = true;
btn_start_again.setEnabled(isDetected);
for(FirebaseVisionBarcode item: firebaseVisionBarcodes)
{
int value_type = item.getValueType();
switch (value_type)
{
case FirebaseVisionBarcode.TYPE_TEXT:
{
createDialog(item.getRawValue());
}
break;
case FirebaseVisionBarcode.TYPE_URL:
{
//start browser intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getRawValue()));
startActivity(intent);
}
break;
case FirebaseVisionBarcode.TYPE_CONTACT_INFO:
{
String info = new StringBuilder("Name: ")
.append(item.getContactInfo().getName().getFormattedName())
.append("\n")
.append("Address: ")
.append(item.getContactInfo().getAddresses().get(0).getAddressLines())
.append("\n")
.append("Email: ")
.append(item.getContactInfo().getEmails().get(0).getAddress())
.toString();
createDialog(info);
}
break;
default:
break;
}
}
}
}
private void createDialog(String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(text)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private FirebaseVisionImage getVisionImageFromFrame(Frame frame){
byte[] data= frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize() .getHeight())
.setWidth(frame.getSize() .getWidth())
//.setRotation(frame.getRotation())
.build();
return FirebaseVisionImage.fromByteArray(data,metadata);
}
}
i am making a app in which on click of button it moves from 1 activity to 2nd activity on which i need gps to be active i used a alertdialog box to turn on the gps by clicking settings it will open to the setting and if i enable it dialogbox disapper and gps start working but if i press back button without enabling the gps it works and activity starts i want to check if gps is enabled if not the it should not show me the 2nd activity
No Error Coming but just on back press on setting without enabling it will start activity without any error and still gps is off.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView1 = (TextView) findViewById(R.id.location_view);
button1 = (Button) findViewById(R.id.camera);
button2 = (Button) findViewById(R.id.upload);
editText1 = (EditText) findViewById(R.id.remarks);
imageView11 = (ImageView) findViewById(R.id.image1);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
locationText = (TextView) findViewById(R.id.location_view);
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat
.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission
.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, (LocationListener) this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Account Clicked",Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Logout");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Logout ");
alerDialogbuilder.setMessage("Logingout will need id password again");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intents = new Intent(Main3Activity.this,MainActivity.class);
startActivity(intents);
Toast.makeText(getApplicationContext(),"Successfull Logout",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Logout Canceled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
return true;
default:return super.onOptionsItemSelected(item);
}
}
private void camera(){
Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intents,CAMERA_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST&&resultCode== Activity.RESULT_OK){
Bitmap photo= (Bitmap)data.getExtras().get("data");
imageView11.setImageBitmap(photo);
}
}
private void upload(){
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Confirm Upload ?");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("Are You Sure You Want to Upload Data");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"File Uploading...",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Recheck Data",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
#Override
public void onClick(View view) {
if(view==button1){
camera();
}
else if (view == button2){
upload();
}
}
#Override
public void onLocationChanged(Location location) {
double lati = location.getLatitude();
double longi = location.getLongitude();
locationText.setText("Latitude: " + lati + "\n Longitude: " + longi);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
AlertDialog.Builder alerDialogbuilder = new AlertDialog.Builder(Main3Activity.this);
alerDialogbuilder.setTitle("Enable Gps to Continue");
alerDialogbuilder.setIcon(R.drawable.ic_error_black_24dp);
alerDialogbuilder.setMessage("If You Want To Enable Gps Go To Settings");
alerDialogbuilder.setCancelable(false);
alerDialogbuilder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
Toast.makeText(getApplicationContext(),"Enable Gps..",Toast.LENGTH_SHORT).show();
}
});
alerDialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
Toast.makeText(getApplicationContext(),"Uploading Failed,Enable Gps",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = alerDialogbuilder.create();
alertDialog.show();
}
}
i want to check only if gps is enabled or not when my activity start if it is not enabled go to settings and still if the user doesnot enable the gps setting it should not work any further pls help me out m a new to android
Implement below method for checking status -:
public boolean CheckGpsStatus() {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return GpsStatus;
}
protected LocationRequest locationRequest;
public void checkForLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setInterval(MIN_UPDATE_INTERVAL);
locationRequest.setNumUpdates(1);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public void checkForLocationSettings() {
try {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.addLocationRequest(locationRequest);
SettingsClient settingsClient = LocationServices.getSettingsClient(MainActivity.this);
settingsClient.checkLocationSettings(builder.build())
.addOnSuccessListener((Activity) MainActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
// delay(1);
//Setting is success...
// Toast.makeText(SplashActivity.this, "Enabled the Location successfully. Now you can press the buttons..", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener((Activity) MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult((Activity) MainActivity.this, GET_PERMISSION_REQ_CODE);
} catch (Exception ex) {
new MyUtils().catchError(MainActivity.this, ex);
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(MainActivity.this, "Setting change is not available.Try in another device.", Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
new MyUtils().catchError(MainActivity.this, e);
}
}
This Above code shows the popup for enable the gps if gps is not enabled and also gives you callback for success and failure
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,OnMapReadyCallback,LocationListener{
protected static final String TAG = "MainActivity";
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
Marker mCurrLocationMarker;
GoogleMap mgooglemap;
private LocationManager locationManager;
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// MarkerOptions markerOptions = new MarkerOptions();
// markerOptions.position(latLng);
// markerOptions.title("Current Position");
// markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// mCurrLocationMarker = mgooglemap.addMarker(markerOptions);
//move map camera
mgooglemap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
mgooglemap.getMaxZoomLevel();
// locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Please Enable GPS", Toast.LENGTH_LONG).show();
//for you want to open Settings screen
while(!onProviderEnabled())
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
}
}
The onProviderDisabled() of the above code will provide you the required flow.
Here I want to show two dialog boxes...one for if there is net connection available and other if there is no connection..but i want that when one dialog box is shown, the other dialogue box should be dismissed .......dismiss() is not working in this case....and somehow if I use AlertDialog instead of AlertDialog.Builder to use dismiss(), then i am not able give setPositive, setNegative and setNeutral buttons....any help will be appreciated.......
BroadcastReceiver br;
#Override
protected void onCreate(Bundle savedInstanceState) {
...........//
getStarted();
}
private void getStarted() {
if (br == null) {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
...............//
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("No Internet ");
builder.setMessage("Offline");
builder.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder.show();
}
}
};
final IntentFilter if = new IntentFilter();
if.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(br, if);
}
}
}
Dismiss Your dialog if NetworkInfo.State.CONNECTED is connected,Please change builder1.show(); into builder1.dismiss();
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.dismiss();
}
Use broadcast receiver to react when the connection is changed with intent filter android.net.ConnectivityManager.CONNECTIVITY_ACTION. So, you can do your stuffs when the receiver receive the intent (or there connection is changed). See here.