简体   繁体   中英

onStop , onResume , Onpause function not running

I want to update the status of user he/she uses application.

In case the app is in foreground then the status must be online. Else if the app is running in the background then the status must be offline. I am using a AsyncTask to compute the background tasks. When I use the onStop , onResume and onPause methods, the background activity is hanging the UI thread.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.setTitle("Welcome ");
        toolbar = (Toolbar) findViewById(R.id.signoutToolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new CustomAdapter(getSupportFragmentManager(), getApplicationContext()));


        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);


        tabLayout.getTabAt(0).setIcon(R.drawable.common_full_open_on_phone);

        tabLayout.getTabAt(1).setIcon(R.drawable.messenger_bubble_large_white);

        tabLayout.getTabAt(2).setIcon(R.drawable.messenger_bubble_large_white);


        mAuth = FirebaseAuth.getInstance();

        mlisterner = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {


                if (firebaseAuth.getCurrentUser() == null) {
                    Intent intent = new Intent(MainActivity.this, GetStarted.class);
                    //   intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //check.close();
                    // TempCdb.close();

                    finish();
                    startActivity(intent);

                } else {
                    Firebase.setAndroidContext(getApplicationContext());
                    currentuser = FirebaseAuth.getInstance().getCurrentUser();

                    email_Current = currentuser.getEmail();
                    email_Current = email_Current.replace(".", "@");
                    //Toast.makeText(this, ""+email_Current, Toast.LENGTH_SHORT).show();
                    ref = new Firebase("https://zumi-60a8f.firebaseio.com/Users/");


                    ref.child(email_Current).child("AppStatus").setValue("Online");

                    // startService(new Intent(getBaseContext(),BGserviceForCurrentUser.class));

                    TempCdb = getApplicationContext().openOrCreateDatabase("zumi1.db", Context.MODE_PRIVATE, null);
                    TempCdb.execSQL(TABLE_CREATE);

                    if (mAuth.getCurrentUser() != null) {
                        Cursor check1 = TempCdb.rawQuery("select * from current_Luser", null);
                        if (check1.getCount() == 0) {
                            // Toast.makeText(this, "This is the First Time", Toast.LENGTH_SHORT).show();
                            new BGSERIVCE().execute();
                            check1.close();

                        } else {
                            Toast.makeText(getApplicationContext(), "This is the NOT First Time", Toast.LENGTH_SHORT).show();
                            check1.close();
                        }
                        check1.close();
                        TempCdb.close();
                    }

                }

            }
        };

        db = FirebaseDatabase.getInstance().getReference().child("Users");
        db.keepSynced(true);


    }

    String url;

    public class BGSERIVCE extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            played = 1;
            FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();

            Cdb = getApplicationContext().openOrCreateDatabase("zumi1.db", Context.MODE_PRIVATE, null);
            Cdb.execSQL(TABLE_CREATE);

            Firebase.setAndroidContext(getApplicationContext());
//            Toast.makeText(getApplicationContext(), "background Running....", Toast.LENGTH_SHORT).show();
            String email_Current = currentuser.getEmail().replace(".", "@");
            ref = new Firebase("https://zumi-60a8f.firebaseio.com/Users/");
            values = new ContentValues();
            if (Cdb.isOpen()) {
                ref.child(email_Current).addValueEventListener(new com.firebase.client.ValueEventListener() {
                    @Override
                    public void onDataChange(com.firebase.client.DataSnapshot snapshot) {
                        for (com.firebase.client.DataSnapshot postSnapshot : snapshot.getChildren()) {

                            //Adding it to a string

                            Cdb.execSQL("delete from current_Luser");

                            url = snapshot.child("image").getValue().toString();
                            String Dname = snapshot.child("Dname").getValue().toString(); // NAME

                            String email = snapshot.child("email_phone").getValue().toString().replace("@zumi.com", ""); // PHONE@EMAIL.co
                            String status_E = snapshot.child("status").getValue().toString();

                            //   private  static  final String TABLE_CREATE="create table if not exists current_Luser (email_phone TEXT,  status TEXT, Dname TEXT,image blob,snyc TEXT)";

                            values.put("email_phone", "\"" + email + "\"");
                            values.put("status", "\"" + status_E + "\"");
                            values.put("Dname", "\"" + Dname + "\"");
                            values.put("snyc", "\"" + "Yes" + "\"");

                        }
                        //Toast.makeText(MainActivity.this, ""+values.toString(), Toast.LENGTH_SHORT).show();
                        //  new inputstream().execute(url);

                        Cdb.execSQL("insert into current_Luser(email_phone,status,Dname,snyc)  values (" + values.get("email_phone") + "," + values.get("status") + "," + values.get("Dname") + "," + values.get("snyc") + ")");
                        Toast.makeText(MainActivity.this, "Complete BG Process", Toast.LENGTH_SHORT).show();


                    }

                    @Override
                    public void onCancelled(FirebaseError firebaseError) {
                        //System.out.println("The read failed: " + firebaseError.getMessage());
                    }
                });
            }

//            Cdb.close();
            return null;
        }
    } // BG SERVICE__UPDATES CURRENT SQLITE


    /*  @Override
      protected void onPause() {
          Firebase.setAndroidContext(getApplicationContext());
          currentuser = FirebaseAuth.getInstance().getCurrentUser();
          if(currentuser==null)
          {

          }
          else {
              email_Current = currentuser.getEmail();
              email_Current = email_Current.replace(".", "@");
              //Toast.makeText(this, ""+email_Current, Toast.LENGTH_SHORT).show();
              ref = new Firebase("https://zumi-60a8f.firebaseio.com/Users/");

              ref.child(email_Current).child("AppStatus").setValue("Offline");
          }
          super.onPause();

      }

      @Override
      protected void onResume() {

          Firebase.setAndroidContext(getApplicationContext());
          currentuser = FirebaseAuth.getInstance().getCurrentUser();
          if(currentuser==null)
          {

          }
          else {
              email_Current = currentuser.getEmail();
              email_Current = email_Current.replace(".", "@");
              //Toast.makeText(this, ""+email_Current, Toast.LENGTH_SHORT).show();
              ref = new Firebase("https://zumi-60a8f.firebaseio.com/Users/");

              ref.child(email_Current).child("AppStatus").setValue("Online");
          }
          super.onResume();
      }
  */



    @Override
    protected void onStart() {
        super.onStart();
        //   checkuserexist();
        // new BGSERIVCE().execute();

        mAuth.addAuthStateListener(mlisterner);

    }

The methods is hanging your UI, you can use them by Thread :

Ex.

new Thread(new Runnable(){

//Your method or code

}).start();

Your onPause, onResume, onStop... these methods should be in your activity class, not in your asynctask.

if you look at the docs, activity has these methods you can override, https://developer.android.com/reference/android/app/Activity.html

Asynctask has no such methods, that's why it doesn't work. https://developer.android.com/reference/android/os/AsyncTask.html

Try it:

private void doOffline() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // TODO: offline
        }
    }, 1000); // delay 1 second
}

private void doOnline() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // TODO: online
        }
    }, 1000); // delay 1 second
}

@override
protected void onStart() {
    super.onStart();
    doOnline();
}

@override
protected void onResume() {
    super.onResume();
    doOnline();
}

@override
protected void onPause() {
    super.onPause();
    doOffline();
}

@override
protected void onStop() {
    super.onStop();
    doOffline();
}

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