I try to prevent automatic connection to WiFi and displaying dialog box after turning on WiFi adapter from notification bar.
I register programmatically BroadcastReceiver that receives WIFI_STATE_CHANGED_ACTION. In WIFI_STATE_ENABLED I remove network from the configured network list. But it does not work.
I register BroadcastReceiver in:
#Override
protected void onStart() {
super.onStart();
registerReceiver(wifiStatusReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
}
And unregister in onStop method.
BroadcastReceiver code:
public class WiFiStatusReceiver extends BroadcastReceiver {
private WifiManager wifiManager;
#Override
public void onReceive(Context context, Intent intent) {
wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if(!isInitialStickyBroadcast()) { //it is not a sticky intent
switch(wifiManager.getWifiState()) {
case WifiManager.WIFI_STATE_ENABLING:
Toast.makeText(context, R.string.enabling_wifi, Toast.LENGTH_SHORT).show();
break;
case WifiManager.WIFI_STATE_ENABLED:
Toast.makeText(context, R.string.enabled_wifi, Toast.LENGTH_SHORT).show();
wifiManager.disconnect();
if(!wifiManager.getConfiguredNetworks().isEmpty()) { //there are some networks
for(WifiConfiguration wifiConfig :wifiManager.getConfiguredNetworks()) {
wifiManager.removeNetwork(wifiConfig.networkId);
}
}
break;
case WifiManager.WIFI_STATE_DISABLING:
Toast.makeText(context, R.string.disabling_wifi, Toast.LENGTH_SHORT).show();
break;
case WifiManager.WIFI_STATE_DISABLED:
Toast.makeText(context, R.string.disabled_wifi, Toast.LENGTH_SHORT).show();
break;
}
} else { //is a sticky intent
wifiManager.disconnect();
if(!wifiManager.getConfiguredNetworks().isEmpty()) { //there are some networks
for(WifiConfiguration wifiConfig :wifiManager.getConfiguredNetworks()) {
wifiManager.removeNetwork(wifiConfig.networkId);
}
}
}
}
}
Any suggestions ?
Try this to Disable the Wifi............. and when needed enable it.........
boolean isOn = false;
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(isOn);
Related
I am able to list unpaired devices on scan discovery only if other devices are on their 'bluetooth setting screen'.If other devices are on their homepage then my application cannot find those devices.
I have android 7 on my mobile phone and other devices have android 9 on them.
Any help is appreciated.Thanks:)
public void startDiscovery()
{
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
BA.startDiscovery();
registerReceiver(mReceiver, filter);
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("main","action found"+action);
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(), "Discovery finished", Toast.LENGTH_SHORT).show();
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Log.d("main","devicename"+deviceName);
Log.d("main","deviceHardwareAddress"+deviceHardwareAddress);
}
};
#Override
protected void onDestroy() {
Log.d("main","destroyed");
super.onDestroy();
BA.cancelDiscovery();
// Don't forget to unregister the ACTION_FOUND receiver.
unregisterReceiver(mReceiver);
}
Its not being discovered because its hidden according to the bt protocol however see https://stackoverflow.com/a/36984988/8461344
My code is working perfectly, i used a Brodcast Receiver.
In my application when the user click a button, a phone call is started, and the second activity (outcall.java) popup the screen, in the outcall Activity i have a VideoView, what I want to do is that the Video starts when the call is answered, and the activity is killed when the call is ended.
I have another problem with my code, i want the second activity to launch only when I use the button inside the application, because now it launches always even if i call a friend.
help will be appreciated
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
Button play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter(""));
play = (Button)findViewById(R.id.button2);
final MediaPlayer mP=MediaPlayer.create(MainActivity.this,R.raw.reco);
play.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (mP.isPlaying()){
mP.pause();
play.setBackgroundResource(R.drawable.play);
}else {
mP.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
ActivityCompat.requestPermissions(this, new String[]{CALL_PHONE}, PackageManager.PERMISSION_GRANTED);
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
OpenCallOut();
}
};
public void OpenCallOut(){
Intent intent = new Intent(this, Outcall.class);
startActivity(intent);
}
public void CallButton(View view) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "123456"));
startActivity(intent);
}
#Override
public void onDestroy() {
finish();
System.exit(0);
}
}
Here is my Broadcast, i found this in codetoart but don't know how to use it
public class Broadcast extends BroadcastReceiver {
private static final String TAG = "PhoneStateBroadcastReceiver";
Context mContext;
String incoming_nr;
private int prev_state;
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent(""));
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr= bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
mContext=context;
}
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
#Override
public void onCallStateChanged(int state, String incomingNumber){
if(incomingNumber!=null&&incomingNumber.length()>0) incoming_nr=incomingNumber;
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "CALL_STATE_RINGING");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "CALL_STATE_OFFHOOK");
prev_state=state;
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.d(TAG, "CALL_STATE_IDLE==>"+incoming_nr);
if((prev_state==TelephonyManager.CALL_STATE_OFFHOOK)){
prev_state=state;
}
if((prev_state==TelephonyManager.CALL_STATE_RINGING)){
prev_state=state;
}
break;
}
}
}
}
Here is my second activity Outcall.Java
public class Outcall1 extends AppCompatActivity {
VideoView myVideo;
private MediaController media_control;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_outcall1);
myVideo = (VideoView) findViewById(R.id.videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myvideo);
media_control = new MediaController(this);
myVideo.setMediaController(media_control);
myVideo.setVideoURI(uri);
myVideo.start();
}
}
There are basically multiple ways for sending broadcasts in android.
In simple terms, some are due to system events such as the all the outgoing calls, while some are private to a particular application i.e the local broadcasts within the app.
1.In your case, the second activity is launching always because your onRecieve() is responding to system events. Hence you should try to sending local broadcast on the button click using the LocalBroadcastManager.sendBroadcast.
Alternatively , you can also use Service for starting your second activity .In this case , before starting call intent start your service .Inside the servie you can set a small delay and then start the second activity.
And for finishing your second activity on call end , you can use the above broadcast reciever that you posted but know for detecting call end, and then in case when the state of phone is call disconnected. Fire another broadcast to be recieved by the second activity which finishes the activity on recieving it.
This will help you with the implementation of the step 2.
I am aware of the BroadCastReceiver, but how can I use it to call a method in my activity. So if I get a notification from my service, a button in my UI turns red, and red being the object that has been sent from the service and turning red the method that has been called by the activity.
sorry for bad english :)
Register a BroadcastReceiver in your activity
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
if (message.equals("eventOne"))
{
//do something
}
else if (message.equals("eventTwo"))
{
//do something else
}
}
};
Override onResume and onDestroy of your activity
#Override
protected void onResume()
{
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
#Override
protected void onDestroy()
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
To check if your service is running add the following on your activity
private static boolean isServiceRunning(String serviceName, Context context)
{
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if (serviceName.equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
Call it like this
boolean isServiceRunning = isServiceRunning(MyService.class.getName(), this.getApplicationContext());
if (!isServiceRunning)
{
Intent startMyServiceIntent = new Intent(this.getApplicationContext(), MyService.class);
startService(startMyServiceIntent);
}
Finally on your service add a method like that and call it whenever you want
private void sendMessage(String event)
{
Intent intent = new Intent("my-event");
intent.putExtra("message", event);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
sendMessage("eventOne");
return START_STICKY;
}
And don't forget to add your service to manifest
<application
...
...
<service android:name=".MyService"/>
</application>
You can use a BroadcastReceiver, an event bus or an observable. In your activity, listen for the event and call a method that updates your UI how you want.
I do something similarly for GCM intent service. I use an rxBus that posts when the service is triggered. My activity subscribes to the bus and reacts when it sees the post.
when the phone is connected to the bluetooth in the car. I want my app to switch on automatically. to do this i have to save the paired car bluetooth device name to a string. then when the phones bluetooth is connected to something. I have to check if its the car. If it is i want to start a service.
I'm having difficulty passing the string that contains the bluetooth car device name to the receiver, as my receiver is already receiving a intent filter to listen out for ACTION_ACL_CONNECTED. is it possible to send a intent & an intent filter to the same receiver.
How can I can send the btdeviceName string from the activity to the receiver in this case.
Main Activity
private void addDrawerItems() {
final BroadcastReceiver bluetoothBroadcast = new BluetoothReceiver();
final IntentFilter blueToothFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
final Intent btbroadcastIntent = new Intent(this, BluetoothReceiver.class);
btbroadcastIntent.putExtra("btDeviceName", mPairedBluetoothDevice);
String[] osArray = {"Bluetooth Auto Start", "Reply to Calls", "Reply to sms", "Customise Message"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, osArray);
if (mIsPremiumUser) {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
} else {
mDrawerList.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Toast.makeText(getApplicationContext(), "blue", Toast.LENGTH_LONG).show();
showBluetoothDialog();
}
return true;
}
});
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView ctv = (CheckedTextView) view;
if (!mIsPremiumUser) {
Toast.makeText(getApplication(), "Upgrade", Toast.LENGTH_LONG).show();
return;
}
switch (position) {
case 0:
if (ctv.isChecked()) {
if (!isblueToothRegistered) {
registerReceiver(bluetoothBroadcast, blueToothFilter);
sendBroadcast(btbroadcastIntent);
isblueToothRegistered = true;
}
} else {
if (isblueToothRegistered) {
unregisterReceiver(bluetoothBroadcast);
isblueToothRegistered = false;
}
}
break;
BluetoothReceiver
public class BluetoothReceiver extends BroadcastReceiver {
private MainActivity ma;
private String pairedDevice;
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Receieved", Toast.LENGTH_LONG).show();
String action = intent.getAction();
pairedDevice = intent.getStringExtra("btDeviceName");
Toast.makeText(context, pairedDevice + "2", Toast.LENGTH_LONG).show();
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
Toast.makeText(context, "Bluetooth Connected", Toast.LENGTH_LONG).show();
if (device.getName().equals(pairedDevice)) {
Toast.makeText(context, device.getName() + " 1", Toast.LENGTH_LONG).show();
}
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Toast.makeText(context, "Bluetooth Disconnected", Toast.LENGTH_LONG).show();
}
}
}
An IntentFilter can have multiple actions. So start by creating your own custom action name to listen for and add it to the blueToothFilter.
blueToothFilter.addAction("my.custom.action");
Once you register the bluetoothBroadcast receiver with this IntentFilter it will now receive calls for both actions. Add another condition in onReceive to handle your new custom action.
Finally in your Activity send a broadcast with your custom action and the device name when ready.
Intent intent = new Intent()
.setAction("my.custom.action")
.putExtra("btDeviceName", mPairedBluetoothDevice);
sendBroadcast(intent);
UPDATE
I now understand that you want both the BluetoothDevice device and String pairedDevice in a single call to onReceive(). That is not possible since those variables are taken from separate actions and each action calls onReceive() once.
To fix this you can change the BluetoothReceiver to be an inner class of your Activityso you can keep a reference to the data you need there.
I have a broadcastreceiver created in my Service class.
It is set to react to this action: WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
So basically everytime I do a method call of wifi.startScan(); , and the results become available, the broadcastreceiver's onReceive method does its thing.
My issue is that I need to process those scan results and its likely not good practice to do so much in the broadcastreceiver. I want to do all the calculations back in my service class but I need to somehow access the ScanResults.
Any sort of help with this? As it is much needed.
Here is a simplified version of my code conveying the purpose of my broadcastreceiver:
Snippet from my Service class:
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); //reacts to the scan results being available
registerReceiver(mybroadcast,i);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(!wifi.isWifiEnabled()){ // if wifi is not enabled
toast = Toast.makeText(getApplicationContext(), "Wifi is off. Please turn it on.", Toast.LENGTH_LONG);
toast.show();
//wifi.setWifiEnabled(true);
//startActivity(backIntent);
}
else
{
wifi.startScan(); //what the receiver is going to react to
}
Code for my receiver:
private final BroadcastReceiver mybroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//gets the scan results
wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scans = wifi.getScanResults();
// do some work here...
}
}
You can try adding an handler to service for ex:
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Server Response: " + aResponse, Toast.LENGTH_SHORT)
.show();
} else {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Not Got Response From Server.", Toast.LENGTH_SHORT)
.show();
}
}
};
And send a message to it in OnReceive of your BroadcastReceiver:
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);