I am just trying to implement Wifi P2P and I'm stuck on getting the peer list.
When I click on discover device Button then I just want to fetch all the devices append the list of devices to a string which I can output using a text view.
MainActivity.java
package com.example.lrmah.wifip2p;
public class MainActivity extends AppCompatActivity implements
WifiP2pManager.PeerListListener {
private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
Button B;
TextView t;
IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView) findViewById(R.id.displayTextView);
B=(Button) findViewById(R.id.discoverPeers);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
}
});
}
});
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
List<WifiP2pDevice> refreshedPeers = (List<WifiP2pDevice>) peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
}
WifiP2pDevice device= refreshedPeers.get(0);
t.setText(device.deviceName);
if (peers.size() == 0) {
return;
}
}}
WifiDirectBroadcastReceiver
package com.example.lrmah.wifip2p;
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
WifiP2pManager.PeerListListener myPeerListListener;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(mActivity,"wifi is on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mActivity,"Please turn on wifi",Toast.LENGTH_LONG).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mManager != null) {
mManager.requestPeers(mChannel, mActivity);
}
}
else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}}
I may be wrong but I think the onPeerAvailable is not being called.
Some points:
else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// here you should call
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected() && isSender) {
// connected with the other device, request connection info to find group owner IP
manager.requestConnectionInfo(channel, yourWifiP2pManager.ConnectionInfoListene);
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// call discoverPeers here
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
if (manager != null) {
manager.requestPeers(channel, yourWifiP2pManager.PeerListListener);
}
}
#Override
public void onFailure(int reasonCode) {}
});
then the device list will be broadcast in
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
WifiP2pDeviceList list = intent.getParcelableExtra(WifiP2pManager.EXTRA_P2P_DEVICE_LIST);
for (WifiP2pDevice d : list.getDeviceList()) { //...
Related
I have the following lines of code. I'm trying to access the Strings deviceName and deviceHarwareAddress. Do I need to construct a class that extends BroadcastReceiver and create a method within that which will return the code for me?
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
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
}
}
};
Not necessary. If you are limiting its use within a single component (say activity/fragment/service), you can keep "mReceiver" inside that component and then register mReceiver for that. That will work fine.
This is the case if you are doing it inside an activity.
public class BluetoothTest extends AppCompatActivity {
private ArrayList<BluetoothDevice> deviceList;
private BluetoothAdapter mBluetoothAdapter;
private ArrayList<DeviceItem> deviceItemList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
/**
* Do necessary coding to enable bluetooth
*/
registerReceiver();
startBluetoothDiscovery();
}
private void registerReceiver() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter dintentFilter = new IntentFilter();
dintentFilter.addAction(BluetoothDevice.ACTION_FOUND);
dintentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
dintentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mDiscoveryBroadcastReceiver, dintentFilter);
}
public void startBluetoothDiscovery() {
if (!mBluetoothAdapter.isDiscovering())
mBluetoothAdapter.startDiscovery();
}
public void setBluetoothDevice(BluetoothDevice device) {
if (!deviceList.contains(device))
deviceList.add(device);
}
public ArrayList<BluetoothDevice> getBluetoothDeviceList() {
return deviceList;
}
private void resetAll() {
deviceItemList.clear();
unregisterReceiver(mDiscoveryBroadcastReceiver);
}
private final BroadcastReceiver mDiscoveryBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(), "Started discovery!!!", Toast.LENGTH_SHORT).show();
deviceList = new ArrayList<>();
deviceItemList.clear();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(), "Finished discovery!!!", Toast.LENGTH_SHORT).show();
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
DeviceItem deviceItem = new DeviceItem(device.getName(),
device.getAddress(), device.getBluetoothClass(), device);
deviceItem.setBluetoothDevice(device);
/**
* To check if the device is in paired list or not
*/
if (mBluetoothAdapter.getBondedDevices().contains(device))
deviceItem.setPaired(true);
else
deviceItem.setPaired(false);
if (!deviceItemList.contains(deviceItem))
deviceItemList.add(deviceItem);
/**
* Once the device is found,it is added to a list
*/
setBluetoothDevice(device);
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings;
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
}
In case of "service" you can make use of the binder or observer pattern for make the data available to the activity.
I am trying to develop an application where the user can know the status of his/her Bluetooth Le device once he/she launches the app and the connection status is updated in text view in Home Fragment.I have tried to implement it by sending Broadcast from Ble service and catching it in onResume of Home fragment and subsequently updating it in status text view. The status does gets updated but if I change the fragment and come back to the home fragment the text view to show the status gets blank although the Bluetooth Le device is connected.How can I resolve this problem so that the status shows connected all through out if the device is connected and disconnected if it is disconnected?
Any Kind of guidance will be highly appreciated.
here are the code segments I have used to implement the above
In Bleservice.java
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
In HomeFragment.java
public class HomeFragment extends Fragment
{
private BroadcastReceiver mReceiver;
#Override
protected void onResume() {
super.onResume();
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Bleservice.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
} else if (Bleservice.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
}
}
};
getActivity().registerReceiver(mReceiver,makeGattUpdateIntentFilter());
}
private void updateConnectionState(final int resourceId) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tv_connected_disconnected.setText(resourceId);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(mReceiver);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Bleservice.ACTION_GATT_CONNECTED);
intentFilter.addAction(Bleservice.ACTION_GATT_DISCONNECTED);
return intentFilter;
}
Connect to your BleService by bindService. Check out example with Activity and Service.
private BleService mBluetoothLeService;
private boolean isConnected;
#Override
protected void onStart() {
super.onStart();
Intent bindIntent = new Intent(this, BleService.class);
startService(bindIntent);
bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
registerServiceReceiver(); //register here your mGattCallback that get actions from BleService
}
#Override
protected void onStop() {
super.onStop();
unbindService(mServiceConnection);
mBluetoothLeService = null;
LocalBroadcastManager.getInstance(this).unregisterReceiver(mGattUpdateReceiver);
}
In method bindService you need to pass a ServiceConnection that manage Service Lifecycle.
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BleService.LocalBinder) service).getService();
isConnected = (mBluetoothLeService.getConnectionState() != BleService.STATE_CONNECTED)
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
In Service you need to declare Binder.
private final IBinder mBinder = new LocalBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public BleService getService() {
return BleService.this;
}
}
public int getConnectionState() {
return mConnectionState;
}
So now, after binding to BleService, you can get a connection state.
I am working on a project in Android Studio where I am supposed to connect two devices using Wifi-Direct.
I have managed to connect to another device with Wifi-direct. My problem is that when I close the app manually on my phone, the devices do not disconnect. How can I achieve this? I am quite new with Android Studio and java.
Here is my WifiDirectActivity class:
public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
public static final String TAG = "wifidirectdemo";
private WifiP2pManager manager;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
private BroadcastReceiver receiver = null;
/**
* #param isWifiP2pEnabled the isWifiP2pEnabled to set
*/
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_peers);
// add necessary intent values to be matched.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
}
/** register the BroadcastReceiver with the intent values to be matched */
#Override
public void onResume() {
super.onResume();
receiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
if (!amConnected) {
performSearch();
}
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
/**
* Remove all peers and clear all fields. This is called on
* BroadcastReceiver receiving a state change event.
*/
public void resetData() {
DeviceListFragment fragmentList = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
DeviceDetailFragment fragmentDetails = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
if (fragmentList != null) {
fragmentList.clearPeers();
}
if (fragmentDetails != null) {
fragmentDetails.resetViews();
}
}
#Override
public void showDetails(WifiP2pDevice device) {
DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.showDetails(device);
}
#Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
#Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void disconnect() {
final DeviceDetailFragment fragment = (DeviceDetailFragment) getFragmentManager()
.findFragmentById(R.id.frag_detail);
fragment.resetViews();
manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onFailure(int reasonCode) {
Log.d(TAG, "Disconnect failed. Reason :" + reasonCode);
}
#Override
public void onSuccess() {
fragment.getView().setVisibility(View.GONE);
}
});
}
#Override
public void onChannelDisconnected() {
// we will try once more
if (manager != null && !retryChannel) {
Toast.makeText(this, "Channel lost. Trying again", Toast.LENGTH_LONG).show();
resetData();
retryChannel = true;
manager.initialize(this, getMainLooper(), this);
} else {
Toast.makeText(this,
"Severe! Channel is probably lost premanently. Try Disable/Re-Enable P2P.",
Toast.LENGTH_LONG).show();
}
}
#Override
public void cancelDisconnect() {
/*
* A cancel abort request by user. Disconnect i.e. removeGroup if
* already connected. Else, request WifiP2pManager to abort the ongoing
* request
*/
if (manager != null) {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
if (fragment.getDevice() == null
|| fragment.getDevice().status == WifiP2pDevice.CONNECTED) {
disconnect();
} else if (fragment.getDevice().status == WifiP2pDevice.AVAILABLE
|| fragment.getDevice().status == WifiP2pDevice.INVITED) {
manager.cancelConnect(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Aborting connection",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this,
"Connect abort request failed. Reason Code: " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
}
private void performSearch() {
final DeviceListFragment fragment = (DeviceListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(WiFiDirectActivity.this, "Discovery Initiated",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reasonCode) {
Toast.makeText(WiFiDirectActivity.this, "Discovery Failed : " + reasonCode,
Toast.LENGTH_SHORT).show();
}
});
}
}
When you close the app the execution will run through onPause() callback, there you should call the disconnect() method. However, take 5 minutes of your time to understand Android's life cycle principle: https://developer.android.com/guide/components/activities/activity-lifecycle.html. It's one of the first things to learn before developing an Android app.
Everything works fine but when WifiP2pManager calls onPeersAvailable method (it calls it correctly) the Peers Device List is empty, which makes no sense because if the method is called, it's because a peer was discovered. :S
Is something wrong in my code? Thanks.
Main Activity, Broadcast Receiver, and Discovery:
public class Main extends Activity{
FileManager flManager;
Context ctx;
LinearLayout lay_found_users;
LinearLayout lay_conversations;
AddLayoutItem addLayoutItem = new AddLayoutItem();
private final String TAG = "Main";
//Wifi Direct
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
WifiP2pManager.PeerListListener mPeerListListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
ctx = getApplicationContext();
flManager = new FileManager(ctx);
//Wifi Direct
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mPeerListListener = new WifiP2pManager.PeerListListener(){
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList){
Log.i(TAG, "Peers available");
int size = peerList.getDeviceList().size();
Log.i(TAG, String.valueOf(size));
}
};
mReceiver = new WDBroadcastReceiver(mManager, mChannel, this, mPeerListListener);
WDDiscovery wdDiscovery = new WDDiscovery(mManager, mChannel);
wdDiscovery.discover();
}
#Override
protected void onResume(){
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onDestroy(){
super.onDestroy();
unregisterReceiver(mReceiver);
}
public class WDBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private Main mActivity;
private final String TAG = this.getClass().getSimpleName();
private WifiP2pManager.PeerListListener mPeerListListener;
public WDBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, Main activity, WifiP2pManager.PeerListListener peerListListener){
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
this.mPeerListListener = peerListListener;
}
#Override
public void onReceive(Context context, Intent intent){
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Log.i(TAG, "Wifi P2P Enabled");
} else {
Log.i(TAG, "Wifi P2P Disabled");
}
}else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
if (mManager != null){
mManager.requestPeers(mChannel, mPeerListListener);
Log.i(TAG, "Peer Discovered");
}
}else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
// Respond to new connection or disconnections
}else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
// Respond to this device's wifi state changing
}
}
}
public class WDDiscovery {
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
private final String TAG = this.getClass().getSimpleName();
public WDDiscovery(WifiP2pManager manager, WifiP2pManager.Channel channel) {
mManager = manager;
mChannel = channel;
}
public void discover() {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.i(TAG, "WiFi P2P Discovery successful");
}
#Override
public void onFailure(int reasonCode) {
Log.i(TAG, "WiFi P2P Discovery error");
}
});
}
}
In my case, I add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
in manifest and give app the permission.
It works.
I was facing the same issue, the solution in my case was
add these two lines into Android Manifiest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
and make sure to ask for runtime permission of the location
I want to detect the switch of GPS.
My idea is to use IntentService and Broadcast intent.
My service is running but my broadcast receiver doesn't work.
I just wanna say to my HomeActivity if GPS is turn on/off by user. With this info, i will able to set up my GoogleMap with the current location.
Thx !
GpsService.java :
public class GpsService extends IntentService implements LocationListener {
private final static String TAG = "com.example.smartoo.gpsservice";
public GpsService () {
super(TAG);
Log.e("TAG", "GPS service k");
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
Intent i = new Intent("android.location.PROVIDERS_CHANGED");
i.putExtra("enabled", 1);
sendBroadcast(i);
}
}
#Override
public void onProviderDisabled(String provider) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
Intent i = new Intent("android.location.PROVIDERS_CHANGED");
i.putExtra("disnabled", 1);
sendBroadcast(i);
}
}
#Override
protected void onHandleIntent(Intent intent) {
}
}
HomeActivity.java
public class HomeActivity extends ActionBarActivity implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
//My attrs
private GoogleMap mMap = null;
Location currentLocation;
/*
* Initialize the Activity
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
//Get the map from xml file
mMap = getMap();
Intent i = new Intent(HomeActivity.this, GpsService.class);
startService(i);
}
/*
* Called when the Activity is restarted, even before it becomes visible.
*/
#Override
public void onStart() {
super.onStart();
final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//Check if GPS is enable on device.
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
showGPSDisabledAlertToUser();
}
}
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
int extra = intent.getIntExtra("enabled", -1);
//If GPS not enabled
if(extra == -1) {
extra = intent.getIntExtra("disabled", -1);
//If GPS not disabled
if (extra == -1) {
//Nothing
}
//If GPS disabled
else {
//Do something
}
}
//If GPS enabled
else {
Toast.makeText(HomeActivity.this, "GPS enabled", Toast.LENGTH_LONG).show();
currentLocation = getLocation();
setUpMapIfNeeded();
}
Toast.makeText(HomeActivity.this, "in onREceive", Toast.LENGTH_LONG).show();
}
}
}
}
For an example, first add the following permission to your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then, a simple Activity:
public class MainActivity extends Activity
{
private GpsStatusReceiver receiver = new GpsStatusReceiver();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected void onResume()
{
super.onResume();
registerReceiver(receiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
}
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}
private class GpsStatusReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
LocationManager lm = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
boolean isEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
onGpsStatusChanged(isEnabled);
}
}
private void onGpsStatusChanged(boolean isEnabled)
{
// Do/start your work here.
Toast.makeText(this, "GPS enabled - " + isEnabled, 0).show();
}
}