Service not stopping - android

I am creating an application which run a service where a function is called repeatedly in 5 seconds. I am able to start the service by clicking a button but cant stop when another button is clicked!
My code is:
public class LocationService extends Service implements LocationListener {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String TAG = "MyServiceTag";
Timer t;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
startJob();
}
},
0, // run first occurrence immediatetly
5000); // run every 60 seconds
return START_STICKY;
}
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
t.cancel();
t.cancel();
return super.stopService(name);
}
Starting and stopping is done in another activity.
public void popupstart() {
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location Sharing");
alertDialog.setMessage("Enable location sharing will broadcast your location to clients applications. This is a battery draining process and kindly turn off " +
"location sharing after use");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("shareLocation", "yes");
editor.commit();
liveStatus = "1";
mFab = (FloatingActionButton)findViewById(R.id.fab);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mFab.setImageDrawable(ContextCompat.getDrawable(gnavigationActivity.this, R.drawable.locationon));
}
else{
mFab.setImageDrawable(getResources().getDrawable(R.drawable.locationon));
}
if(!isMyServiceRunning(LocationService.class)) {
Toast.makeText(gnavigationActivity.this, "Location Sharing started", Toast.LENGTH_LONG).show();
processStartService(LocationService.TAG);
}
else{
Toast.makeText(gnavigationActivity.this, "Location Sharing already started", Toast.LENGTH_LONG).show();
}
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void popupstop() {
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(this);
alertDialog.setTitle("Stop Location Sharing");
alertDialog.setMessage("You are about to stop location sharing which now will not broadcast location to client users. Are you sure?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
processStopService(LocationService.TAG);
Toast.makeText(gnavigationActivity.this, "Location Sharing Stoped", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("shareLocation", "no");
editor.commit();
liveStatus = "0";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mFab.setImageDrawable(ContextCompat.getDrawable(gnavigationActivity.this, R.drawable.locationoff));
}
else{
mFab.setImageDrawable(getResources().getDrawable(R.drawable.locationoff));
}
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void processStartService(final String tag) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.addCategory(tag);
startService(intent);
}
private void processStopService(final String tag) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.addCategory(tag);
stopService(intent);
}

on calling stopService(intent);
the override method onDestroy will start
try to do this
#Override
public void onDestroy(){
super.onDestroy();
t.cancel();
t.cancel();
}

Related

Android Studio Bluetooth BroadcastReceiver problem

