I'm a newbie to Android development, so apologies in advance if this is a stupid question.
I'm running a simple app that tracks the user's location and store it in a real-time db.
the app works perfectly fine on the emulator, but not for the real devices.
it gets slow with a message showing that "V/FA: Inactivity, disconnecting from service", and when it starts running, nothing is written to the database.
here's my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alice.locationfinder3">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>
</manifest>
and my build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.alice.locationfinder3"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.google.firebase:firebase-messaging:12.0.1'
implementation 'com.google.firebase:firebase-database:12.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.android.gms:play-services:12.0.1'
}
apply plugin: 'com.google.gms.google-services'
Finally, my main activity:
package com.example.alice.locationfinder3;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.location.Criteria;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.location.Criteria.ACCURACY_FINE;
public class MainActivity extends AppCompatActivity {
private LocationManager locationManager;
private LocationListener locationListener;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = database.getReference();
double latitude; // latitude
double longitude; // longitude
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(ACCURACY_FINE);
String bestProvider = locationManager.getBestProvider(criteria, true);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("Location: ", location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
long time = location.getTime();
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = sdf.format(date);
writeNewPoint(timestamp, longitude, latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if(Build.VERSION.SDK_INT < 23)
{
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);
}
else {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
else {
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Criteria criteria;
criteria = new Criteria();
criteria.setAccuracy(ACCURACY_FINE);
String bestProvider = locationManager.getBestProvider(criteria, true);
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);
}
}
}
private void writeNewPoint(String timestamp, double longitude, double latitude) {
Point point = new Point(longitude, latitude);
mDatabase.child("points").child(timestamp).setValue(point);
}
}
Snapshot from logcat:
09-02 16:05:11.150 28873-28906/com.example.alice.locationfinder3 V/FA: Inactivity, disconnecting from the service
09-02 16:05:11.170 28873-28958/com.example.alice.locationfinder3 I/FirebaseCrash: Sending crashes
09-02 16:05:31.195 28873-28873/com.example.alice.locationfinder3 D/Location:: Location[gps XX.7591,XX.6441 hAcc=64 et=+16h53m5s212ms alt=604.5306458863317 vel=0.14499298 bear=124.898796 vAcc=??? sAcc=??? bAcc=??? {Bundle[mParcelledData.dataSize=40]}]
0
Again, this works fine with the emulator, runs and stores to the db.
But it fails with real devices.
Thanks.
Try following these steps.The reasoning is explained in this post: V/FA: Inactivity, disconnecting from the service
Steps:
1)Uninstall the app from your mobile/emulator.
2)Then go to the File option in the main menubar in the android studio.
3)Then click on Invalidatecasha/restart.
Related
I have an issue with my Android App. I am asking for permissions to the user to access the READ_EXTERNAL_STORAGE but the bug "permission denial" still makes my app crash.
I have spent hours on it and I have no clue how to fix it.
Here's my logcat:
03-07 15:02:12.387 6800-8893/? E/DatabaseUtils: Writing exception to parcel
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=8108, uid=10089 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
at android.content.ContentProvider$Transport.query(ContentProvider.java:211)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
at android.os.Binder.execTransact(Binder.java:453)
03-07 15:02:12.391 8108-11729/? E/iu.UploadsManager: Insufficient permissions to process media
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=8108, uid=10089 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.os.Parcel.readException(Parcel.java:1602)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:421)
at android.content.ContentResolver.query(ContentResolver.java:502)
at android.content.ContentResolver.query(ContentResolver.java:438)
at lqt.a(PG:14)
at com.google.android.libraries.social.autobackup.FingerprintScannerIntentService.onHandleIntent(PG:15)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.os.HandlerThread.run(HandlerThread.java:61)
My Main activity is:
package com.example.arjufy;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
public class MainActivity extends AppCompatActivity implements MarketPlaceFragment.OnListFragmentInteractionListener {
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabaseReference;
private String mUsername;
private String mPhotoUrl;
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser == null) {
// Not signed in, launch the Sign In activity
startActivity(new Intent(this, SplashScreenActivity.class));
finish();
return;
} else {
mUsername = mFirebaseUser.getEmail();
}
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
setContentView(R.layout.activity_main);
Fragment fragment = new MarketPlaceFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.theFragmentFrame, fragment).addToBackStack("MarketPlaceFragment").commit();
}
}
public boolean checkPermissionREAD_EXTERNAL_STORAGE(
final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
(Activity) context,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
showDialog("External storage", context,
Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
ActivityCompat
.requestPermissions(
(Activity) context,
new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void showDialog(final String msg, final Context context,
final String permission) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage(msg + " permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context,
new String[] { permission },
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// do your stuff
} else {
Toast.makeText(MainActivity.this, "GET_ACCOUNTS Denied",
Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.logoff:
FirebaseAuth.getInstance().signOut();
Intent intent1 = new Intent(this, LoginActivity.class);
startActivity(intent1);
return true;
case R.id.profile:
Intent intent2 = new Intent(this, MyProfileActivity.class);
startActivity(intent2);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListFragmentInteraction(DatabaseReference reference) {
Intent intent = new Intent(this, ProductDetailViewActivity.class);
intent.putExtra("Product reference", reference.toString());
startActivity(intent);
}
}
My manifest is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.arjufy">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
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>``
<activity android:name=".LoginActivity" />
<activity android:name=".SplashScr
eenActivity" />
<activity android:name=".AddProductActivity" />
<activity android:name=".SignUpActivity" />
<activity android:name=".MyProfileActivity" />
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.arjufy"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/path_files" />
</provider>
<activity android:name=".ProductDetailViewActivity" />
</application>
</manifest>
and my gradle is:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.arjufy"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:16.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-storage:16.1.0'
implementation 'com.google.firebase:firebase-database:16.1.0'
implementation 'com.firebaseui:firebase-ui:0.5.3'
implementation 'me.relex:circleindicator:2.1.0#aar'
implementation 'com.getbase:floatingactionbutton:1.10.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.google.firebase:firebase-core:16.0.7'
}
Do you have any idea where it might come from?
Thanks a lot for your help.
Very much appreciated.
From Android Developer Documentation
If your app needs a dangerous permission, you must check whether you have that permission every time you perform an operation that requires that permission. Beginning with Android 6.0 (API level 23), users can revoke permissions from any app at any time, even if the app targets a lower API level.
So you need to request permission like this
#TargetApi(23)
public void enableRunTimePermisstion() {
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) &&
(getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED))
if (getActivity().shouldShowRequestPermissionRationale
(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "Write storage permission is need for app"
, Toast.LENGTH_LONG).show();
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
Toast.makeText(getActivity(), "request permission"
, Toast.LENGTH_LONG).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Write external storage granted", Toast.LENGTH_LONG).show();
// >> here you call the method that need the permission
}
} else {
Toast.makeText(getActivity(), "Write external permission denied", Toast.LENGTH_SHORT).show();
enableRunTimePermisstion(); // >> When user request the permission we calling the previous method again.
}
}
Runtime permission has actually taken a new shape in the recent times ... like you need to use a fileprovider, provide Uri and the likes but here is a good library that i have used in the recent times. It works well and hassle free. You can check it out on codepath.
https://guides.codepath.com/android/Managing-Runtime-Permissions-with-PermissionsDispatcher
Cheers.
I was looking for the solution to my problem the whole day now, but I couldn't find out. I'm absolutely new to java/android studio/app programming and probably it's just a very small thing that I don't see.
I just want my App to show the current location of the device. Nothing more.
When running the App on the emulator, no error is shown and the App starts.
Then I open the extended controls and push the "SEND"-button in "Location".
Now I would expect my App to show the current location, but nothing happens. The TextViews "textLat", "textLong" and "textAlt" are staying empty.
I have absolutely no Idea what my fault is. I wrote that code with the help of different tutorials. I also tried it on my real device.
I would be very grateful for any help! Thanks alot!
package com.example.findlocation_test2;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView textLat;
TextView textLong;
TextView textAlt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLat = (TextView) findViewById(R.id.textLat);
textLong = (TextView) findViewById(R.id.textLong);
textAlt = (TextView) findViewById(R.id.textAlt);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(location != null) {
double dLat = location.getLatitude();
double dLong = location.getLongitude();
double dAlt = location.getAltitude();
textLat.setText(Double.toString(dLat));
textLong.setText(Double.toString(dLong));
textAlt.setText(Double.toString(dAlt));
}
else {
textLat.setText("Fehler");
textLong.setText("Fehler");
textAlt.setText("Fehler");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(), "GPS wurde akiviert",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Toast.makeText(getBaseContext(), "GPS wurde deaktiviert",
Toast.LENGTH_SHORT).show();
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, ll);
}
}
And in the manifest I added the permissions:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.findlocation_test2">
<uses-permission android:name="android.permission.ACCESS_INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> /**Erlaubnis, um auf die GPS Daten zuzugreifen*/
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
hello, thanks a lot for the time you re according to my issue.
I am trying to run an app in android studio and it builds fine with 0 errors, the app icon is showing on the device(i tried on different devices and emulators btw) but when it launches, it crashes after a few seconds, saying "my app" has stopped. I tried to view the logcat errors and i didnt understand the problem.
here is the logcat error file, and tell me if you need any other information about the problem please.
03-28 19:20:23.382 13915-13921/? E/jdwp: Failed sending reply to debugger: Broken pipe
03-28 19:20:23.532 13915-13929/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.internal.zzadf.zzg
03-28 19:20:23.762 13915-13915/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
03-28 19:20:23.782 13915-13915/? E/OneSignal: OneSignal AppId format is invalid.
Example: 'b2f7f966-d8cc-11e4-bed1-df8f05be55ba'
java.lang.NumberFormatException: Invalid long: "xxxxxxxx"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.util.UUID.fromString(UUID.java:201)
at com.onesignal.OSUtils.initializationChecker(OSUtils.java:52)
at com.onesignal.OneSignal.init(OneSignal.java:238)
at com.onesignal.OneSignal.init(OneSignal.java:215)
at com.onesignal.OneSignal.access$000(OneSignal.java:68)
at com.onesignal.OneSignal$Builder.init(OneSignal.java:142)
at com.mp3player.searchonline.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
03-28 19:20:27.816 13915-13915/com.usmans.songscloud E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: android.support.v7.internal.widget.TintManager
at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1041)
at android.support.design.widget.TabLayout.createTabView(TabLayout.java:582)
at android.support.design.widget.TabLayout.addTabView(TabLayout.java:616)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:334)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:309)
at android.support.design.widget.TabLayout.setTabsFromPagerAdapter(TabLayout.java:571)
at android.support.design.widget.TabLayout.setupWithViewPager(TabLayout.java:550)
at com.mp3player.searchonline.MainActivity.setView(MainActivity.java:93)
at com.mp3player.searchonline.MainActivity.onCreate(MainActivity.java:86)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mp3player.searchonline" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/MyMaterialTheme"
android:name="com.mp3player.searchonline.App" >
<!--This meta-data tag is required to use Google Play Services.-->
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
<activity
android:name="com.mp3player.searchonline.MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustNothing" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mp3player.searchonline.PlayerActivity"
android:label="#string/app_name"
android:theme="#style/MyDialogTheme" >
</activity>
</application>
</manifest>
MainActivity.java
package com.mp3player.searchonline;
/**
* Created by Usman Jamil on 02/02/2017.
* Usmans.net
* Skype usman.jamil78
* email usmanjamil547#gmail.com
*/
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.Snackbar;
import com.onesignal.OneSignal;
import java.util.ArrayList;
import java.util.List;
import android.support.design.widget.CoordinatorLayout;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements constants {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private CoordinatorLayout coordinatorLayout;
private SearchView mSearchView;
private MenuItem searchMenuItem;
String[] Final_Suggestions=null;
private SimpleCursorAdapter mAdapter;
String SearchText=null;
SongFragment fragment;
ProgressDialog pDialog;
String TabFragmentB;
Boolean Is = false;
FloatingActionButton Sharebutton;
String urs;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
int id = viewPager.getCurrentItem();
OneSignal.startInit(this).init();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
Sharebutton = (FloatingActionButton) findViewById(R.id.fav);
Sharebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onshare();
}
});
final String[] from = new String[] {"cityName"};
final int[] to = new int[] {android.R.id.text1};
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
null,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
Snackbar snackbar = Snackbar .make(coordinatorLayout, getString(R.string.WelcomeMsg), Snackbar.LENGTH_LONG);
SongFragment toy1 = (SongFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + viewPager.getId() + ":" + 0);
setView();
snackbar.show();
}
public void setView(){
Sharebutton.setVisibility(View.VISIBLE);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SongFragment(), "Search");
adapter.addFragment(new DownloadFragment(), "Downloaded");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public Fragment getActiveFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(tag);
}
#Override
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
if ((paramInt == 4) && (paramKeyEvent.getRepeatCount() == 0)) {
onexit();
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public void onexit() {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Rate Us");
localBuilder
.setMessage(getString(R.string.rating)).setNeutralButton("Rate",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
MainActivity.this.ratee(MainActivity.this
.getApplicationContext()
.getPackageName());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
paramAnonymousDialogInterface.dismiss();
MainActivity.this.finish();
}
});
localBuilder.show();
}
public void onshare() {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Share");
localBuilder
.setMessage(getString(R.string.share)).setNeutralButton("Share",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
MainActivity.this.share(getString(R.string.ShareMsg)+MainActivity.this
.getApplicationContext()
.getPackageName());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
public void ratee(String paramString) {
try {
Intent localIntent = new Intent("android.intent.action.VIEW");
localIntent
.setData(Uri.parse("market://details?id=" + paramString));
startActivity(localIntent);
return;
} catch (Exception localException) {
}
}
public void share(String paramString) {
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,paramString);
sendIntent.setType("text/plain");
startActivity(sendIntent);
return;
} catch (Exception localException) {
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "com.usmans.songscloud"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
manifestPlaceholders = [onesignal_app_id: "xxxxxxxx-e269-4dfb-8b48-357b707acdae",
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: "108880509xxxx"]
useLibrary 'org.apache.http.legacy'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
maven {
url 'https://dl.bintray.com/ayz4sci/maven/'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:22.2.0'
compile 'com.cjj.materialrefeshlayout:library:1.3.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.ayz4sci.androidfactory:downloadprogress:1.0.1'
compile 'com.android.support:support-v4:25.0.0'
// Required for OneSignal, even if you have added FCM.
compile 'com.google.android.gms:play-services-gcm:+'
// Required for geotagging
compile 'com.google.android.gms:play-services-location:+'
compile 'com.google.android.gms:play-services-analytics:+'
// play-services-analytics is only needed when using 8.1.0 or older.
// compile 'com.google.android.gms:play-services-analytics:+'
compile 'com.google.android.gms:play-services-ads:10.2.1'
compile 'com.onesignal:OneSignal:3.4.3'
}
Seems like the "app id" you're passing to the OneSignal framework should be of type Long but you're passing an invalid value.
See this error discussion: OneSignal AppId format is invalid
I am following the Spotify tutorial on android sdk beta22-noconnect-2.20b to just get the groundwork on an app that I want to to write and I am having trouble getting my application to authenticate. I am sure that I have signed my app and inserted the correct fingerprint into the "My Applications" tab on spotify. My URI is correct. I am also fairly certain that I followed the tutorial 100% properly. Every time I run the program I get this error.
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/com.spotify.sdk.android.authentication.LoginActivity: https://accounts.spotify.com/authorize?client_id=7c59d84c8b7f4e35b3c85a7a5289db1b&response_type=token&redirect_uri=spotifymixer%3A%2F%2Fcallback&show_dialog=true&scope=user-read-private%20streaming
D/SpotifyAuthHandler: start
D/com.spotify.sdk.android.authentication.LoginActivity: Error authenticating
D/SpotifyAuthHandler: stop
I don't know how to proceed. Could I have used an incorrect signature for the program?
My MainActivity.java:
package com.example.mammo.spotifyplayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import com.spotify.sdk.android.authentication.AuthenticationClient;
import com.spotify.sdk.android.authentication.AuthenticationRequest;
import com.spotify.sdk.android.authentication.AuthenticationResponse;
import com.spotify.sdk.android.player.Config;
import com.spotify.sdk.android.player.ConnectionStateCallback;
import com.spotify.sdk.android.player.Error;
import com.spotify.sdk.android.player.Player;
import com.spotify.sdk.android.player.PlayerEvent;
import com.spotify.sdk.android.player.Spotify;
import com.spotify.sdk.android.player.SpotifyPlayer;
public class MainActivity extends Activity implements
SpotifyPlayer.NotificationCallback, ConnectionStateCallback
{
// TODO: Replace with your client ID
private static final String CLIENT_ID = "7c59d84c8b7f4e35b3c85a7a5289db1b";
// TODO: Replace with your redirect URI
private static final String REDIRECT_URI = "spotifymixer://callback";
private Player mPlayer;
private static final int REQUEST_CODE = 1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);
builder.setScopes(new String[]{"user-read-private", "streaming"});
AuthenticationRequest request = builder.build();
AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);
}
public void tryAgain(View view){
AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(CLIENT_ID, AuthenticationResponse.Type.TOKEN, REDIRECT_URI);
builder.setScopes(new String[]{"user-read-private", "streaming"});
AuthenticationRequest request = builder.build();
AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == REQUEST_CODE){
AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
if(response.getType() == AuthenticationResponse.Type.TOKEN) {
Config playerConfig = new Config(this, response.getAccessToken(), CLIENT_ID);
Spotify.getPlayer(playerConfig, this, new SpotifyPlayer.InitializationObserver() {
#Override
public void onInitialized(SpotifyPlayer spotifyPlayer) {
mPlayer = spotifyPlayer;
mPlayer.addConnectionStateCallback(MainActivity.this);
mPlayer.addNotificationCallback(MainActivity.this);
}
#Override
public void onError(Throwable throwable) {
Log.e("MainActivity", "Could not initialize player: " + throwable.getMessage());
}
});
}
}
}
#Override
protected void onDestroy() {
Spotify.destroyPlayer(this);
super.onDestroy();
}
#Override
public void onPlaybackEvent(PlayerEvent playerEvent) {
Log.d("MainActivity", "Playback event received: " + playerEvent.name());
switch (playerEvent) {
// Handle event type as necessary
default:
break;
}
}
#Override
public void onPlaybackError(Error error) {
Log.d("MainActivity", "Playback error received: " + error.name());
switch (error) {
// Handle error type as necessary
default:
break;
}
}
#Override
public void onLoggedIn() {
Log.d("MainActivity", "User logged in");
mPlayer.playUri(null, "spotify:track:2TpxZ7JUBn3uw46aR7qd6V", 0, 0);
}
#Override
public void onLoggedOut() {
Log.d("MainActivity", "User logged out");
}
#Override
public void onLoginFailed(int i) {
Log.d("MainActivity", "Login failed");
}
#Override
public void onTemporaryError() {
Log.d("MainActivity", "Temporary error occurred");
}
#Override
public void onConnectionMessage(String message) {
Log.d("MainActivity", "Received connection message: " + message);
}
}
My build.gradle (Module:app):
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.example.mammo.spotifyplayer"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
// This library handles authentication and authorization
compile 'com.spotify.sdk:spotify-auth:beta22-noconnect-2.20b#aar'
// This library handles music playback
compile 'com.spotify.sdk:spotify-player:beta22-noconnect-2.20b#aar'
compile 'com.android.support:appcompat-v7:24.2.1'
testCompile 'junit:junit:4.12'
}
And my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mammo.spotifyplayer">
<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"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Needed for LoginActivity to work -->
<activity
android:name="com.spotify.sdk.android.authentication.LoginActivity"
android:theme="#android:style/Theme.Translucent.NoTitleBar"/>
</application>
</manifest>
I'm developing a Android app and I'm still green in this area.
In my app I'm using the FusedLocationApi to get both the last know location and make Location update requests and I got a problem where, even with both Location and WiFi activated on Android Studio emulator and Samsung Galaxy S5, I never got the LocationListener's onLocationChanged() called.
Here is my code:
package com.trackit.app.locationupdatetest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = MapsActivity.class.getSimpleName();
public static final String STARTING_POSITION = "Rio de Janeiro"; //Application's default position
public static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 1; //Fine location permission
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private MapsActivity mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
(findViewById(R.id.Location)).setEnabled(false);
(findViewById(R.id.StreetView)).setEnabled(false);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null)
buildGoogleAPIClient();
//Create and configure a Location Request object to used while looking for location updates
if(mLocationRequest == null)
buildLocationRequest();
mActivity = this;
}
private synchronized void buildGoogleAPIClient() {
//Configuring the Google API client before connect
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private synchronized void buildLocationRequest() {
mLocationRequest = LocationRequest.create()
.setInterval(10000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setFastestInterval(1000)
.setSmallestDisplacement(1);
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
/**
* This method is called when the Activity is no longer visible to the user.
*/
#Override
protected void onStop() {
if(mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
super.onStop();
}
/**
* This callback is triggered when the map is ready to be used.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
public void buttonPressed(View buttonPressed){
displayUserLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
(findViewById(R.id.Location)).setEnabled(true);
(findViewById(R.id.StreetView)).setEnabled(true);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.e(TAG,"onConnectionFailed:"+connectionResult.getErrorCode()+","+connectionResult.getErrorMessage());
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull
int[] grantResults) {
//Process the user permission's response
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_FINE_LOCATION:
processLocationPermissionResult(grantResults);
break;
default:
}
}
public void processLocationPermissionResult(#NonNull int grantResults[]) {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
displayLocation();
else {} // permission denied, boo! Disable the functionality that depends on this permission.
}
public void displayUserLocation(){
//Verify if the app have permission to access user's location
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.
ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.
permission.ACCESS_FINE_LOCATION)) {
//Asks the permission to access the user's location
Toast.makeText(this, "This app needs to access your location. " +
"Allow the app to access it?", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MapsActivity.MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
} else displayLocation(); //If the permission was granted
}
public void displayLocation() throws SecurityException{
Location lastLocation = LocationServices.FusedLocationApi.
getLastLocation(mGoogleApiClient);
if(lastLocation != null) {
Log.e(TAG, "!!!!!!");
LatLng position = new LatLng(lastLocation.getLatitude(), lastLocation.
getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("Marker in " +
MapsActivity.STARTING_POSITION));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
} else{
Log.e(TAG, "??????");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 10 && location.getSpeed() < 55.55555555555556){
Log.e(TAG, "onLocationChanged() started");
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("Marker in " +
MapsActivity.STARTING_POSITION));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.e(TAG, "onLocationChanged() terminated");
}
/*else{
//Continue listening for a more accurate location
}*/
}
}
Below are both my AndroidManifest.xml and my gradle:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.trackit.app.locationupdatetest">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<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" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "com.trackit.app.locationupdatetest"
minSdkVersion 21
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.google.android.gms:play-services:9.4.0'
}
I'v searched a lot this week but I've got no helpful answer yet =s
These are some of the threads I've searched (I don't want to look like a lazy guy, because I'm not, I'm just stuck)
onLocationChanged does not get called using fusedLocationAPI.requestLocationUpdates
Unable to get location updates
onLocationChanged not called on some devices
on locaton changed never gets called in android google client api
onLocationChanged isn't being called
Can someone point my errors? =S
I'll venture this answer... if it's helpful, great... if not, sorry...
I have a similar Activity that uses the FusedLocationprovider.
I'm no expert, and can't say WHY yours is not working, but mine is working, and I've noticed the following differences:
YOUR CODE:
private synchronized void buildGoogleAPIClient() {
//Configuring the Google API client before connect
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private synchronized void buildLocationRequest() {
mLocationRequest = LocationRequest.create()
.setInterval(10000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setFastestInterval(1000)
.setSmallestDisplacement(1);
}
MY CODE:
protected synchronized void buildGoogleApiClient() {
this.mGoogleApiClient = new GoogleApiClient.Builder(this).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this).
addApi(LocationServices.API).build();
createLocationRequest();
}
protected void createLocationRequest() {
this.mLocationRequest = new LocationRequest();
this.mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
this.mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
Differences:
1) You put:
if(mLocationRequest == null)
buildLocationRequest();
in your onCreate method. Is this necessary? Wouldn't mLocationRequest always be null in onCreate()?
2) Your methods are private, mine protected
3) your createLocationrequest() is labeled as 'synchronized' ... could is be not working because of this?
4) you use the setSmallestDisplacement() method. I have seen posts that say this method doesn't work properly and results in onLocationChanged() not being called.
5) You instantiate your LocationRequest with: 'LocationRequest.create()' and not "new LocationRequest()' could this be the problem?
Does this help?
Here is an alternate answer.
There is one line of code that is vital in order for onlocationChanged to ever be called:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
And in your case, this code resides very deeply in your code with many conditions needing to be met for this to be reached:
Conditions you require:
security exception not thrown
last location == null
(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
button pushed
I would consider putting MORE LOGS in your code in order to determine that these conditions are in fact being met... trace backwards from:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
PS - I see you're using the Android N permission model. I have yet to put my toes in that water due to the confusion it seems to create... I just set my target SDK = 22. :)