#StackBounty: #javascript #java #android #firebase #firebase-cloud-messaging Firebase Cloud HTTP Message from Web

Bounty: 50

I have set up a webpage (home.html) that a user can sign into firebase using authentication. Once they authenticate, they are directed to a new page(test.html). Once they are here, I want to be able to send a notification or data message.

I am wondering if anyone can help me with the code to send a notification – any type of notification. I’ve been on this for 3 days and cannot send a notification from the web!! I can’t find any tutorials on this – only people using curls.

I have no idea how to handle the code below, which is supposed to be on how to send a notification to the devices subscribed to a topic. I am guessing that this is all JSON and needs to be put into a JSON object?

Please assume the Initialization is filled in, I removed all info – even though I think that information is supposed to be public.

enter image description here

Thanks for any info!

This is my service worker (so far): firebase-messaging.sw.js

  // Give the service worker access to Firebase Messaging.
  // Note that you can only use Firebase Messaging here, other Firebase libraries
  // are not available in the service worker.
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');  

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();
  messaging.setBackgroundMessageHandler(function(payload){
    const title = "Hello World";
    const options = {
      body: payload.data.status
    };
    return self.registration.showNotification(title, options);
  });

This is the app.js file that goes to the test.html page

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  // Retrieve Firebase Messaging object.
  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function() {
    console.log('Notification permission granted.');
    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
  })
  .catch(function(err) {
    console.log('Unable to get permission to notify.', err);
  })

  messaging.onMessage(function(payload){
    console.log('onMessage:', payload);
  });

And the barebones test.html file

<!DOCTYPE html>

<html>
    <head>
        https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js
        https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js
    </head>
    <body> 
        /scripts/app.js
    </body>
</html>


Get this bounty!!!

#StackBounty: #android #performance #android-fragments #exception-handling How to override handleUncaughtException without changing its…

Bounty: 50

I asked this question some time back on Stackoverflow, the answer worked for me, It overrides thehandleUncaughtException, I save the exception and throws the default Unfortunately app has stopped working, but when i integrated this in my app, I am facing an issue.

This is the answer i got.

private Thread.UncaughtExceptionHandler defaultExceptionHandler;

    public void registerCrash(){
        defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();

        Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler(){
            @Override
            public void uncaughtException (Thread thread, Throwable e){
                handleUncaughtException (thread, e);
                if(defaultExceptionHandler != null){
                    defaultExceptionHandler.uncaughtException(thread, e);
                }
            }
        });
    } 

What it does, first it goes to handleUncaughtException (thread, e); i save the crash log in this method, then it reads this line

 if(defaultExceptionHandler != null){
    defaultExceptionHandler.uncaughtException(thread, e);
}

here we throw uncaught exception again, so it goes to the first line again, and again saves the exception, and this goes in loop, and application becomes not responding.

What i want is to save crash log, and then show the default Unfortunate message to user.

EDIT

On Application launch it reads this;

defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();

