简体   繁体   中英

FirebaseMessagingService is not getting called in AsyncTask's doInBackground

I have push Notification and I want to update realm objects when the phone gets a notification but when I try launch this:

RealmModelActiveUser actUser= realm.where(RealmModelActiveUser.class).equalTo("id",1).findFirst();
                int myid= actUser.getUser().getUser_id();
                new ServerBackgroundDownloadConversations(getApplicationContext()) {
                    @Override
                    protected void onPostExecute(String result) {
                        super.onPostExecute(result);

                        if (!result.equals("Error")) {
                            Log.i("Conversation", "UPDATED");
                        }
                    }
                }.execute(myid);

The program jumps into the constructor ServerBackgroundDownloadConversations(getApplicationContext()) but doesn't call doInBackground and I don't know why.

My AsyncTask:

public class ServerBackgroundCreateConversation extends AsyncTask<RealmModelConversations,Void,String> {
    Context context;

    Handler handler;
    String out= "";
    @SuppressLint("HandlerLeak")
    public ServerBackgroundCreateConversation(Context context) {
        this.context = context;

        handler =  new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Bundle bundle= msg.getData();
                if (bundle!=null){
                    out = (String) bundle.get("response");
                } else {
                    out= "Error";
                }
            }

        };
    }


    @Override
    protected String doInBackground(RealmModelConversations... params) {
        RealmModelConversations newConv = params[0];
            UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();
            uploadTask.doFileUpload(newConv.getWork(newConv.getIntWork()), newConv, handler);


            while (out.equals("")){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        return out;
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(String result) {

        if (!result.equals("]") || !result.equals("")){
            /// prihlási nového user aj do active (login/register)
            CreateNewConversation(result);
        } else {
            result="Error";
        }

    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }


    private void CreateNewConversation(String result){
        Realm realm= Realm.getDefaultInstance();
        try {
            Gson gson = new Gson();
            Type typeConv = new TypeToken<JsonSablonaConversations>() {
            }.getType();

            JSONObject pom;
            JSONArray parentArray = new JSONArray(result);
            JSONObject finalObject = parentArray.getJSONObject(0);

            JsonSablonaConversations conversation = gson.fromJson(finalObject.toString(), typeConv);
            final RealmModelConversations NewUserConv = new RealmModelConversations();
            NewUserConv.setId_dialog(conversation.getId_dialog());
            NewUserConv.setDate(conversation.getDate());
            NewUserConv.setKey(conversation.getKey());
            NewUserConv.setId_user(conversation.getId_user());
            NewUserConv.setId_user2(conversation.getId_user2());
            NewUserConv.setMeno(conversation.getMeno());
            NewUserConv.setMeno2(conversation.getMeno2());
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    try {
                        realm.copyToRealmOrUpdate(NewUserConv);
                    } catch (Exception e) {
                        int pom=4;
                    }
                    RealmResults<RealmModelConversations> ru= realm.where(RealmModelConversations.class).findAll();
                }
            });
        }

        catch (Exception e) {
            int ppp=4;
            ppp++;
        }finally {
            realm.close();
        }
    }
}

I try calling this ↑ from an external thread which is called from a Service, but my AsyncTask has handler and handler needs to be in runOnUIthread and in Thread. I can't get Activity because the thread is called from a Service which doesn't have access to Activity.

I solved my problem with this code

    public String postData(int myUserId) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.gallopshop.eu/OFY/getConversations.php");
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(myUserId)));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        String responseStr = EntityUtils.toString(response.getEntity());
        return responseStr;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    return null;
}

I will try to put this method & after this method into simply thread, But maybe it's not needed because it's in a service.

Question - Do I put this into Thread or do you think it'll affect the performance of the app?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM