SERVICE_VERSION_UPDATE_REQUIRED - java

Actually I'm building an application which requires user's location. But I'm getting SERVICE_VERSION_UPDATE_REQUIRED error. Following are my MainActivity.java and AndroidManifest.xml files:
MainActivity.java
TextView lat, lon;
private static final String TAG = MainActivity.class.getSimpleName();
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat = (TextView) findViewById(R.id.lat);
lon = (TextView) findViewById(R.id.lon);
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
requestLocationUpdates();
}
private void requestLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG, connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText("Latitude: " + String.valueOf(latitude));
lon.setText("Longitude: " + String.valueOf(longitude));
}
#Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
}
#Override
protected void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
#Override
protected void onPause() {
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
#Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.harshil.location">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is what logcat says:
D/MainActivity: ConnectionResult{statusCode=SERVICE_VERSION_UPDATE_REQUIRED, resolution=null, message=null}
So, How to get through this problem?

I solved my problem by changing following line [in build.gradle] from:
compile 'com.google.android.gms:play-services:10.0.1'
to:
compile 'com.google.android.gms:play-services:9.8.0'
So, the problem is I am using higher version of Google Play Service for development than that installed on my device or emulator.
I came to my solution as follow:
1. I checked to update Google Play Service on my device but it says it is up-to-date.
2. I checked in App Manager to see the version of it, and I came to know that it is actually at 9.8.77. So I changed play-service version from 10.0.1 to 9.8.0.
Now, I am out of this problem.
Thank you.

Download the the google play store in your mobile and check it .for me i was not installed google play store in my mobile now i installed google play store ,its working fine.

Related

how to add permission in my sms manager

I'm very new to android studio and in my first app I want to build an sos app, my sos app specifically sends a message via sms with the current location. When I first built it, it only works on android 5.0 and down, it will not work in 6.0 and up and now I've tried to look at the logcat and the logcat says it needs a permission to send sms so I gave it a permission using the code below this paragraph and now it runs in android 6.0 but it's not sending messages... {if(checkselfpermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION GRANTED);}
can you help me here is my manifest my file
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/sos"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".DisplayContactActivity"
android:label="#string/title_activity_display_contact"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".EditContactActivity"
android:label="#string/title_activity_edit_contact"
android:parentActivityName=".DisplayContactActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".LogInActivity"
android:label="#string/title_activity_log_in"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
and here is my main activity.
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_SEND_SMS = 1;
ContactDbAdapter contactDbAdapter;
private GoogleApiClient client;
EditText messageText;
UserDbAdapter userDbAdapter;
Cursor cursor;
TextView locationText;
#Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
return super.checkUriPermission(uri, pid, uid, modeFlags);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
userDbAdapter = new UserDbAdapter(this);
messageText = (EditText) findViewById(R.id.messageText);
locationText = (TextView) findViewById(R.id.locationTextView);
try {
userDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open userDbAdapter\n");
}
contactDbAdapter = new ContactDbAdapter(this);
try {
contactDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open contactDbAdapter\n");
}
cursor = contactDbAdapter.getContacts();
final Button sos = (Button) findViewById(R.id.redbutton);
final Button finish = (Button) findViewById(R.id.greenbutton);
final CountDownTimer timer = new CountDownTimer(3999, 100) {
public void onTick(long millisUntilFinished) {
assert sos != null;
sos.setText("" + ((int) (millisUntilFinished) / 1000));
}
#TargetApi(Build.VERSION_CODES.M)
public void onFinish() {
sos.setVisibility(View.GONE);
finish.setVisibility(View.VISIBLE);
finish.setText("finish");
SmsManager smsManager = SmsManager.getDefault();
cursor = contactDbAdapter.getContacts();
String msg = messageText.getText().toString() + "#" + locationText.getText().toString();
Log.e("mytag", msg);
if(cursor.moveToFirst()){
do{
if (checkSelfPermission(Manifest.permission.SEND_SMS)==PackageManager.PERMISSION_GRANTED);
String number=cursor.getString(cursor.getColumnIndex(contactDbAdapter.PHONE_NUM));
smsManager.sendTextMessage(number, null, msg, null, null);
}while(cursor.moveToNext());
}
}
};
sos.setTag(1);
sos.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status != 1) {
sos.setText("sos");
sos.setTag(1);
timer.cancel();
} else {
sos.setTag(0);
timer.start();
}
}
}
);
finish.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
sos.setVisibility(View.VISIBLE);
finish.setVisibility(View.GONE);
sos.callOnClick();
}
}
);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.contact:
Intent contactIntent = new Intent(getApplicationContext(), LogInActivity.class);
startActivity(contactIntent);
return true;
case R.id.message:
Intent messageIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
startActivity(messageIntent);
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onResume() {
super.onResume();
// refresh user message
cursor = userDbAdapter.getUsers();
if (cursor.moveToFirst()) {
messageText.setText(cursor.getString(cursor.getColumnIndex(userDbAdapter.MESSAGE)));
}
// Acquire a reference to the system Location Manager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
}
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
locationText.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null) {
// messageText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
locationText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
}
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public void onDestroy() {
super.onDestroy();
if (cursor != null) {
cursor.close();
}
}
this is also the logcat that appeared before I gave the permission to run it on android 6.0
Process: com.cse4471.osu.sos_osu, PID: 23011
java.lang.SecurityException: Sending SMS message: uid 10179 does not have android.permission.SEND_SMS.
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:842)
at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:317)
at android.telephony.SmsManager.sendTextMessage(SmsManager.java:300)
at com.cse4471.osu.sos_osu.MainActivity$1.onFinish(MainActivity.java:119)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5628)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:853)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:737)
I hope you can help me with this.
You can try this :-
Add it in Manifest -
<uses-permission android:name="android.permission.SEND_SMS" />
And use this runtime permission in your activity
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},1);