When application crashes, it reads these lines

Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler(){
    @Override
    public void uncaughtException (Thread thread, Throwable e){

        handleUncaughtException (thread, e); //Custom Method 

        if(defaultExceptionHandler != null){
            defaultExceptionHandler.uncaughtException(thread, e);
        }
    }

So it first goes to handleUncaughtException() there i have provided custom implementation, then it goes to this;

if(defaultExceptionHandler != null){
  defaultExceptionHandler.uncaughtException(thread, e);
}

The defaultExceptionHandler is never null; So it goes in a loop in case of multiple crashes.

I have tried adding count there, but it was 0 each time.


Get this bounty!!!

#StackBounty: #android #image #picasso #android-image #image-loading Can Picasso queue for me?

Bounty: 200

Here’s a critical point I don’t know concerning the behavior of Picasso.

Imagine you are, say, showing a slide-show of ten items. Say, they are on-screen for ten seconds each.

The ideal behavior would be this: at the start of the slide show, I simply perform following:

picasso.get( url1 )
picasso.get( url2 )
picasso.get( url3 )
picasso.get( url4 )
picasso.get( url5 )
picasso.get( url6 )
picasso.get( url7 )
picasso.get( url8 )
picasso.get( url9 )
picasso.get( url10 )

And, in fact, Picasso would do those one at a time, in a queue.

What is the behavior of Picasso, if I tell it to pre-warm 10 urls all at once?

Is it possible to have Picasso do things only one at a time, in order – is there such an option?

(Other questions arising are, can you cancel the queue, or …?)

Thanks, Picasso experts!


Get this bounty!!!

#StackBounty: #android #android-asynctask #onclicklistener #api-ai API.AI: How to stop AsyncTask on click of the AIButton?

Bounty: 50

I’m using AIButton in my app and I have a AsyncTask which gets executed after AIButton is clicked and receives some command and AsyncTask sometimes takes too long to execute.

Here’s my code:

final AIConfiguration config = new AIConfiguration("xxx",
                AIConfiguration.SupportedLanguages.English,
                AIConfiguration.RecognitionEngine.System);

listenButton = (AIButton) findViewById(R.id.micButton);

config.setRecognizerStartSound(getResources().openRawResourceFd(R.raw.test_start));
config.setRecognizerStopSound(getResources().openRawResourceFd(R.raw.test_stop));
config.setRecognizerCancelSound(getResources().openRawResourceFd(R.raw.test_cancel));

listenButton.initialize(config);
listenButton.setResultsListener(this);

So, what I want is to stop all running AsyncTask when the AIButton is clicked so that previous tasks are stopped in order to execute new task. How to do this?

The problem here is that you can’t do something like: listenButton.onClickListener() here.


Get this bounty!!!

#StackBounty: #java #android #annotations #dependencies #gson Use Gson in my generated classes (annotation processor)

Bounty: 50

I’m developing a library to generate classes using annotations and processors. The generated classes should use Gson library from google.

My question is : Where should I add the Gson dependency ? I’m currently adding it into the processor build.gradle but when the classes are generated, Gson is not found and Android Studio is suggesting to add it to the app module.

Also, I pushed a first version of the library to bintray before I noticed this problem (because I was already using Gson in my app module, so the error didn’t show up). When I included my library to another project, used the annotation and build the project, I got this message :

Error:Bad service configuration file, or exception thrown while
constructing Processor object: javax.annotation.processing.Processor:
Provider me.aflak.filter_processor.FilterProcessor could not be
instantiated: java.lang.NoClassDefFoundError:
com/squareup/javapoet/TypeName

Is it related to the way I add my dependencies ? Obviously I’m missing something…

This is the processor build.gradle :

apply plugin: 'java-library'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':filter-annotation')

    implementation 'com.squareup:javapoet:1.9.0'
    implementation 'com.google.code.gson:gson:2.8.1'
    implementation 'com.google.auto.service:auto-service:1.0-rc3'
}

// bintray stuff here...

This is my app.module dependency :

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation project(':filter-annotation')
    annotationProcessor project(':filter-processor')
}

Any help would be greatly appreciated, thanks!


Get this bounty!!!

#StackBounty: #android #google-play-services #android-location #fusedlocationproviderapi #google-location-services Location Updates usi…

Bounty: 50

I want to get location updates on a “background service” using latest fused location provider client.I don’t want to use the location listeners and Google API Client that all are using.
I also need to use location settings Api provided by google play services to check whether location setting are disable or enable on that “background service”.Please help.


Get this bounty!!!

#StackBounty: #android #bitmap #android-contacts Is this how to correctly set a photo to a contact on the address-book?

Bounty: 200

Background

Suppose I’ve found a contact by using some query on the address book. Found it by performing a query to get contact info from a specific account (like of WhatsApp), as I’ve written here.

Now I have an image that I wish to use it to update the contact’s photo.

The problem

I have created code based on things I’ve found here on StackOverflow, that update a contact photo.

Thing is, some users claim it doesn’t do anything. I’m not sure what causes it. Maybe bad way to access the contact (id/lookup-key?). Maybe I need to get an extra address-book field. Maybe the query itself is wrong…

I’m having problems figuring out the reason for this issue, because I can’t reproduce it and so does most of the users.

The code

Here’s what I did:

        final ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        final String lookupKey=...;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            final byte[] photoByteArray = new byte[(int) file.length()];
            fileInputStream.read(photoByteArray);
            fileInputStream.close();
            final Builder builder = ContentProviderOperation.newUpdate(Data.CONTENT_URI);
            builder.withSelection(Data.LOOKUP_KEY + "=?" + " AND " + Data.MIMETYPE + "=?", new String[]{lookupKey, Photo.CONTENT_ITEM_TYPE});
            builder.withValue(Photo.PHOTO, photoByteArray);
            ops.add(builder.build());
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops )

The question

Is there anything wrong with the code?

Should I update the contact differently?

How come some users fail to update? Isn’t the lookup-key enough? Can it update the wrong data?

I’ve read somewhere that I might need to use RAW-contact-ids, but couldn’t find what to do exactly. Query and then update/insert?

Someone has suggested that developers should consider using an account of their app to save photos, instead of updating, as it might cause issues. Is it true?


Get this bounty!!!

#StackBounty: #android #sms #smsmanager Sending 50+ messages causing issues lead to generic failure

