Android activity runs twice

I was running my app on a Nexus 7 2013 and in the logcat I noticed some logs are running twice. After writing several magazines, I came to the conclusion that each action is performed twice on the tablet. It is strange to think that on a phone (LG G3 or Samsung galaxy s4 mini) magazines are printed only once.

After some research, I tried to add android:launchMode="singleTop"

either singleTask

or singleInstance

, but none worked. Also I have some intentions in flag actions: intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

and 2 AsyncTasks

.

Is there a way that causes problems or asynthesis?

manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.marian.digimusicstream" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <!--
     To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user. This disconnect
     option is required to comply with the Google+ Sign-In developer policies
    -->
    <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- To retrieve the account name (email) as part of sign-in: -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- To auto-complete the email text field in the login form with the user emails -->
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme">
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Light.NoTitleBar"
            android:windowSoftInputMode="stateHidden"
            android:launchMode="singleTop">

            <!-- <intent-filter> -->
            <!-- <action android:name="android.intent.action.MAIN" /> -->
            <!-- <category android:name="android.intent.category.LAUNCHER" /> -->
            <!-- </intent-filter> -->
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name=".musicPlayer"
            android:label="@string/title_activity_music_player">

            <!-- android:theme="@android:style/Theme.DeviceDefault.Light.DarkActionBar" -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".PlayerService" />
        <service android:name=".audioService" />

        <receiver android:name=".PlayPauseReceiver" />
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
        <receiver android:name=".musicPlayer$MusicNoisyReceiver" >
            <intent-filter>
                <action android:name="android.media.AUDIO_BECOMING_NOISY" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".singleMusicScreen"
            android:label="@string/title_activity_single_music_screen" >
        </activity>
    </application>

</manifest>

      

Activity:

public class musicPlayer extends DrawerActivity {

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

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
        pullToRefresh = (PullRefreshLayout) findViewById(R.id.pullToReresh);
        musicListLayout = new RelativeLayout(getApplicationContext());

        progressBar = new ProgressBar(getApplicationContext());

        pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = pref.edit();

        getUser = pref.getString("sharedUser", "");
        getPassword = pref.getString("sharedPass", "");

        new doLogin().execute();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_music_player, menu);
        return true;
    }

    @Override
    public void onBackPressed() {
        // Do Here what ever you want do on back press;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public boolean isFirstItemCompletelyVisible() {
        return mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0;
    }

    @Override
    public void onResume() {
        super.onResume();
        musicList.post(new Runnable() {
            @Override
            public void run() {
                pullToRefresh.setEnabled(isFirstItemCompletelyVisible());
            }
        });
    }

    private class doLogin extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {

            Intent myIntent = getIntent();
            boolean button = myIntent.getBooleanExtra("LoginButton", false);

            if (!pref.getBoolean("isCheckBoxChecked", false) && !button) {
                Intent intent = new Intent(musicPlayer.this, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getApplicationContext().startActivity(intent);
                finish();
                cancel(true);
            }

            if (button) {
                getUser = myIntent.getStringExtra("userLogin");
                getPassword = myIntent.getStringExtra("passLogin");
            }

            Log.i("TEST", "User: " + getUser + " pass: " + getPassword);
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                Log.i("TEST", "Init");

                api = DefaultClientFactory.create(host, getUser, getPassword);
                Log.i("TEST", "" + api.getUserInfo());

                return true;
            } catch (StorageApiException e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if (!result) {
                Intent intent = new Intent(musicPlayer.this, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getApplicationContext().startActivity(intent);
                Toast.makeText(getApplicationContext(), "Invalid E-mail or Password !", Toast.LENGTH_SHORT).show();
            } else {
//                new backgroundTask().execute();
            }

        }
    }
}

      

+3


source to share


1 answer


activity trigger modes must be used carefully.

Android: launchMode = "SingleTop"

If an activity instance is present on top of the task stack, no new instance will be created and the system will route your intent information via onNewIntent (). If it is missing from the top, a new instance will be created. Multiple instances can be created and each instance can belong to a different task. ( Nice posting in activity launch mode )



  • Why are you checking the common prefix in onPreExecute () and then canceling it? The best way would be to execute the asynctask after checking it out.

  • cancel (true) does not guarantee that it will stop the async task as soon as it is called. A better way would be to add the isCancelled () check to doInBackground (), if canceling the returned result as needed. This will help complete the asynthesis as quickly as possible without completing the task written there.

  • In the manifest, you can add android: conifgChanges to better convey the orientation.

    android: configChanges = ["mcc", "mnc", "locale", "" touchscreen "," keyboard "," keyboard "," Navigation "," ScreenLayout "," fontScale "," uiMode "," orientation " , "screenSize", "SmallestScreenSize"]

Hope this helps!

0


source







All Articles