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.
Related
Here in below code I am discovering all available BLE devices and trying to pair and unpair device on request. But I am not getting callback in registered broadcast receiver.
public class DeviceConfigurationActivity extends AppCompatActivity {
Context context;
Toolbar toolbar;
RecyclerView recyclerView;
DeviceListAdapter mAdapter;
ArrayList<BluetoothDevice> mList;
RelativeLayout rlBack;
//BLUETOOTH
BluetoothAdapter bluetoothAdapter;
Set<BluetoothDevice> pairedDevices;
String deviceName, deviceHardwareAddress;
ProgressBar progressBar;
private Intent bluetoothSerialServiceIntent;
boolean mBound = false;
private BluetoothSerialService btService;
String selectedWorkType = "";
private int btDevicePosition;
private BTDeviceEntity connectedDevice;
private BluetoothDevice alreadyConnectedBTDevice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_configuration);
init();
}
public void init(){
context = this;
toolbar = findViewById(R.id.toolbar);
recyclerView = findViewById(R.id.recycler_view);
rlBack = findViewById(R.id.rl_back);
progressBar = findViewById(R.id.progress_bar);
mList = new ArrayList<>();
//Method calling
setListeners();
setUpRecyclerView();
setUpBluetooth();
}
private void setListeners() {
rlBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
/**
* BLUETOOTH SETUP
*/
private void setUpBluetooth() {
progressBar.setVisibility(View.VISIBLE);
//GET BLUETOOTH DEFAULT ADAPTER AND START DISCOVERY
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
if (bluetoothAdapter == null){
Toast.makeText(context, "Device doesn't support Bluetooth", Toast.LENGTH_SHORT).show();
}
//CHECK IF BLUETOOTH IS ENABLED
checkIfEnabled();
//REGISTER FOR A BROADCASTS WHEN A DEVICE IS DISCOVERED
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
//REGISTER FOR A BROADCASTS FOR A DEVICE STATE CHANGED
IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);
}
private void setUpRecyclerView() {
mAdapter = new DeviceListAdapter(context, mList, new DeviceListAdapter.DeviceListAdapterInterface() {
#Override
public void onConnect(BluetoothDevice device, int position) {
onConnection(device, position);
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(mAdapter);
}
//CHECK IF ENABLED
private void checkIfEnabled() {
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
//Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
}else {
//Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
private void onConnection(BluetoothDevice device, int position) {
//connectedDevice = device;
btDevicePosition = position;
if (device.getBondState() != Constants.STATE_DISCONNECTED) {
new AlertDialog.Builder(context)
.setTitle("Connect to device")
.setMessage("Are you sure you want to connect to " + device.getName() + " ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pairDevice(device);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
} else {
new AlertDialog.Builder(context)
.setTitle("Disconnect from device")
.setMessage("Are you sure you want to disconnect from " + device.getName() + " ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
unpairDevice(device);
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
private void pairDevice(BluetoothDevice device){
Method method;
try {
method = device.getClass().getMethod("createBond", (Class[])null);
method.invoke(device, (Object[]) null);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
mList.remove(btDevicePosition);
mList.add(device);
//mAdapter.updateAdapter(mList);
//mAdapter.updateDeviceState(btDevicePosition, device.getBondState());
}
private void unpairDevice(BluetoothDevice device){
Method method;
try {
method = device.getClass().getMethod("removeBond", (Class[])null);
method.invoke(device, (Object[])null);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
mList.remove(btDevicePosition);
mList.add(device);
//mAdapter.updateAdapter(mList);
//mAdapter.updateDeviceState(btDevicePosition, device.getBondState());
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mList.add(device);
//Set adapter
Log.i("BT", device.getName() + "\n" + device.getAddress());
progressBar.setVisibility(View.GONE);
mAdapter.updateAdapter(mList);
}
}
};
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast.makeText(context, "Paired", Toast.LENGTH_SHORT).show();
// mAdapter.updateAdapter(mList);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED) {
Toast.makeText(context, "Unpaired", Toast.LENGTH_SHORT).show();
// mAdapter.updateAdapter(mList);
}
}
}
};
/**
* HANDLER METHODS
*/
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
unregisterReceiver(mPairReceiver);
}
}
Below is my adapter class for recycler view. Here also facing issue to update connected or disconnected update status.
public class DeviceListAdapter extends RecyclerView.Adapter<DeviceListAdapter.MyViewHolder> {
Context context;
ArrayList<BluetoothDevice> mList;
DeviceListAdapterInterface mListener;
public interface DeviceListAdapterInterface{
void onConnect(BluetoothDevice device, int position);
}
public void updateAdapter(ArrayList<BluetoothDevice> mList){
this.mList = mList;
notifyDataSetChanged();
}
public DeviceListAdapter(Context context, ArrayList<BluetoothDevice> mList,DeviceListAdapterInterface mListener) {
this.context = context;
this.mList = mList;
this.mListener = mListener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int position) {
View view = LayoutInflater.from(context).inflate(R.layout.row_bt_device2, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, #SuppressLint("RecyclerView") int position) {
BluetoothDevice model = mList.get(position);
myViewHolder.txtDeviceName.setText(model.getName());
if (model.getBondState() != Constants.STATE_DISCONNECTED){
myViewHolder.txtConnectionStatus.setText("Connect");
}else {
myViewHolder.txtConnectionStatus.setText("Disconnect");
}
myViewHolder.txtConnectionStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.onConnect(model, position);
}
});
}
#Override
public int getItemCount() {
return mList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtDeviceName, txtConnectionStatus;
ImageView imgIcon;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txtDeviceName = itemView.findViewById(R.id.txt_device_name);
txtConnectionStatus = itemView.findViewById(R.id.txt_connection_status);
imgIcon = itemView.findViewById(R.id.img_icon);
}
}
}
Please suggest for solution. Any help will be appreciated. Thanks in advance.
Before startDiscovery() registerReciever.
public BroadcastReceiver connectionCallbacks = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case BluetoothCommands.STATE_CONNECTING:
break;
case BluetoothCommands.STATE_CONNECTED:
break;
case BluetoothCommands.STATE_DISCONNECTED:
break;
case BluetoothDevice.ACTION_FOUND:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//From here you can add devices to your list.
break;
case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
if (intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR) == BluetoothDevice.BOND_BONDED) {
}
break;
}
}
};
In pairDevice method call
device.createBond();
Register with these actions.
public IntentFilter getConnectionIntentFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothCommands.STATE_CONNECTING);
intentFilter.addAction(BluetoothCommands.STATE_CONNECTED);
intentFilter.addAction(BluetoothCommands.STATE_DISCONNECTED);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
return intentFilter;
}
My app needs internet to work so i'm trying to check the internet connection work or not i want when internet is turn off app show the user dialog with TRY AGAIN button when user click TRY AGAIN Button and interent connection still doesn't work Show Dialog (internet doesn't work try again )
check internet connection method :
public Boolean CheckInternetConnection(){
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()) {
return true;
}
else
return false;
}
inside onCreate
protected void onCreate(){
......
......
if(CheckInternetConnection()){
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.mipmap.info)
.setTitle("Internet Connection !")
.setMessage("No Internet Connection")
.setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(CheckInternetConnection()){
//TRY AGAIN and REOPEN DIALOG
}
}
});
builder.setCancelable(false);
AlertDialog about = builder.create();
about.show();
TextView messageText = (TextView) about.findViewById(android.R.id.message);
assert messageText != null;
messageText.setGravity(Gravity.CENTER);
Button nbutton = about.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(Color.BLACK);
}
Create showDialog() separate method and call it whenever you need to show the dialog again.
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
if (isNetworkConnected()) {
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
} else {
showDialog();
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("No Internet Connection");
builder.setNegativeButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (isNetworkConnected()) {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
} else {
showDialog();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
if you get the connection fail and then show dialog like "your connection fail" try this code below .
mainactivity
public class MyActivity implements NetworkStateReceiverListener {
private NetworkStateReceiver networkStateReceiver;
}
oncreate
public void onCreate(Bundle savedInstanceState) {
/* ... */
networkStateReceiver = new NetworkStateReceiver();
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
mainactivity
#Override
public void networkAvailable() {
// internet connection success
}
#Override
public void networkUnavailable() {
//REOPEN DIALOG
}
the receiver
public class NetworkStateReceiver extends BroadcastReceiver {
protected List<NetworkStateReceiverListener> listeners;
protected Boolean connected;
public NetworkStateReceiver() {
listeners = new ArrayList<NetworkStateReceiverListener>();
connected = null;
}
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
private void notifyStateToAll() {
for(NetworkStateReceiverListener listener : listeners)
notifyState(listener);
}
private void notifyState(NetworkStateReceiverListener listener) {
if(connected == null || listener == null)
return;
if(connected == true)
listener.networkAvailable();
else
listener.networkUnavailable();
}
public void addListener(NetworkStateReceiverListener l) {
listeners.add(l);
notifyState(l);
}
public void removeListener(NetworkStateReceiverListener l) {
listeners.remove(l);
}
public interface NetworkStateReceiverListener {
public void networkAvailable();
public void networkUnavailable();
}
}
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();
}
For example: my app calls a native settings activity, by
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, CODE);
Then when it is finished (by pressing the back button for example) I want to know. I tried this way, but the onActivityResult() wasn't called when the native activity was finalized... so my app wasn't informed...
How I have to do? Anyone knows?
Thanks...
EDIT:
Thanks every one.
The complete code is that:
public class MainActivity extends AppCompatActivity {
public static final int DIALOG_CODE = 0x1;
private TextView txtGps;
private TextView txtNet;
private LocationManager manager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first();
}
private void checkConfigs() {
boolean gps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean net = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
setWidgets(gps, net);
if (gps && net){
Toast.makeText(this, "Configurações Ok!", Toast.LENGTH_SHORT).show();
} else {
DialogConfig.exibDialog(getFragmentManager());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == DIALOG_CODE) && (resultCode == RESULT_OK)){
checkConfigs();
} else {
Toast.makeText(this, "As config não foram alteradas!", Toast.LENGTH_SHORT).show();
}
}
public void setWidgets(boolean gsp, boolean net){
if (gsp){
txtGps.setText(R.string.gps_hab);
} else {
txtGps.setText(R.string.gps_n_hab);
}
if (net){
txtNet.setText(R.string.wifi_hab);
} else {
txtNet.setText(R.string.wifi_n_hab);
}
}
private View.OnClickListener onClickCheck() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
checkConfigs();
}
};
}
#SuppressWarnings("ConstantConditions")
private void first() {
txtGps = (TextView) findViewById(R.id.txt_gps);
txtNet = (TextView) findViewById(R.id.txt_net);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
findViewById(R.id.btn_check).setOnClickListener(onClickCheck());
}
public static class DialogConfig extends DialogFragment {
public static void exibDialog(FragmentManager fm){
new DialogConfig().show(fm, "dialog");
}
#Override
public android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("As conf não estão corretas! Alt configs?")
.setPositiveButton("Ok", onOk())
.setNegativeButton("Cancel", onCancel())
.create();
}
private DialogInterface.OnClickListener onCancel() {
return new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
};
}
private DialogInterface.OnClickListener onOk() {
return new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, DIALOG_CODE);
}
};
}
}
}
[Resolved]
Thanks again to every one, I tried again, creating a interface of callback in dialog, so the activity could be informed and call the other native settings activity by itself , and got the response in onActivityResult(), but comparing only a code (not by RESULT_OK), This way worked. But there is a other way (like was suggested) that use the lifecycle, to me seems more easy.
I basically tried what you tried and it works for me.
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);
and for onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(PREFIX, "onActivityResult");
}
When I came back to the app, onActivityResult was called.
Not sure what you are doing different. can you show your onActivityResult code?
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
}
}