Bounty: 50

I am developing an application in which i need to send 100+ of messages. After going through few threads i came to know there is limitation on sending messages like 100 messages can be send in an hour. To do so i divide my recipient list into chunks and place delay of 5 seconds between each chunk and 3 seconds delay in every message. The delay between chunks increase after every chunk and when it gets to 100 seconds it will reset to 5 seconds. After that it worked OK for 50 messages but when i raise recipient list it causing issues some messages didn’t go at first place and shown as error messages in native.

Is there any standard way to achieve this i may need to send 100+ messages , how can i send multiple messages without any failure at once. If i need to place delay what should be the appropriate delay between chunks or messages.

Thanks in advance.

private final int MAX_SMS_IN_ONE_TIME = 10;
private final int DELAY_BETWEEN_CHUNKS = 5000;

public void sendMessage(arguments){ 
    // Send long messages in chunk of 20 messages and put gap of increasing 5 seconds till 50 seconds and then reset.

    final Iterator iterator = messageChunks.iterator();
    new Thread(new Runnable() {
        @Override
        public void run(){

        int interval =1;
        while (iterator.hasNext()) {

            for (final Contact contact :
                (List<Contact>) iterator.next()) {

                sendSMS(body, contact.getmMobileNumbers().get(0));

                App.trackEvent("Message", "Sent", "Messages from our sms app");
            }
        }
        try {
            Log.i("chunk", "chunk # " + interval + " delay is " + DELAY_BETWEEN_CHUNKS);
            Thread.sleep(DELAY_BETWEEN_CHUNKS * interval);
            interval++;
            if (interval == 10) {
                interval = 1;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        }
        }
    }).start();
}

public void sendSMS(final String message, final String phoneNo) {
    try {
        String SENT = "com.ebryx.smscustommessagegeneration"+""+System.currentTimeMillis()+""+((int)this.getmMessageId());
        Intent intentMessageASendStatus = new Intent(SENT);

        final PendingIntent pi = PendingIntent.getBroadcast(App.getContext(),  ((int)this.getmMessageId()),
                intentMessageASendStatus, PendingIntent.FLAG_CANCEL_CURRENT);
        final ArrayList<PendingIntent> sentPI = new ArrayList<PendingIntent>(){{add(pi);}};

        App.getContext().registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {


                switch (getResultCode())
                {
                    case Activity.RESULT_OK:

                        Log.i("tag","sent successfully ");
            break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

                        Log.i("tag","Generic Failure");
                break;

                    case SmsManager.RESULT_ERROR_NO_SERVICE:

                        Log.i("tag","No service failure");
            break;

        case SmsManager.RESULT_ERROR_NULL_PDU:
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:

                        Log.i("tag","Airplane mode failure");
                        break;
                }
            }
        }, new IntentFilter(SENT));

        final SmsManager smsManager = SmsManager.getDefault();
        final ArrayList<String> parts = smsManager.divideMessage(message);

        new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    smsManager.sendMultipartTextMessage(phoneNo, null, parts, sentPI, null);

                }}, 3000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


Get this bounty!!!

#StackBounty: #android #ios #react-native #react-native-android #react-native-ios How to schedule background job at specific time in re…

Bounty: 50

I want to execute some Task T at specific time in a day in background in react native. I see that it is possible in android as of now using Headless JS. I found that this library implemented this https://github.com/vikeri/react-native-background-job and allows you to execute stuff in background.

This is not completely what I am looking, it doesn’t allows you to schedule a task T at specific time. Does anyone know any work around for this ?

I have checked this thread Execute code at specific time in react native where I didn’t find a solution of my issue.


Get this bounty!!!

#StackBounty: #android #google-maps #android-intent #navigation Start new navigation without exiting from previous navigation in Google…

Bounty: 50

I’m starting Google Map from my application to Navigate the user to some location.

Here is my code.

Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                Uri.parse("google.navigation:q=" + rideDetailsModel.getEndLatitude() + "," + rideDetailsModel.getEndLongtitude()));
        startActivity(intent);

I’m using Chat Head like Uber driver app to take back to my application from Google Map. That’s working fine. The problem is, While I’m invoking the same code above, Google Map asks me to exit from the previous navigation. Because previous navigation is not cleared.

How to force Google Map to create new navigation without asking to close the previous one.

Two methods can solve my problem.

Method 1

If I can close Google map application from my application, my problem solved. But I searched a lot, the non-rooted phone can’t kill other applications.

Method 2

Clear the previous navigation and create new navigation. So Google Map won’t ask the user to exit from the previous navigation before start the new navigation.


Get this bounty!!!