I'm trying to scan for Bluetooth devices around. In the log, I see that the bluetoothAdapter as started discovery, but it doesn't send back anything on the receiver, I don't even get an ACTION_DISCOVERY_STARTED.
Here is what I have made :
MainActivity.java :
public class MainActivity extends AppCompatActivity {
private Button button_addUser;
private Button button_viewUsers;
private Button button_test;
private Button button_bluetooth;
private int REQUEST_ENABLE_BLT_CONNECT = 100;
private int REQUEST_ENABLE_BLT_SCAN = 101;
private int REQUEST_ENABLE_BLT_ACCESS_COARSE_LOCATION = 102;
private int REQUEST_ENABLE_BT = 10;
private int REQUEST_ENABLE_LOCATION = 11;
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ArrayList<BluetoothObject> listBlt = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.button_addUser = (Button) this.findViewById(R.id.button_addUser);
this.button_viewUsers = (Button) this.findViewById(R.id.button_viewUsers);
this.button_test = (Button) this.findViewById(R.id.button_test);
this.button_bluetooth = (Button) this.findViewById(R.id.button_bluetooth);
button_addUser.setEnabled(true);
dialogUpBltOnStart();
button_addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent addUserIntent = new Intent(MainActivity.this, Activity_addUser.class);
MainActivity.this.startActivity(addUserIntent);
}
});
button_viewUsers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent viewUsersIntent = new Intent(MainActivity.this, Activity_viewUsers.class);
MainActivity.this.startActivity(viewUsersIntent);
}
});
button_test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogUpBltOnStart();
}
});
button_bluetooth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestPermissionsBltScan();
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
private void enableBLT(){
//BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
dialogNoBlt();
}
if (!mBluetoothAdapter.isEnabled()) {
if (ContextCompat.checkSelfPermission(
MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) ==
PackageManager.PERMISSION_GRANTED) {
Intent enableBltIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBltIntent, REQUEST_ENABLE_BLT_CONNECT);
} else {
requestPermissionsBltConnect();
}
}
}
private void requestPermissionsBltConnect() {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BLUETOOTH_CONNECT)){
new AlertDialog.Builder(this)
.setTitle(R.string.dialogTitle1)
.setMessage(R.string.dialogMessage3)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_ENABLE_BLT_CONNECT);
}
})
.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
dialogCancelBlt();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_ENABLE_BLT_CONNECT);
}
}
private void requestPermissionsBltScan() {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BLUETOOTH_SCAN)){
new AlertDialog.Builder(this)
.setTitle(R.string.dialogTitle1)
.setMessage(R.string.dialogMessage6)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.BLUETOOTH_SCAN}, REQUEST_ENABLE_BLT_SCAN);
}
})
.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
dialogCancelBlt();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.BLUETOOTH_SCAN}, REQUEST_ENABLE_BLT_SCAN);
}
}
private void requestPermissionsBltCoarseLocation() {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)){
new AlertDialog.Builder(this)
.setTitle(R.string.dialogTitle1)
.setMessage(R.string.dialogMessage6)
.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_ENABLE_BLT_ACCESS_COARSE_LOCATION);
}
})
.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
dialogCancelBlt();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_ENABLE_BLT_ACCESS_COARSE_LOCATION);
}
}
public void bluetoothScanning(){
//listBlt = getArrayOfAlreadyPairedBluetoothDevices();
//Log.d("oui", String.valueOf(listBlt.size()));
scanForDevice();
}
public ArrayList getArrayOfAlreadyPairedBluetoothDevices(){
ArrayList<BluetoothObject> arrayOfAlreadyPairedBluetoothDevices = null;
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0){
arrayOfAlreadyPairedBluetoothDevices = new ArrayList<BluetoothObject>();
for(BluetoothDevice device : pairedDevices){
BluetoothObject bluetoothObject = new BluetoothObject(device.getName(), device.getAddress());
arrayOfAlreadyPairedBluetoothDevices.add(bluetoothObject);
}
}
return arrayOfAlreadyPairedBluetoothDevices;
}
public void scanForDevice(){
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d("oui", "stop");
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("oui", "action");
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceAddress = device.getAddress();
Log.d("oui", deviceName);
} else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d("oui", "end");
} else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.d("oui", "started");
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ENABLE_BLT_CONNECT) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, R.string.toast1, Toast.LENGTH_SHORT).show();
enableBLT();
} else {
Toast.makeText(this, R.string.toast2, Toast.LENGTH_SHORT).show();
dialogCancelBlt();
}
} else if(requestCode == REQUEST_ENABLE_BLT_SCAN) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Toast.makeText(this, R.string.toast1, Toast.LENGTH_SHORT).show();
requestPermissionsBltCoarseLocation();
} else {
Toast.makeText(this, R.string.toast2, Toast.LENGTH_SHORT).show();
dialogCancelBlt();
}
} else if(requestCode == REQUEST_ENABLE_BLT_ACCESS_COARSE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Toast.makeText(this, R.string.toast1, Toast.LENGTH_SHORT).show();
bluetoothScanning();
} else {
Toast.makeText(this, R.string.toast2, Toast.LENGTH_SHORT).show();
dialogCancelBlt();
}
}
}
private void dialogUpBltOnStart(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
if(!mBluetoothAdapter.isEnabled()){
builder.setTitle(R.string.dialogTitle2);
builder.setMessage(R.string.dialogMessage4);
builder.setPositiveButton(R.string.button_upBluetooth, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
enableBLT();
}
});
builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
dialogCancelBlt();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
} // Ask to activate the bluetooth when the main activity launches
private void dialogNoBlt(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.dialogMessage2);
builder.setPositiveButton(R.string.button_closeApp, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
System.exit(0);
}
});
builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} //Explain why the user should use the bluetooth
private void dialogCancelBlt(){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.dialogTitle3);
builder.setMessage(R.string.dialogMessage5);
builder.setPositiveButton(R.string.button_understand, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
AndroidManifest.xml :
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
In the logs, I have only a :
I/BluetoothAdapter: startDiscovery
I can't manage to find what I've done wrong. When I launch the app on my phone, all authorizations are asked, bluetooth is enabled, but it just doesn't send back anything.
If you can help me, thank you !
I figured out. The gps was off, so even if I had the authorizations, it cannot find any devices.

How to check if the user has enabled or disabled gps service during runtime in android?

I have an app where I need to get user's location. So at the start of the app, i have checked if the GPS is turned on or not. If yes, the user will easily log in to the app. If not, the alert dialog will be shown where user will be asked to turn it on. If the user denies, the app will close, if the user accepts to turn on gps, the user will be navigated to location settings. However, i am unable to track if the user has turned the gps on or not after the user reaches location settings. How do i do that ? This is my alert box code:
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog dialog = new AlertDialog.Builder(login.this).setTitle("GPS NOT ENABLED!")
.setMessage("Plese, turn on your gps to login to the app")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
dialog.dismiss();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK &&
event.getAction() == KeyEvent.ACTION_UP &&
!event.isCanceled()) {
dialog.dismiss();
finish();
return true;
}
return false;
}
})
.show();
dialog.setCanceledOnTouchOutside(false);
}
One way I have implemented in below fashion.
1.Create an interface:
public interface GpsInterface {
void onGpsStatusChanged(boolean gpsStatus);
}
2.Create a BroadcastReceiver:
public class GpsListener extends BroadcastReceiver {
private GpsInterface gpsInterface = null;
private Context context;
public GpsListener(){}
public GpsListener(Context ctx, GpsInterface gpsInterface){
this.gpsInterface = gpsInterface;
this.context = ctx;
}
#Override
public void onReceive(Context context, Intent intent) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
gpsInterface.onGpsStatusChanged(true);
}else{
gpsInterface.onGpsStatusChanged(false);
}
}
}
3.Implement the GpsInterface in your class/activity
public class MyActivity extends Activity implements GpsInterface{
private GpsListener gpsListener;
private boolean isGpsOn;
//other stuff
}
//in onCreate()
IntentFilter mfilter = new IntentFilter(
"android.location.PROVIDERS_CHANGED");
gpsListener = new GpsListener(getActivity(), this);
registerReceiver(gpsListener, mfilter);
Implement the onGpsStatusChanged() method in the activity
#Override
public void onGpsStatusChanged(boolean gpsStatus) {
Logger.e("GPS STATUS", "ON " + gpsStatus);
isGpsOn = gpsStatus;
}
4.Unregister your broadcast receiver in onDestroy()
#Override
public void onDestroy() {
unregisterReceiver(gpsListener);
}
Hope this will help.
Use the below code to check whether gps provider and network providers are enabled or not.
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
Here is a clean way to check GPS status during runtime.
Create a Broadcast Receiver
private BroadcastReceiver mGPSConnectivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// GPS ON
} else {
// GPS OFF
}
}
};
Register the Broadcast Receiver in onStart()
#Override
protected void onStart() {
super.onStart();
registerReceiver(mGPSConnectivityReceiver,
new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
Don't forget to unregister the Receiver in onStop()!
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(mGPSConnectivityReceiver);
}
This is probably the easiest and cleanest solution for this problem. I really hope that it helps!

How to update the android app when the Location toggle is enabled in Settings?

My app is promtping the user to switch on the Location service by navigating to Location-Settings activity.
Now how to check in the activity code when the user toggles the Location option in the settings activity.
public void checkGPS() {
LocationManager lm = (LocationManager) GlobalHome.this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(GlobalHome.this);
dialog.setMessage(MessagesString.LOCATION_DIALOG_MESSAGE);
dialog.setPositiveButton(MessagesString.LOCATION_DIALOG_POSTIVE_TEXT, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
GlobalHome.this.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
I think you are looking for this , Hoping - it will solve your problem
public class MainActivity extends Activity implements LocationListener {
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
isLocationServiceActive();
}
private void isLocationServiceActive(){
locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
if(locationManager!=null){
LocationProvider gpsLocationProvider=locationManager.getProvider(LocationManager.GPS_PROVIDER);
LocationProvider networkLocationProvider=locationManager.getProvider(LocationManager.NETWORK_PROVIDER);
if(gpsLocationProvider==null && networkLocationProvider==null){
//device does'nt support location services
showDeviceNotSupportLocationsDialog();
}
else if(networkLocationProvider!=null && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 100.0F, this);
}
else if(gpsLocationProvider!=null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 100.0F, this);
}
else{
showNoGpsDialog();
}
}
}
public void showNoGpsDialog()
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setMessage(this.getResources().getString(R.string.gps_network_not_enabled));
localBuilder.setPositiveButton(this.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
Intent localIntent = new Intent("android.settings.LOCATION_SOURCE_SETTINGS");
MainActivity.this.startActivity(localIntent);
}
});
localBuilder.setCancelable(false);
localBuilder.show();
}
public void showDeviceNotSupportLocationsDialog()
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setMessage(this.getResources().getString(R.string.device_not_support_locations));
localBuilder.setPositiveButton(this.getResources().getString(R.string.exit), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
MainActivity.this.finish();
}
});
localBuilder.setCancelable(false);
localBuilder.show();
}
#Override
public void onLocationChanged(Location location) {
//location changed
}
#Override
public void onProviderDisabled(String s) {
//your code here
}
#Override
public void onProviderEnabled(String s) {
//your code here
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
//your code here
}
}

