I want to add leak canary to a test project. I created a project and did the steps from this video: https://www.youtube.com/watch?v=2VKBjlHtKMY
When I'm trying wrongWay(), the message "Dumping Memory app will freeze" is appearing in the emulator Nexus_5X_API_23. When I'm trying rightWay(), the same message is appearing too. There is no message "Dumping Memory app will freeze" in video when author using rightWay().
I cant understand why?
Where can I find a good tutorial about Leak Canary or other Leak Memory library.
So build.gradle is:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "com.example.vopolski.myleakcanary"
minSdkVersion 15
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'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vopolski.myleakcanary">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:name=".LeakCanaryApplication">
<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>
LeakCanaryApplication.java
package com.example.vopolski.myleakcanary;
import android.app.Application;
import android.content.Context;
import android.os.SystemClock;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
public class LeakCanaryApplication extends Application {
private RefWatcher refWatcher;
#Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
LeakCanaryApplication application =
(LeakCanaryApplication) context.getApplicationContext();
return application.refWatcher;
}
}
MainActivity.java
package com.example.vopolski.myleakcanary;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import android.app.Application;
public class MainActivity extends AppCompatActivity {
private String msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rightWay();
}
private void rightWay() {
new MyThread().start();
}
private class MyThread extends Thread {
#Override
public void run() {
while (true) {
SystemClock.sleep(1000);
}
}
}
private void wrongWay() {
new Thread() {
#Override
public void run() {
while (true){
SystemClock.sleep(1000);
}
}
}.start();
}
}
I think you should add the following to your Activity onDestroy method
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
You can refer to following URL https://github.com/square/leakcanary/wiki/FAQ
I think you're doing the rightWay() wrong.
MyThread should be static, otherwise it's a non-static inner class, and implicitly references the outer class Activity. The thread runs forever, so the activity won't be GCed. This is a memory leak.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
The community is reviewing whether to reopen this question as of 11 hours ago.
Improve this question
I got this error in my android studio:
Can't determine type for tag '<macro name="m3_comp_assist_chip_container_shape">?attr/shapeAppearanceCornerSmall</macro>'
Build.gradle(:app):
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 32
buildToolsVersion "33.0.1"
defaultConfig {
configurations.all {
resolutionStrategy { force 'androidx.core:core:1.6.0' }
}
applicationId "com.example.move_sensor"
minSdkVersion 21
targetSdkVersion 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
build.gradle(Mov_Sensor):
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.3"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
the error after building:
Can't determine type for tag '<macro name="m3_comp_assist_chip_container_shape">?attr/shapeAppearanceCornerSmall</macro>'
AndriodMainifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.move_sensor">
<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/Theme.Move_Sensor">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java:
package com.example.move_sensor;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////
MovementDetector.getInstance().addListener(new MovementDetector.Listener() {
#Override
public void onMotionDetected(SensorEvent event, float acceleration) {
TextView mMotionDetectionTextView = null;
mMotionDetectionTextView.setText("Acceleration: ["+String.format("%.3f",event.values[0])+","+String.format("%.3f",event.values[1])+","+String.format("%.3f",event.values[2])+"] "+String.format("%.3f", acceleration));
//if (acceleration > SettingsHelper.getInstance().getMotionDetectionThreshold()){
// mMotionDetectionTextView.setTextColor(Color.RED);
// } else {
mMotionDetectionTextView.setTextColor(Color.WHITE);
//}
}
});
////
}
#Override
public void onResume() {
super.onResume();
MovementDetector.getInstance().start();
}
#Override
public void onPause() {
super.onPause();
MovementDetector.getInstance().stop();
}
protected final String TAG = getClass().getSimpleName();
}
after searching for it online I thought that decrease of the dependencies
to previouse version will fix that. so I changed my dependencies from:
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
to:
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
but I got similar error:
Can't determine type for tag '<macro name="m3_comp_bottom_app_bar_container_color">?attr/colorSurface</macro>'
any help with this?
thank you
I added truecaller login for phone number verification I installed its working fine in the signed release apk if I generate a signed app bundle it's not working its calling onfailuerLister() error code 3 partnerKey error, it working fine if I have taken debug SHA1 if it's working in debug apk but not working in debug app-bundle, if I have taken SHA1 from release then release apk working fine but not working in the release app bundle, totally app-bundle not working at all, all other feature like location everything working fine in app-bundle except truecaller login
Mainactivity.java
package com.amitor.kotlintrue;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.truecaller.android.sdk.ITrueCallback;
import com.truecaller.android.sdk.TrueError;
import com.truecaller.android.sdk.TrueProfile;
import com.truecaller.android.sdk.TruecallerSDK;
import com.truecaller.android.sdk.TruecallerSdkScope;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
EditText editTextName, mobileNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = findViewById(R.id.editTextName);
mobileNumber = findViewById(R.id.mobileNumberText);
(findViewById(R.id.button)).setOnClickListener((View v) -> {
//check if TrueCaller SDk is usable
if(TruecallerSDK.getInstance().isUsable()){
TruecallerSDK.getInstance().getUserProfile(this);
}else{
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setMessage("Truecaller App not installed.");
dialogBuilder.setPositiveButton("OK", (dialog, which) -> {
Log.d(TAG, "onClick: Closing dialog");
dialog.dismiss();
}
);
dialogBuilder.setIcon(R.drawable.ic_launcher_background);
dialogBuilder.setTitle(" ");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
});
// customisation of TrueCaller function like color , text can be done here
TruecallerSdkScope trueScope = new TruecallerSdkScope.Builder(this, sdkCallback)
.consentMode(TruecallerSdkScope.CONSENT_MODE_BOTTOMSHEET)
.loginTextPrefix(TruecallerSdkScope.LOGIN_TEXT_PREFIX_TO_GET_STARTED)
.loginTextSuffix(TruecallerSdkScope.LOGIN_TEXT_SUFFIX_PLEASE_VERIFY_MOBILE_NO)
.ctaTextPrefix(TruecallerSdkScope.CTA_TEXT_PREFIX_USE)
.buttonShapeOptions(TruecallerSdkScope.BUTTON_SHAPE_ROUNDED)
.privacyPolicyUrl("https://tagle.in")
.termsOfServiceUrl("https://tagle.in")
.footerType(TruecallerSdkScope.FOOTER_TYPE_NONE)
.consentTitleOption(TruecallerSdkScope.SDK_CONSENT_TITLE_LOG_IN)
.build();
TruecallerSDK.init(trueScope);
}
private final ITrueCallback sdkCallback = new ITrueCallback() {
#Override
public void onSuccessProfileShared(#NonNull final TrueProfile trueProfile) {
Toast.makeText(MainActivity.this,trueProfile.firstName, Toast.LENGTH_LONG ).show();
Log.i(TAG, trueProfile.firstName + " " + trueProfile.lastName);
launchHome(trueProfile);
}
#Override
public void onFailureProfileShared(#NonNull final TrueError trueError) {
Toast.makeText(MainActivity.this,TrueError.ERROR_TYPE, Toast.LENGTH_LONG ).show();
// Log.i(TAG, trueError.toString());
}
#Override
public void onVerificationRequired(#Nullable final TrueError trueError) {
Toast.makeText(MainActivity.this,trueError.getErrorType(), Toast.LENGTH_LONG ).show();
Log.i(TAG, "onVerificationRequired");
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TruecallerSDK.SHARE_PROFILE_REQUEST_CODE) {
TruecallerSDK.getInstance().onActivityResultObtained(this, requestCode, resultCode, data);
} }
private void launchHome(TrueProfile trueProfile) {
editTextName.setText(trueProfile.firstName);
mobileNumber.setText(trueProfile.phoneNumber);
// startActivity(new Intent(getApplicationContext(), HomeActivity.class)
// .putExtra("profile", trueProfile));
// finish();
}
}
build.gradle
plugins {
id 'com.android.application'
}
android {
signingConfigs {
debug {
storeFile file('/Users/moden/key_store.jks')
storePassword '189556'
keyAlias 'key0'
keyPassword '189556'
}
release {
storeFile file('/Users/moden/key_store.jks')
storePassword '123456'
keyAlias 'key0'
keyPassword '123456'
}
}
namespace 'com.amitor.kotlintrue'
compileSdk 33
defaultConfig {
applicationId "com.amitor.kotlintrue"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
implementation 'com.truecaller.android.sdk:truecaller-sdk:2.7.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-sdk tools:overrideLibrary="com.truecaller.android.sdk" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Kotlintrue"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<meta-data
android:name="com.truecaller.android.sdk.PartnerKey"
android:value="3sBRy9fe254fbac0541b5988fb6b085190ed4" />
</application>
</manifest>
I changed many partners kyes changed dependency I tried every solution which I got but not working at all
If you are using your bundle tool to create an apk for testing then you can use the following command to generate a universal apk.
bundletool build-apks --bundle=<bundle_file_location> --output=universal.apks --mode=universal --ks=<keystore_name> --ks-pass='pass:<keystore_passowrd>' --ks-key-alias=<keystore_alias_name> --key-pass='pass:key_password'
Then extract the apk using following command
unzip universal.apks -d apks
For playstore apps you have to update your SHA-1 with the SHA-1 from playstore App Integrity --> App Signing tab in truecaller page.
So Truecaller SDK gets a bit tricky when you are generating bundles. Let's say you have a current Truecaller key which you have made for your release/debug builds and when you run the application it runs fine but when you make a bundle (.aab) of it, it doesn't work.
Let's see how to fix this :
If you read the Truecaller SDK docs carefully ( Link - https://docs.truecaller.com/truecaller-sdk/android/getting-release-ready/google-play-app-signing )
you will find that you would need to create a new Truecaller Partner key but this time with the SHA1 from your Google Play console.
Steps:
Go to your app on Play console.
Find out the SHA1 of your app generated by Play Console ( It's different from the one you provided via Android Studio )
Use that SHA1 to generate a new Truecaller Partner key
Use this partner key when you are making bundles for releasing on Play Store.
If you want to directly install on your device this key won't work so you will have to use your previous key only.
Tip : You can keep both the keys in your strings.xml and use the key generated via SHA1 from Play Console when you are making bundles otherwise use your normal key for debugging.
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.
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>
this is my first time integrating Google Analytics with an Android app and I'm having troubles following these indications
https://developers.google.com/analytics/devguides/collection/android/v4/
It looks like that when adding this part of the code to MainActivity.java it doesn't work so I'm not able to compile the app.
// Obtain the shared Tracker instance.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
my code:
build.gradle (app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.developername.myapp"
manifestPlaceholders = [manifestApplicationId: "${applicationId}",
onesignal_app_id: "XXX",
onesignal_google_project_number: "XXX"]
minSdkVersion 15
targetSdkVersion 23
versionCode 6
versionName "2.6"
}
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:23.2.0'
compile 'com.google.android.gms:play-services-ads:9.0.2'
compile 'com.android.support:gridlayout-v7:23.2.0'
compile 'com.onesignal:OneSignal:2.+#aar'
compile 'com.google.android.gms:play-services-gcm:9.0.2'
compile 'com.google.android.gms:play-services-analytics:9.0.2'
}
apply plugin: 'com.google.gms.google-services'
build.gradle (project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Application.java
package com.developername.myapp;
import android.app.Application;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import android.util.Log;
import org.json.JSONObject;
import com.onesignal.OneSignal;
public class Radio extends Application{
private Tracker mTracker;
synchronized public Tracker getDefaultTracker() {
if (mTracker == null) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
mTracker = analytics.newTracker(R.xml.global_tracker);
}
return mTracker;
}
#Override
public void onCreate() {
super.onCreate();
OneSignal.startInit(this)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.setAutoPromptLocation(true)
.init();
}
private class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
/**
* Callback to implement in your app to handle when a notification is opened from the Android status bar or
* a new one comes in while the app is running.
* This method is located in this Application class as an example, you may have any class you wish implement NotificationOpenedHandler and define this method.
*
* #param message The message string the user seen/should see in the Android status bar.
* #param additionalData The additionalData key value pair section you entered in on onesignal.com.
* #param isActive Was the app in the foreground when the notification was received.
*/
#Override
public void notificationOpened(String message, JSONObject additionalData, boolean isActive) {
String additionalMessage = "";
try {
if (additionalData != null) {
if (additionalData.has("actionSelected"))
additionalMessage += "Pressed ButtonID: " + additionalData.getString("actionSelected");
additionalMessage = message + "\nFull additionalData:\n" + additionalData.toString();
}
Log.d("OneSignalExample", "message:\n" + message + "\nadditionalMessage:\n" + additionalMessage);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
MainActivity.java
package com.developername.myapp.activity;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.developername.myapp.R;
import com.developername.myapp.Radio;
import com.developername.myapp.fragment.MainFragment;
public class MainActivity extends BaseActivity{
AdView mAdView;
private static boolean activityStarted;
Radio application = (Radio) getApplication();
mTracker = application.getDefaultTracker();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (activityStarted
&& getIntent() != null
&& (getIntent().getFlags() & Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
finish();
return;
}
activityStarted = true;
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check your logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder().build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
addFragment(new MainFragment(), true);
}
}
Android Studio seems to be finding an error at
Radio application = (Radio) getApplication();
mTracker = application.getDefaultTracker();
What I'm doing wrong?
Help please.
Thanks
You Just need to add your Application file to Manifest file at Application Level. Like this.
<application
android:name=".Application"
android:allowBackup="false"
android:icon="#mipmap/app_logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/app_logo"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:allowBackup">
Also Define the Network and Network Status Primission .