Not able to get location with Service (LocationManager)

i am in real trouble here. Trying to get lat and lon with a background service every 3 sec but i am only able to get some data written when i click send lat and lon in extended controls of the emulator , so both phone and emulator are not working. Here is my code below, it would be awesome if someone could help me. Thanks!
Service
public class GPSService extends Service {
private static final String TAG = "GpsService";
private LocationListener locationListener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("latExtra",location.getLatitude());
i.putExtra("lonExtra",location.getLongitude());
sendBroadcast(i);
Log.i(TAG, "onLocationChanged: extras lat lon"+location.getLatitude()+" "+location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Log.i(TAG, "onProviderDisabled: DISABLED");
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager =(LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
String provider =locationManager.getBestProvider(c,true);
Log.i(TAG, "onCreate: bestProvider "+provider);
//noinspection MissingPermission
locationManager.requestLocationUpdates(provider,2000,0,locationListener);
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null){
Log.i(TAG, "onDestroy: Location manager nije null i brisem");
//noinspection MissingPermission
locationManager.removeUpdates(locationListener);
}
}
}
MainActivity
private final String TAG = "Main";
...
BroadcastReceiver broadcastReciever;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//setStatusBarTranslucent(false);
if(!runtimePermisions()){
startLocationUpdate();}
...
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//stopService();
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//REQUEST PERMISSION
Log.i(TAG, "onClick: NO PERMISION");
} else {
Log.i(TAG, "onClick: got permision");
}
...
}
public void startLocationUpdate(){
Intent i = new Intent(this,GPSService.class);
startService(i);
Log.i(TAG, "startLocationUpdate: Pokrenuo sam service");
}
#Override
protected void onResume() {
super.onResume();
if (broadcastReciever == null){
broadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
lat = (Double) intent.getExtras().get("latExtra");
lon = (Double) intent.getExtras().get("lonExtra");
Log.i(TAG, "onReceive: lat lon "+lat+" "+lon);
}
};
}
registerReceiver(broadcastReciever,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if (broadcastReciever!=null){
unregisterReceiver(broadcastReciever);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults [0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
startLocationUpdate();
}else{
runtimePermisions();}
}
}
private boolean runtimePermisions() {
if (Build.VERSION.SDK_INT >= 23 &&ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
},100);
return true;
}
return false;
}
MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digiart.yoweather">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SettingsActivity"
android:theme="#style/SettingsTheme"></activity>
<service android:name=".Gps.GPSService"/>
</application>
</manifest>
Again... Any help would be great! THANKS :D
As K. Sopheak said, it can take a while to get the location. From the documentation:
It may take a while to receive the first location update. If an immediate location is required, applications may use the getLastKnownLocation(String) method.
So, you could try getting the last known location using getLastKnownLocation(String) when the service is started and, assuming it exists, broadcast it in the same way you would a location update. Bear in mind, though, that the last known location could be out of date. Depending on what you're using the location for this may or may not be acceptable.
Also, as an aside, a couple of thoughts:
You said 3 seconds, but the code uses 2,000 milliseconds - was that just a typo?
The frequency of location updates is a minimum time - you are not guaranteed to get updates that often. As per the documentation:
The location update interval can be controlled using the minTime parameter. The elapsed time between location updates will never be less than minTime, although it can be more depending on the Location Provider implementation and the update interval requested by other applications.
Is there any particular reason you need location updates at such a high frequency? Obtaining a location can be battery intensive, particularly given that you are requesting FINE as well as COARSE location permissions, so requesting it so frequently could place an enormous drain on device battery life. This is particularly so given that the code is running in a service and will therefore continue to run even when the application is in the background or the user is in an activity which does not require location data. Again, from the documentation:
Choosing a sensible value for minTime is important to conserve battery life. Each location update requires power from GPS, WIFI, Cell and other radios. Select a minTime value as high as possible while still providing a reasonable user experience. If your application is not in the foreground and showing location to the user then your application should avoid using an active provider (such as NETWORK_PROVIDER or GPS_PROVIDER), but if you insist then select a minTime of 5 * 60 * 1000 (5 minutes) or greater. If your application is in the foreground and showing location to the user then it is appropriate to select a faster update interval.
Google recommends using the Google Play services location APIs instead of the Android framework location APIs:
The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.

