I have an android app that does not require a log in, but I do have Anonymous sign-in enabled so that I can retrieve the userID from Firebase and use it to log specific events. I have the feeling that it just stopped retrieving the UID from Firebase.
What I've done to resolve the issue is the following:
updated all the dependencies
updated the emulator
Installed a new emulator
re-added the google services plugin
re-added google-services.json file
updated Android Manifest
I've tried to create a login-activity for the sake of testing, where through a button with an onclicklisterer, the user get's anoynmously logged in.
I've doubled checked Local History in Android Studio to see whether big changes were made to the code, not the case. See screenshot
Enabled and disabled anonymous login from the Firebase Console.
Re-written the entire code based on documentation from Firebase.
I've basically tried every solution there is
My Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.superawesome.metime">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/wazzup"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Cardview" />
<activity android:name=".cardviewactivity" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxx" />
<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>
<activity
android:name="com.google.firebase.auth.internal.FederatedSignInActivity"
tools:replace="android:launchMode"
android:launchMode="standard" />
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
My code:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true; // go back to the first screen
case R.id.cardoverview:
startActivity(new Intent(this, cardviewactivity.class));
return true; //go to the screen where all the swiped right activities are stored
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w("This Tag", "getInstanceId failed", task.getException());
return;
} else {
Log.d("This tag", "We need this");
}
}
});
swipeDb = FirebaseDatabase.getInstance().getReference().child("Users");
final FirebaseFirestore db = FirebaseFirestore.getInstance();
//Anonymous user login to be registered in Firebase
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser(); // save the UID of the user in users in Firebase without having to log in
final String UID = mCurrentUser.getUid();
DatabaseReference currentUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child("UID");
currentUserDb.setValue(UID); //save the User UID to the Firebase Realtime database
// Calling to the AdMob API to add advertisements to the banner in the main view.Gotta make that dough
// Change this to big cards in the future
final AdView adView = findViewById(R.id.adView);
final AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
Screenshot to Firebase Authentication
Error I'm receiving from the logcat:
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
I/FirebaseCrashlytics: Initializing Crashlytics 17.0.0
I/FirebaseInitProvider: FirebaseApp initialization successful
I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
V/FA: onActivityCreated
W/rawesome.metim: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
V/FA: App measurement disabled via the init parameters
I/FA: App measurement initialized, version: 28000
To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.superawesome.metime
D/FA: Debug-level message logging enabled
V/FA: Detected application was in foreground
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.superawesome.metime, PID: 21746
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.superawesome.metime/com.superawesome.metime.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3341)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3485)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2045)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.superawesome.metime.MainActivity.onCreate(MainActivity.java:118)
at android.app.Activity.performCreate(Activity.java:7989)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3316)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3485)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2045)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
V/FA: Connecting to remote service
D/FA: Event not sent since app measurement is disabled
com.superawesome.metime.MainActivity.onCreate(MainActivity.java:118) --> final String UID = mCurrentUser.getUid();
I've been trying to resolve this issue for over a week now with no success
Edit:
I know I can add listeners to see if the user is anonymously signed in or not. The whole problem around this is that the user is not being signed in anymore at all.
Edit2:
From logcat:
2020-05-30 12:39:53.655 23257-23297/com.superawesome.metime I/DynamiteModule: Selected remote version of com.google.android.gms.ads.dynamite, version >= 21600
2020-05-30 12:39:53.658 23257-23297/com.superawesome.metime V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
2020-05-30 12:39:53.770 23257-23311/com.superawesome.metime I/TetheringManager: registerTetheringEventCallback:com.superawesome.metime
2020-05-30 12:39:53.818 23257-23303/com.superawesome.metime W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2020-05-30 12:39:54.025 23257-23303/com.superawesome.metime I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
2020-05-30 12:39:54.076 23257-23257/com.superawesome.metime I/FirebaseCrashlytics: Initializing Crashlytics 17.0.0
2020-05-30 12:39:54.220 23257-23257/com.superawesome.metime I/FirebaseInitProvider: FirebaseApp initialization successful
2020-05-30 12:39:54.332 23257-23332/com.superawesome.metime D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
2020-05-30 12:39:54.342 23257-23332/com.superawesome.metime D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
2020-05-30 12:39:54.362 23257-23332/com.superawesome.metime D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
2020-05-30 12:39:54.527 23257-23315/com.superawesome.metime V/FA: App measurement disabled via the init parameters
2020-05-30 12:39:55.234 23257-23315/com.superawesome.metime I/FA: App measurement initialized, version: 28000
2020-05-30 12:39:55.247 23257-23315/com.superawesome.metime I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
2020-05-30 12:39:55.267 23257-23315/com.superawesome.metime I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.superawesome.metime
2020-05-30 12:39:55.274 23257-23315/com.superawesome.metime D/FA: Debug-level message logging enabled
2020-05-30 12:39:57.009 23257-23315/com.superawesome.metime V/FA: Detected application was in foreground
2020-05-30 12:39:57.995 23257-23315/com.superawesome.metime V/FA: Connecting to remote service
2020-05-30 12:40:23.846 23257-23311/com.superawesome.metime W/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE. Will retry token retrieval
2020-05-30 12:41:23.931 23257-23311/com.superawesome.metime W/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE. Will retry token retrieval
2020-05-30 12:42:54.030 23257-23311/com.superawesome.metime W/FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE. Will retry token retrieval
Related
In the project I made on Android studio, I put a button on the user login page to log in with a google account.The account name appears in the Choose an account section.
In the Authentication section, the name does not appear as an account login.The user's mail and password have been entered and saved.When I log into the application with that account, I want it to redirect to the other page, but it does not redirect to the MainActivity2.java page. I would be glad if you could help.
Run:
Connected to process 18504 on device 'emulator-5556'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/MultiDex: VM with version 2.1.0 has multidex support
Installing application
VM has multidex support, MultiDex support library is disabled.
I/ple.geziprojec: Waiting for a blocking GC ClassLinker
I/ple.geziprojec: WaitForGcToComplete blocked ClassLinker on ClassLinker for 176.388ms
W/ple.geziprojec: Verification of void com.google.android.gms.common.internal.StringResourceValueReader.<init>(android.content.Context) took 177.170ms (118.53 bytecodes/s) (1040B approximate peak alloc)
W/ComponentDiscovery: Class com.google.firebase.dynamicloading.DynamicLoadingRegistrar is not an found.
I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
I/FirebaseInitProvider: FirebaseApp initialization successful
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:20 and remote module com.google.android.gms.measurement.dynamite:21
Selected remote version of com.google.android.gms.measurement.dynamite, version >= 21
V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
W/ple.geziprojec: Verification of void com.google.android.gms.common.api.internal.GoogleApiManager$zaa.connect() took 107.853ms (806.65 bytecodes/s) (2328B approximate peak alloc)
W/ple.geziprojec: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ple.geziprojec: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
W/ple.geziprojec: Verification of void com.google.android.gms.common.internal.BaseGmsClient.zza(int, android.os.IInterface) took 133.587ms (3346.13 bytecodes/s) (5928B approximate peak alloc)
I/ple.geziprojec: The ClassLoaderContext is a special shared library.
I/ple.geziprojec: The ClassLoaderContext is a special shared library.
I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation
I/DynamiteModule: Considering local module com.google.android.gms.signinbutton_dynamite:0 and remote module com.google.android.gms.signinbutton_dynamite:2
Selected remote version of com.google.android.gms.signinbutton_dynamite, version >= 2
W/ple.geziprojec: Verification of int com.google.android.gms.common.internal.GmsClientSupervisor$zza.zzq() took 161.972ms (18.52 bytecodes/s) (720B approximate peak alloc)
V/FA: onActivityCreated
D/HostConnection: HostConnection::get() New Host Connection established 0xe9121d40, tid 18553
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xe9124ba0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xe9124ba0: ver 2 0 (tinfo 0xe9455f70) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xe9123ef0, tid 18553
D/goldfish-address-space: allocate: Ask for block of size 0x100
allocate: ioctl allocate returned offset 0x3fe83c000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_2
W/ple.geziprojec: Verification of void ic.e() took 123.348ms (6809.95 bytecodes/s) (11464B approximate peak alloc)
W/ple.geziprojec: Verification of void ie.<init>(jc) took 152.305ms (98.49 bytecodes/s) (968B approximate peak alloc)
I/OpenGLRenderer: Davey! duration=771ms; Flags=1, IntendedVsync=4143801720841, Vsync=4143835054173, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=4143845992300, AnimationStart=4143846040000, PerformTraversalsStart=4143846105800, DrawStart=4144157390900, SyncQueued=4144354861800, SyncStart=4144360117400, IssueDrawCommandsStart=4144360507700, SwapBuffers=4144536078100, FrameCompleted=4144578165500, DequeueBufferDuration=318500, QueueBufferDuration=1625500, GpuCompleted=0,
W/ple.geziprojec: Verification of void lt.B() took 115.481ms (207.83 bytecodes/s) (992B approximate peak alloc)
I/Choreographer: Skipped 49 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=988ms; Flags=0, IntendedVsync=4143851699017, Vsync=4144668365651, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=4144680002300, AnimationStart=4144680060000, PerformTraversalsStart=4144680717500, DrawStart=4144727417500, SyncQueued=4144728390300, SyncStart=4144731782000, IssueDrawCommandsStart=4144731852000, SwapBuffers=4144734026400, FrameCompleted=4144844020200, DequeueBufferDuration=279000, QueueBufferDuration=16261600, GpuCompleted=0,
W/ple.geziprojec: Verification of void rc.<clinit>() took 163.597ms (378.98 bytecodes/s) (1416B approximate peak alloc)
V/FA: App measurement collection enabled
V/FA: App measurement enabled for app package, google app id: com.example.geziproject, 1:1088981466528:android:40238883a0fda69fa1f8c5
I/FA: App measurement initialized, version: 34027
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.geziproject
D/FA: Debug-level message logging enabled
V/FA: Connecting to remote service
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
V/FA: Activity resumed, time: 4143853
I/FA: Tag Manager is not found and thus will not be used
V/FA: Connection attempt already in progress
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 5
V/FA: Recording user engagement, ms: 4309
V/FA: Activity paused, time: 4148164
V/FA: onActivityCreated
V/FA: Activity resumed, time: 4148325
V/FA: Screen exposed for less than 1000 ms. Event not sent. time: 214
V/FA: Activity paused, time: 4148556
D/FA: Application going to the background
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10154; state: ENABLED
V/FA: Activity resumed, time: 4154166
V/FA: Inactivity, disconnecting from the service
W/ConnectionTracker: Exception thrown while unbinding
java.lang.IllegalArgumentException: Service not registered: ls#9d99311
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1757)
at android.app.ContextImpl.unbindService(ContextImpl.java:1874)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:792)
at ci.f(:com.google.android.gms.dynamite_measurementdynamite#204713100#20.47.13 (150700-0):1)
at ci.d(:com.google.android.gms.dynamite_measurementdynamite#204713100#20.47.13 (150700-0):2)
at lt.E(:com.google.android.gms.dynamite_measurementdynamite#204713100#20.47.13 (150700-0):9)
at ld.a(:com.google.android.gms.dynamite_measurementdynamite#204713100#20.47.13 (150700-0):3)
at ef.run(:com.google.android.gms.dynamite_measurementdynamite#204713100#20.47.13 (150700-0):3)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at iy.run(:com.google.android.gms.dynamite_measurementdynamite#204713100#20.47.13 (150700-0):5)
Gradle dependencies:
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.firebase:firebase-auth:20.0.1'
implementation 'com.google.firebase:firebase-database:19.6.0'
implementation 'androidx.navigation:navigation-fragment:2.3.2'
implementation 'androidx.navigation:navigation-ui:2.3.2'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.+'
implementation platform('com.google.firebase:firebase-bom:26.2.0')
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'me.everything:providers-android:1.0.1'
implementation 'com.google.android.gms:play-services-auth:19.0.0'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-core:18.0.0'
}
apply plugin: 'com.google.gms.google-services'
LoginActivity.java:
public class LoginActivity extends AppCompatActivity {
private SignInButton signInButton;
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private Button signout;
private final static int RC_SIGN_IN=123;
protected void onStart() {
super.onStart();
FirebaseUser user=mAuth.getCurrentUser();
if(user!=null){
Intent intent= new Intent(getApplicationContext(),MainActivity2.class);
startActivity(intent);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
createRequest();
signInButton=findViewById(R.id.signin);
mAuth=FirebaseAuth.getInstance();
signout=findViewById(R.id.sign_out);
signInButton.setOnClickListener(v -> signIn());
}
private void createRequest() {
GoogleSignInOptions gso= new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(String.valueOf(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient= GoogleSignIn.getClient(this,gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RC_SIGN_IN){
Task<GoogleSignInAccount> task=GoogleSignIn.getSignedInAccountFromIntent(data);
//handleSignInResult(task);
try{
GoogleSignInAccount account=task.getResult(ApiException.class);
Toast.makeText(getApplicationContext(),"giriş başarılı",Toast.LENGTH_LONG).show();
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
Toast.makeText(this,e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
Intent intent= new Intent(getApplicationContext(),MainActivity2.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this,"başarısız",Toast.LENGTH_LONG).show();
}
});
}
MainActivity2.java:
public class MainActivity2 extends AppCompatActivity {
TextView name,mail;
Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
logout= findViewById(R.id.logout);
name=findViewById(R.id.name);
mail=findViewById(R.id.email);
GoogleSignInAccount signInAccount= GoogleSignIn.getLastSignedInAccount(this);
if(signInAccount!=null){
name.setText(signInAccount.getDisplayName());
mail.setText(signInAccount.getEmail());
}
logout.setOnClickListener(v -> {
FirebaseAuth.getInstance().signOut();
Intent intent=new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
});
}
}
I) Below is code for parsing data async from google sheet and works fine as long as the internet speed is good but crashes on slow speed. How to address this? I have fixed for no internet.
II) If the google sheet is opened for update ( one a row at a time), the system crashes on trying to open. How can I skip the rows which are not assessible ( or updating) ?
III) Is there any way to find time when the google sheet was last updated ?
IV) How to tell google maps not to open the map till the parsing is done?
protected void ReadGoogleSheetAsync(){
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=mykey");
}
private void processJson(JSONObject object) {
try {
JSONArray rows = object.getJSONArray("rows");
for (int r = 0; r < rows.length(); ++r) {
JSONObject row = rows.getJSONObject(r);
JSONArray columns = row.getJSONArray("c");
UserData ud = new UserData();
ud.setId(columns.getJSONObject(0).getString("f"));
ud.setName(columns.getJSONObject(1).getString("v"));
ud.setState(columns.getJSONObject(2).getString("v"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
This is based on DownloadWebpageTask.java from git.
Stacktrace:
08/03 06:41:06: Launching 'MapsActivity' on vivo vivo 1902.
$ adb shell am start -n "com.example.fmtxstatus/com.example.fmtxstatus.MapsActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Waiting for process to come online... Connected to process 6659 on device 'vivo-vivo_1902-CIEMU8KRPFLFHEBU'. Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page. D/VivoTheme: load old package name start I/mple.fmtxstatu: The ClassLoaderContext is a special shared library. W/mple.fmtxstatu: JIT profile information will not be recorded: profile file does not exits.
JIT profile information will not be recorded: profile file does not exits. D/NightModeController: com.example.fmtxstatus = true
disable nightmode package:com.example.fmtxstatus I/FtBuild: getRomVersion mRomVer=9.0 D/VivoPhoneWindow: DEBUG_ALIENSCREEN:getRotation mRotation=0 I/PhoneWindow: initSystemUIColor I/zzbz: Making Creator dynamically W/mple.fmtxstatu: Unsupported class loader W/mple.fmtxstatu: Skipping duplicate class check due to unsupported classloader I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:202614000 I/DynamiteModule: Selected remote version of com.google.android.gms.maps_dynamite, version >= 202614000 V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils I/DynamiteLoaderV2: [71] Mapsdynamite W/mple.fmtxstatu: Unsupported class loader W/mple.fmtxstatu: Skipping duplicate class check due to unsupported classloader I/Google Maps Android API: Google Play services client version: 12451000 I/Google Maps Android API: Google Play services package version: 202614029 W/mple.fmtxstatu: Accessing hidden field Ljava/nio/Buffer;->address:J (light greylist, reflection) I/mple.fmtxstatu: The ClassLoaderContext is a special shared library. E/libc: Access denied finding property "persist.vendor.log.tel_dbg" W/com.example.fmtxstatus: type=1400 audit(0.0:118917): avc: denied { read } for comm=4173796E635461736B202332 name="u:object_r:mtk_em_tel_log_prop:s0" dev="tmpfs" ino=6814 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:mtk_em_tel_log_prop:s0 tclass=file permissive=0 D/NetworkSecurityConfig: No Network Security Config specified, using platform default D/OpenGLRenderer: Dumper init 4 threads <0x7a04d12b40> D/OpenGLRenderer: <com.example.fmtxstatus> is running.
Skia GL Pipeline I/SurfaceFactory: [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl#5b77117 D/ViewRootImpl[MapsActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl#ff0122, this = DecorView#13807b3[MapsActivity] V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl#ff0122, this = DecorView#13807b3[MapsActivity] I/CatcherGestureDetector: DecorView onAttached D/yuan: onVisibilityChanged----com.google.maps.api.android.lib6.impl.ci{2c1c49c G.ED..C.. ......I. 0,0-0,0} D/Surface: Surface::allocateBuffers(this=0x79f461d000) I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0 I/OpenGLRenderer: Initialized EGL, version 1.4 D/OpenGLRenderer: Swap behavior 2 D/Surface: Surface::connect(this=0x79f461d000,api=1) D/TextureView: getHardwareLayer, createNewSurface:true I/BufferQueue: [unnamed-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:-1) BufferQueue core=(6659:com.example.fmtxstatus) W/mple.fmtxstatus: type=1400 audit(0.0:118918): avc: denied { read } for name="u:object_r:graphics_debug_prop:s0" dev="tmpfs" ino=6754 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:graphics_debug_prop:s0 tclass=file permissive=0 E/libc: Access denied finding property "vendor.debug.sf.stc_interval" W/mple.fmtxstatus: type=1400 audit(0.0:118919): avc: denied { read } for name="u:object_r:debug_bq_dump_prop:s0" dev="tmpfs" ino=6713 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:debug_bq_dump_prop:s0 tclass=file permissive=0 E/libc: Access denied finding property "vendor.debug.bq.dump" W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar I/BufferQueueConsumer: [unnamed-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) connect(C): consumer=(6659:com.example.fmtxstatus) controlledByApp=true E/libc: Access denied finding property "vendor.debug.bq.dump" W/mple.fmtxstatus: type=1400 audit(0.0:118920): avc: denied { read } for name="u:object_r:debug_bq_dump_prop:s0" dev="tmpfs" ino=6713 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:debug_bq_dump_prop:s0 tclass=file permissive=0 I/BufferQueueConsumer: [unnamed-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) setConsumerName: unnamed-6659-0 E/libc: Access denied finding property "vendor.debug.bq.line" W/mple.fmtxstatus: type=1400 audit(0.0:118921): avc: denied { read } for name="u:object_r:graphics_debug_prop:s0" dev="tmpfs" ino=6754 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:graphics_debug_prop:s0 tclass=file permissive=0 E/libc: Access denied finding property "vendor.debug.bq.dump" I/BufferQueueConsumer: [SurfaceTexture-0-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) setConsumerName: SurfaceTexture-0-6659-0 W/mple.fmtxstatus: type=1400 audit(0.0:118922): avc: denied { read } for name="u:object_r:debug_bq_dump_prop:s0" dev="tmpfs" ino=6713 scontext=u:r:untrusted_app:s0:c252,c256,c512,c768 tcontext=u:object_r:debug_bq_dump_prop:s0 tclass=file permissive=0 I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp I/BufferQueueConsumer: [SurfaceTexture-0-6659-0](this:0x7a03285800,id:0,api:0,p:-1,c:6659) setDefaultBufferSize: width=720 height=1404 D/OpenGLRenderer: 0x7a032fb740 setSurfaceTexture: 0x0 to 0x7a032d1800 D/Linux: [Posix_connect Debug]Process com.example.fmtxstatus :443 E/ion: ioctl c0044901 failed with code -1: Invalid argument I/GLConsumer: [SurfaceTexture-0-6659-0] attachToContext D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< E/Google Maps Android API: Authorization failure. Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map. E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
com.example.fmtxstatus W/System: ClassLoader referenced unknown path: system/framework/mediatek-cta.jar I/System.out: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp D/Linux: [Posix_connect Debug]Process com.example.fmtxstatus :443 D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object D/OpenSSLLib: OpensslErr:Module:12(177:); file:external/boringssl/src/crypto/asn1/asn1_lib.c ;Line:168;Function:ASN1_get_object I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found. I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:5
Selected remote version of com.google.android.gms.googlecertificates, version >= 5 I/DynamiteLoaderV2: [71] Googlecertificates W/mple.fmtxstatu: Unsupported class loader W/mple.fmtxstatu: Skipping duplicate class check due to unsupported classloader I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< I/System.out: [OkHttp] sendRequest>> I/System.out: [OkHttp] sendRequest<< I/Choreographer: Skipped 52 frames! The application may be doing too much work on its main thread.
The issue seems to be related to poor handling of HttpURLConnection object. There are issues in the downloadUrl() method implementation in the class DownloadWebpageTask, which may be relevant to the queries 1-3, the variable responseCode is never used.
If the response is not HttpURLConnection.HTTP_OK , try reconnecting ( or till a custom timeout) or return a null string. On slow internet or bad connection, the response will not be HttpURLConnection.HTTP_OK, hence trying to reference the json-object may lead to undefined behavior.
private String downloadUrl(String urlString) throws IOException {
/*...*/
conn.connect();
responseCode = conn.getResponseCode();
if( responseCode == HttpURLConnection.HTTP_OK)
{
// do something
}
else
{
// retry or return null string
}
}
The function processJson(object) in the snippet should be called only if json-object is not null. Issues under queries 1 to 3 should be taken care of with these modifications.
protected void ReadGoogleSheetAsync(){
new DownloadWebpageTask(new AsyncResult() {
#Override
public void onResult(JSONObject object) {
if(object) processJson(object);
}
}).execute("https://spreadsheets.google.com/tq?key=mykey");
}
For query 4 related to google maps api, OnMapReadyCallback is called when the map is ready to be used. Override onMapReady() method to find if the map is ready or not.
I have a mapsActivity that don't load correctly. The Api key is well
configured because if I call to maps activity after the splashScreen everything works OK. My emulator has installed api 26
This is the log when I call Mapsactivity after splashScreen.
> I/FA: App measurement initialized, version: 22048
> I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
> I/FA: To enable faster debug mode event logging run:
> adb shell setprop debug.firebase.analytics.app com.lyntia.android.mera
> D/FA: Debug-level message logging enabled
> D/SplashScreenActivity: User has logged in, token OK
> V/FA: onActivityCreated
> I/zygote: Background concurrent copying GC freed 15298(1332KB) AllocSpace objects, 11(220KB) LOS >objects, 55% free, 1238KB/2MB,
> paused 2.344ms total 101.117ms
> V/FA: Connecting to remote service
> V/FA: Connection attempt already in progress
> I/zzbz: Making Creator dynamically
> W/zygote: Skipping duplicate class check due to unrecognized classloader
> I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module
> com.google.android.gms.maps_dynamite:221
> Selected remote version of com.google.android.gms.maps_dynamite, version >= 221
> V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
> V/FA: Connection attempt already in progress
> W/zygote: Skipping duplicate class check due to unrecognized classloader
> I/zygote: Do partial code cache collection, code=30KB, data=22KB
> After code cache collection, code=30KB, data=22KB
> I/zygote: Increasing code cache capacity to 128KB
> I/Google Maps Android API: Google Play services client version: 12451000
> I/Google Maps Android API: Google Play services package version: 16089022
> I/zygote: Do partial code cache collection, code=52KB, data=38KB
> I/zygote: After code cache collection, code=52KB, data=38KB
> Increasing code cache capacity to 256KB
> D/skia: --- SkAndroidCodec::NewFromStream returned null
> V/FA: Activity resumed, time: 3535145
> I/FA: Tag Manager is not found and thus will not be used
> D/OpenGLRenderer: HWUI GL Pipeline
> I/zygote: Do full code cache collection, code=83KB, data=87KB
> D/: HostConnection::get() New Host Connection established 0xa3a7c440, tid 15830
> I/OpenGLRenderer: Initialized EGL, version 1.4
> D/OpenGLRenderer: Swap behavior 1
> I/zygote: After code cache collection, code=81KB, data=65KB
> W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
> D/OpenGLRenderer: Swap behavior 0
> D/EGL_emulation: eglCreateContext: 0xa63060a0: maj 2 min 0 rcv 2
> V/FA: Connection attempt already in progress
> V/FA: Connection attempt already in progress
> D/EGL_emulation: eglMakeCurrent: 0xa63060a0: ver 2 0 (tinfo 0x88213db0)
> E/RecyclerView: No adapter attached; skipping layout
> D/: HostConnection::get() New Host Connection established 0x932f0040, tid 15826
> D/EGL_emulation: eglCreateContext: 0xa6305920: maj 1 min 0 rcv 1
> D/EGL_emulation: eglMakeCurrent: 0xa63060a0: ver 2 0 (tinfo 0x88213db0)
> D/EGL_emulation: eglMakeCurrent: 0xa6305920: ver 1 0 (tinfo 0x92ef6900)
> D/FA: Connected to remote service
> V/FA: Processing queued up service tasks: 5
> I/zygote: Do partial code cache collection, code=111KB, data=97KB
> I/zygote: After code cache collection, code=102KB, data=92KB
> I/zygote: Increasing code cache capacity to 512KB
> W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not >found.
> I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote >module
> com.google.android.gms.googlecertificates:4
> Selected remote version of com.google.android.gms.googlecertificates, version >= 4
> W/zygote: Skipping duplicate class check due to unrecognized classloader
> V/FA: Inactivity, disconnecting from the service
> I/zygote: Do full code cache collection, code=240KB, data=192KB
> After code cache collection, code=208KB, data=138KB
> I/zygote: Do partial code cache collection, code=245KB, data=187KB
> I/zygote: After code cache collection, code=245KB, data=187KB
> Increasing code cache capacity to 1024KB
This is the log when I call mapsActivity in they correct place (Don't work).
D/EGL_emulation: eglMakeCurrent: 0xa3de7c80: ver 2 0 (tinfo 0xa3918900)
D/EGL_emulation: eglMakeCurrent: 0xa3de7c80: ver 2 0 (tinfo 0xa3918900)
V/FA: Recording user engagement, ms: 1649
V/FA: Activity paused, time: 671631
V/FA: onActivityCreated
I/zygote: JIT allocated 56KB for compiled code of void android.view.View.<init>(android.content.Context, android.util.AttributeSet, int, int)
I/zzbz: Making Creator dynamically
W/zygote: Skipping duplicate class check due to unrecognized classloader
I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:221
Selected remote version of com.google.android.gms.maps_dynamite, version >= 221
V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
W/zygote: Skipping duplicate class check due to unrecognized classloader
I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 16089022
V/FA: Activity resumed, time: 672047
E/RecyclerView: No adapter attached; skipping layout
D/: HostConnection::get() New Host Connection established 0x9157a5c0, tid 7910
D/EGL_emulation: eglCreateContext: 0x911c7740: maj 1 min 0 rcv 1
D/EGL_emulation: eglMakeCurrent: 0xa3de7c80: ver 2 0 (tinfo 0xa3918900)
D/EGL_emulation: eglMakeCurrent: 0x911c7740: ver 1 0 (tinfo 0x90eec950)
D/EGL_emulation: eglMakeCurrent: 0xa3de7c80: ver 2 0 (tinfo 0xa3918900)
D/EGL_emulation: eglMakeCurrent: 0xa3de7c80: ver 2 0 (tinfo 0xa3918900)
W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
Selected remote version of com.google.android.gms.googlecertificates, version >= 4
W/zygote: Skipping duplicate class check due to unrecognized classloader
I/zygote: Do full code cache collection, code=471KB, data=305KB
After code cache collection, code=467KB, data=235KB
V/FA: Inactivity, disconnecting from the service
I/zygote: Do partial code cache collection, code=495KB, data=276KB
I/zygote: After code cache collection, code=495KB, data=276KB
Increasing code cache capacity to 2MB
activity_maps.xml
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3" />
MapsActivity.java
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
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 {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#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));
}
}
androidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MeraApp"
android:allowBackup="true"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<!--
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" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Before mapsactivity there are some activities that get and post data from/to the server.
I don't know if it can be a problem with memory, cache...
Any help?
Trying to read a file from the downloads directory for an application I'm working on, and I cannot for the life of me get it to open the dialog for the user to give permission to access files.
Trying to add the ability to import data from a file the user can download from another site. Attempting to open the file from the download folder is nothing but failure. Finally determine that it's definitely the permissions to access the file that aren't being enabled, and I can't get the dialog to allow permissions to ever come up. Give up and create a new app from scratch
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
paste in the android developer site example of how to enable permissions and that gives errors from scratch in the android development studio.
"Wrong 1st argument type. Found: 'android.content.Context', required: 'android.app.Activity'
Inspection info:
shouldShowRequestPermissionRationale (android.app.Activity,String)
in ActivityCompat cannot be applied to (android.content.Context,String)"
using (activity)this works to remove the error, but doesn't give much trust in the android docs at this point.
Still can't get the permission dialog to come up. Try several other examples and Stackoverflow "solutions" with no joy.
finish basic app from scratch, stick in some printlns to show progress, no dialog in the emulator or on my phone. Logcat shows that the everything seems to be working in the process, it's finding the permission no allowed, branching to the part to ask for it, then testing to see if the response allowed it, except for the part where it actually opens a dialog. I've had no luck finding anything relevant on the egl errors.
Example logcat:
07-20 08:30:19.999 23735-23735/anticlimacticteleservices.myapplication I/System.out: need to ask for permission
07-20 08:30:20.014 23735-23775/anticlimacticteleservices.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-20 08:30:20.049 23735-23775/anticlimacticteleservices.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-20 08:30:20.050 23735-23775/anticlimacticteleservices.myapplication W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-20 08:30:20.096 23735-23775/anticlimacticteleservices.myapplication D/EGL_emulation: eglCreateContext: 0xaaa757e0: maj 2 min 0 rcv 2
07-20 08:30:20.099 23735-23775/anticlimacticteleservices.myapplication D/EGL_emulation: eglMakeCurrent: 0xaaa757e0: ver 2 0 (tinfo 0xac396210)
07-20 08:30:20.133 23735-23775/anticlimacticteleservices.myapplication D/EGL_emulation: eglMakeCurrent: 0xaaa757e0: ver 2 0 (tinfo 0xac396210)
07-20 08:30:20.181 23735-23735/anticlimacticteleservices.myapplication I/System.out: You denied write external storage permission.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context thisActivity = this;
try{
int writeExternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(writeExternalStoragePermission!= PackageManager.PERMISSION_GRANTED){
System.out.println("need to ask for permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}else {
System.out.println("it actually has permission now");
}
}catch (Exception ex) {
System.out.println("failed to get permissions with "+ex.getMessage());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == PERMISSION_REQUEST_CODE) {
int grantResultsLength = grantResults.length;
if(grantResultsLength > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED) {
System.out.println("You did it finally");
}else {
System.out.println("You denied write external storage permission.");
}
}
}
}
I expect a dialog to pop up allowing me to grant the neccesary permission to open a file in the download folder.
Your manifest has:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Your Java code does not refer to READ_EXTERNAL_STORAGE. It refers to WRITE_EXTERNAL_STORAGE. Those need to match.
To fix this:
Decide whether you need to write or not
If the answer to #1 is "yes, I need to write", switch your manifest to refer to WRITE_EXTERNAL_STORAGE
If the answer to #1 is "no, reading is fundamental", switch your Java code to refer to READ_EXTERNAL_STORAGE
FWIW, this sample app from this book demonstrates the use of WRITE_EXTERNAL_STORAGE.
After I install the android_alarm_manager on my project I got this error..
I/AlarmService(24713): Starting AlarmService...
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): Failed to handle method call
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.app.Activity.getExternalFilesDir(java.lang.String)' on a null object reference
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.plugins.imagepicker.ImagePickerPlugin.registerWith(ImagePickerPlugin.java:27)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:29)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at com.example.myapp.Application.registerWith(Application.java:18)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.plugins.androidalarmmanager.AlarmService.startAlarmService(AlarmService.java:65)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.plugins.androidalarmmanager.AndroidAlarmManagerPlugin.startService(AndroidAlarmManagerPlugin.java:75)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.plugins.androidalarmmanager.AndroidAlarmManagerPlugin.onMethodCall(AndroidAlarmManagerPlugin.java:52)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:191)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at io.flutter.view.FlutterNativeView.handlePlatformMessage(FlutterNativeView.java:163)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at android.os.MessageQueue.next(MessageQueue.java:143)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at android.os.Looper.loop(Looper.java:122)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at android.app.ActivityThread.main(ActivityThread.java:5253)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at java.lang.reflect.Method.invoke(Method.java:372)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
E/MethodChannel#plugins.flutter.io/android_alarm_manager(24713): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:708) 4.8s
🔥 To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
An Observatory debugger and profiler on Mi 4i is available at: http://127.0.0.1:3860/
For a more detailed help message, press "h". To detach, press "d"; to quit, press "q".
E/flutter (24713): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter (24713): PlatformException(error, Attempt to invoke virtual method 'java.io.File android.app.Activity.getExternalFilesDir(java.lang.String)' on a null object reference, null)
E/flutter (24713): #0 JSONMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:149:7)
E/flutter (24713): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:279:18)
E/flutter (24713): <asynchronous suspension>
E/flutter (24713): #2 AndroidAlarmManager.initialize (package:android_alarm_manager/android_alarm_manager.dart:70:10)
E/flutter (24713): <asynchronous suspension>
This is my pubspec.yaml
dependencies:
dio: "^1.0.1"
flutter:
sdk: flutter
local_auth: "^0.2.0"
shared_preferences: "^0.4.0"
http: "^0.11.3+16"
path_provider: ^0.4.1
image_picker: "^0.4.10"
multi_image_picker: "1.0.51"
datetime_picker_formfield: ^0.1.3
pull_to_refresh: ^1.1.5
connectivity: ^0.3.1
sqflite : any
location: ^1.4.1
android_alarm_manager: ^0.2.1
geolocator: '^1.7.0'
My main.dart
void main() async {
final int msgId = 0;
runApp(new LoginApp());
await AndroidAlarmManager.initialize();
await AndroidAlarmManager.periodic(
const Duration(seconds: 5), msgId, autoResendReports);
}
void autoResendReports() {
print("TEST");
final DateTime now = new DateTime.now();
final int isolateId = Isolate.current.hashCode;
print(
"[$now] Hello, world! isolate=$isolateId function='$autoResendReports'");
}
class LoginApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: '',
theme: new ThemeData(
primarySwatch: Colors.green,
),
routes: routes,
);
}
}
My AndroidManifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name=".Application"
android:label="MyApp"
android:icon="#mipmap/ic_launcher2">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in #style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service
android:name="io.flutter.plugins.androidalarmmanager.AlarmService"
android:exported="false"/>
</application>
</manifest>
I still can't make the background service for flutter work. Please help.
I got stuck in similar issue for a while, so I tried to work around using the java file. So, basically what I am doing is that I have created the background logic I want using java in the android side, which is easy to do. Then I talk with that side from flutter using MethodChannel. My app is simply need to run an alarm when the app timer finish counting even if in background. I still have some issues in variable passing to the service in android side, which is minor I think, but in general the background thing worked fine for me.