How to make AlertDialog to display anywhere in android app?

I wanna create android app which after 30 second will display to me AlertDialog
I did it but i wanna make AlertDialog will display any where in android for example in home of android.
like this http://www.papktop.com/wp-content/uploads/2012/01/Popup-Notifier-1.jpg
it is my code (main Activity )
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EventBus.getDefault().register(this);
mTextField = (TextView) findViewById(R.id.mTextField);
}
public void show(View view) {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("Nek Test");
// alertDialog.setIcon(getResources().getDrawable(R.mipmap.notification_image));
alertDialog.setTitle("Reminder");
alertDialog.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
alertDialog.show();
}
}.start();
}
}
For show a dialog outside the app, for example over the Home you need to put this permission in the manifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Create a service like this:
public class AlertService extends Service {
private static Context context;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Nek Test");
alertDialog.setTitle("Reminder");
/**ADD THIS FOR DISPLAY THE ALERT ANYWHERE*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setPositiveButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
alertDialog.show();
}
}.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}//End class
And finally start the service from activity:
startService(new Intent(this, AlertService.class));
and add this line into the "application" tag in the manifest:
<service android:name=".AlertService" />
There are many ways to do this :
1- Implement a service that will start in the main activity and in the service execute a timer, and whenever the timer finishes it will call a broadcast receiver and this receiver will trigger the showing of the alert dialogue.
2- You could use otto : http://square.github.io/otto/
In otto you have to register every activity to otto and unregister onDestroy off course. The timer has to be in an asynctask and on the post execute you post a certain result. Then you subscribe the onAsyncTaskResult in each activity and trigger the alert dialogue there.
3- You also use otto but this time do not subscrib to onAsyncTaskResult and instead of posting in the onPostExecute send a broadcast. Have a broadcast listener ready and on receive show the alert dialogue
This code works best for me without any errors
public class AlertService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final AlertDialog alertDialog = new AlertDialog.Builder(AlertService.this).create();
alertDialog.setMessage("Nek Test");
alertDialog.setTitle("Reminder");
alertDialog.setButton("Got it", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
/**ADD THIS FOR DISPLAY THE ALERT ANYWHERE*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

Android - How to make some validations in sequence

I need to do some validations sequentially and some of them involve complex database operations.
So, I need to do this in a separated thread of UI Thread, ok?
But some validations show messages to user, what need confirmation and
when user confirm, the next validation should be call.
This code example explains what I want to implement:
void makeValidation1(){
if(condition1Valid()){
makeValidation2();
}else{
DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
makeValidation2();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("really want to do this?")
.setPositiveButton("Yes", onClick);
builder.create().show();
}
}
void makeValidation2(){
if(condition2Valid()){
}else{
//...
}
}
boolean condition1Valid() {
// complex database Operations
return false;
}
boolean condition2Valid() {
//complex database Operations
return false;
}
//...
void makeValidation9(){
//...
}
My question is: What the best way/pattern to implement this?
1 - Create one asyncTask for each validation? (I cant create only one AsyncTask, because confirmation messages can stop flux).
2 - Create a Runnable for each validation and create thread to run that when need call next validation?
3 - ???
edit
I tested this code #BinaryBazooka, but isnt work. Any help?
public class MainActivity extends Activity implements OnClickListener {
Thread mThread;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
validations();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
mThread.run();
}
});
builder.create().show();
}
void validations(){
//this method go on separated thread
validation1();
validation2();
validation3();
}
void validation1(){
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
//wait for user confirmation
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
mThread.notify();
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
mThread.interrupt();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (mThread) {
mThread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
Log.i("TAG", "<<<<<<<<<< >>>>>>>>>>>>");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT);
}
});
}
}
I would create a new thread and sleep it during these dialog calls, you can access the UI directly from within your runnable with..
runOnUiThread(new Runnable() {
public void run() {}
});
So something like..
Thread someThread = new Thread(new Runnable() {
#Override
public void run(){
runOnUiThread(new Runnable() {
public void run()
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.msg);
builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
someThread.notify();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
someThread.wait();
Works with AsyncTask. Ty.
Code:
public class MainActivity extends Activity implements OnClickListener {
//Thread mThread;
ProgressDialog mProgressDialog;
private ValidationsAsyncTask async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Start");
setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Start Thread?");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.show();
async = new ValidationsAsyncTask();
async.execute();
}
});
builder.create().show();
}
void validation1(){
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Validation 1 failed. Go validation 2?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
//if user confirm, continue validation thread
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//if user cancel, stop validation thread
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
Log.i("TAG - validation1", Thread.currentThread().getName());
try {
synchronized (async) {
//wait for user confirmation
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation2() {
if(true){
runOnUiThread(new Runnable() {
#Override
public void run() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("validacao 2 failed. Go validation 3?");
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mProgressDialog.show();
synchronized (async) {
async.notify();
}
}
});
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
async.cancel(true);
}
});
mProgressDialog.hide();
builder.create().show();
}
});
try {
synchronized (async) {
async.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void validation3() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT).show();
}
});
}
class ValidationsAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
validation1();
validation2();
validation3();
return null;
}
#Override
protected void onCancelled() {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_LONG).show();
}
}
}

Categories

Resources