Android WifiManager getScanResult complains Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission although declared permission

I am developing an App to check Wifi points.
I am getting error "java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results" at wifiManager.getScanResults() even though I already declared those permissions.
main activity
public class MainActivity extends AppCompatActivity {
WifiManager wifiManager;
String[] wifis;
WifiReceiver wifiReceiver;
ListView wifiListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wifiListView = (ListView) findViewById(R.id.wifi_list);
wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReceiver = new WifiReceiver();
wifiManager.startScan();
}
protected void onPause() {
unregisterReceiver(wifiReceiver);
super.onPause();
}
protected void onResume() {
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
private class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> wifiScanList = wifiManager.getScanResults();
wifis = new String[wifiScanList.size()];
for (int i = 0; i < wifiScanList.size(); i++) {
wifis[i] = wifiScanList.get(i).toString();
}
wifiListView.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, wifis));
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sample">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I am on SDK 6.0
I observed similar question, but solution does not apply since I already declared permission.
Anyone know what might be problem? Thank you.
In Android M, you need to ask for the permission which is defined as dangerous in PermissionModel to the user before start using each time, it as such:
private boolean mayRequestLocation() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
Snackbar.make(mView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
#Override
#TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
}
});
} else {
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
}
return false;
}
Add this to your Activity:
private static final int REQUEST_FINE_LOCATION=0
and load it during runtime with:
loadPermissions(Manifest.permission.ACCESS_FINE_LOCATION,REQUEST_FINE_LOCATION);
To evaluate the results of your permission request, you can override onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// The requested permission is granted.
}
else{
// The user disallowed the requested permission.
}
return;
}
}
MADAO is right: you should turn on GPS to get the WIFI access point list.
But I'm not sure about PEERS_MAC_ADDRESS. If you look at the source code (line 957):
/**
* Return the results of the most recent access point scan, in the form of
* a list of {#link ScanResult} objects.
* #return the list of results
*/
public List<ScanResult> getScanResults(String callingPackage) {
enforceAccessPermission();
int userId = UserHandle.getCallingUserId();
int uid = Binder.getCallingUid();
boolean canReadPeerMacAddresses = checkPeersMacAddress();
boolean isActiveNetworkScorer =
NetworkScorerAppManager.isCallerActiveScorer(mContext, uid);
boolean hasInteractUsersFull = checkInteractAcrossUsersFull();
long ident = Binder.clearCallingIdentity();
try {
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !isLocationEnabled()) {
return new ArrayList<ScanResult>();
}
if (!canReadPeerMacAddresses && !isActiveNetworkScorer
&& !checkCallerCanAccessScanResults(callingPackage, uid)) {
return new ArrayList<ScanResult>();
}
if (mAppOps.noteOp(AppOpsManager.OP_WIFI_SCAN, uid, callingPackage)
!= AppOpsManager.MODE_ALLOWED) {
return new ArrayList<ScanResult>();
}
if (!isCurrentProfile(userId) && !hasInteractUsersFull) {
return new ArrayList<ScanResult>();
}
return mWifiStateMachine.syncGetScanResultsList();
} finally {
Binder.restoreCallingIdentity(ident);
}
}
The first if is checking canReadPeerMacAddresses which the code for checkPeersMacAddress() is:
/**
* Returns true if the caller holds PEERS_MAC_ADDRESS.
*/
private boolean checkPeersMacAddress() {
return mContext.checkCallingOrSelfPermission(
android.Manifest.permission.PEERS_MAC_ADDRESS) == PackageManager.PERMISSION_GRANTED;
}
If you add the permission you can bypass if (!canReadPeerMacAddresses && !isActiveNetworkScorer && !isLocationEnabled()) {. I've tested but I cannot get WIFI MAC list by just using the permission and disabling location.
ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION is necessary. To get a valid result, you also have to turn on GPS or get a PEERS_MAC_ADDRESS permission like Setting.

Google Play Services - Activity Recognition Freezes After a Few Results

I have tried to simplify my code as much as possible, basically hte issue is that the ActivityRecognitionIntentService appears to be called a couple of times, then stalls out. It appears to be related to the requestCode in the PendingIntent, but I am not sure, can someone please advise me as to what is going wrong? Thanks.
Dashboard.java
public class Dashboard extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private BroadcastReceiver receiver;
private TextView tvActivity;
private GoogleApiClient mGoogleApiClient;
//String Locationp = "null";
//private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tvActivity = (TextView) findViewById(R.id.tvActivity);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
//.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle arg0) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 2000, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.e("MAIN", "Connected to ActRec");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 1000, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
Log.e("MAIN", "Connection suspended to ActRec");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("MAIN", "Not Connected to ActRec");
}
ActivityRecognitionIntentService.java
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbAct = result.getMostProbableActivity();
int confidence = mostProbAct.getConfidence();
String mostProbActName = getActivityName(mostProbAct.getType());
Intent i = new Intent("com.xxx.abc.ACTIVITY_RECOGNITION_DATA");
i.putExtra("act", mostProbActName);
i.putExtra("confidence", confidence);
Log.e("ARS", mostProbActName + "," + confidence);
//sendBroadcast(i);
} else
Log.e("ARS", "Intent had no ActivityRecognitionData");
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tigerblood.com.node" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<service android:enabled="true" android:name="com.xxx.abc.ActivityRecognitionIntentService"></service>
<activity
android:name="com.tigerblood.node.Dashboard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Android location issue

