How to bring action to the forefront (or create if it does not exist)?

I intercept sms messages with some information in them. Then in my SmsListener I create a notification to display in the status bar. Then, when the user clicks on the notification, I want

  • Bring MainActivity to the forefront (if such an activity has not yet been created, it must be created)
  • Send him data from sms
  • Make some ui changes based on this data in this MainActivity

My activity is defined as

    <activity
        android:name=".MainActivity"
        android:screenOrientation="sensor"
        android:label="@string/app_name"
        android:launchMode="singleTask"/>

Activity starts as

 Intent i = new Intent();
 i.setClass(context, MainActivity.class);
 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 context.startActivity(i);

Also in my work I have an overridden onNewActivity method

 @Override
 public void onNewIntent(Intent intent){
    super.onNewIntent(intent);

    // I have data from broadcast in intent variable passed to this activity
    processDataFromBroadcast(intent);
}

It works fine if MainActivity already exists, but if MainActivity does not exist, it starts, however onNewIntent was not called

processDataFromBroadcast onCreate: processDataFromBroadcast(getIntent()). . , MainActivity , , onCreate, onNewIntent, processDataFromBroadcast , , MainActivity , - , . .

+5
3

, , <activity>, android:launchMode. singleTask singleInstance.

, Intent, . , putExtra() getExtra() .

, , , , this Android .

+5

, , :

. onCreate() onNewIntent(). . onCreate() onNewIntet(), id , ! , , , .

, userdefaults.

, , setIntent(new Intent()) onNewIntent .

+1

, , .

:

Intent mIntent = new Intent(this, SplashActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // You need this if starting the activity from a service
mIntent.setAction(Intent.ACTION_MAIN);
mIntent.addCategory(Intent.CATEGORY_LAUNCHER);

Where SplashActivity is the name of the source application, which is the first screen of your application.

Hope this helps. :)

0
source

All Articles