Hi i am trying to get the device location using the Location api in android using the device network or wifi connection. However it doesnt seem to get the latt or longitude.
i have created a location provider and manager, and registered a location listener.
i then
launched
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
and from that point on, the app doesnt retrieve new location changes at all. what am i missing?
here is my userLocation Code
public class UserLocation implements LocationListener{
public static final int UPDATE_LATT = 0;
private static final int TIME_INTERVAL = 1000;
private static final int DISTANCE = 10;
private LocationManager locationManagaer;
private LocationProvider locationProvide;
private Handler mHandler;
public UserLocation(Context context, Handler handler){
locationManagaer = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationProvide = locationManagaer.getProvider(LocationManager.NETWORK_PROVIDER);
mHandler = handler;
}
public void startSearchLocation(){
Log.d("", "sart location search");
locationManagaer.requestLocationUpdates(locationProvide.getName(),TIME_INTERVAL, DISTANCE, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d("", "location update on " + location.getLongitude());
Message.obtain(mHandler,UPDATE_LATT, new Position(location.getLongitude(), location.getLatitude()));
}
#Override
public void onProviderDisabled(String provider) {
Log.d("", "onProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("", "onStatusChanged");
}
}
here is my activity that uses this class to setup and listen for new locations
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
position = (Position) msg.obj;
Toast.makeText(
getApplicationContext(),
position.getLattitude() + " " + position.getLongetude(),
Toast.LENGTH_LONG).show();
}
};
userLocation = new UserLocation(this, mHandler);
initializeViews();
userLocation.startSearchLocation();
}
Here is my position POJO
public class Position {
private double longetude;
private double lattitude;
public Position(){
}
public Position(double longetude, double lattitude){
}
public double getLongetude() {
return longetude;
}
public void setLongetude(double longetude) {
this.longetude = longetude;
}
public double getLattitude() {
return lattitude;
}
public void setLattitude(double lattitude) {
this.lattitude = lattitude;
}
}
Here is part of my manifest file
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.jr.haliotest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Logcat:
03-23 20:19:14.309: D/(16992): sart location search
03-23 20:19:14.384: E/(16992): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found!
03-23 20:19:14.384: I/(16992): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.449: I/(16992): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl
03-23 20:19:14.514: I/(16992): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl
Testing on a htc one x thats rooted if that helps. wifi is on and god signal
If you are within a building then it is probably that your device is not able to connect to a GPS Provider. I would suggest if you move to a more open space so that you can get a signal.
One hint that if the device is connected to receive a gps signal. The sign of the gps will stop blinking and will become solid.
I would start by checking if your phones location services are enabled and maybe try rebooting. Also try using "GPS" instead of "network" to see if the problem is related to your network not providing location info.
From my experience wifi networks will sometimes simply not provide location info. I'm not sure if that's also true for cell networks, but I suspect there is no guarantee.

Categories

Resources