Reputation: 807
In my app I have to two activities and one background service. The first activity (Activity A) which is the main activity is used to start/stop the service. The service is used to start an activity (Activity B) when it is necessary to launch it (the service can launch activity B even if activity A is not running).
finish()
is called from the Activity B, this is the Activity A that is displayed on the screen and I wish to show the last activity launched before Activity B.My question is how to launch activity B (as a standalone activity) from the service without pass through the activity A (which is the main activity)?
This is the code I used to launch Activity B from service :
Intent intent = new Intent(this, ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
This is my manifest:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- Activity A -->
<activity
android:name="ActivityA"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Activity B -->
<activity
android:name="ActivityB"
android:excludeFromRecents="true"
android:exported="true"
android:immersive="true"
android:launchMode="singleTask" />
<!-- Service -->
<service
android:name="Service"
android:enabled="true"
android:exported="true" >
</service>
</application>
Thanks in advance
Upvotes: 1
Views: 1539
Reputation: 213
Just Place this code in your Activity A
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Service","Message");
ActivityA.this.finish();
}
};
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("finishA"));
}
// Place this code in your Activity B onCreate() method
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("finishA");
LocalBroadcastManager.getInstance(ActivityB.this).sendBroadcast(intent);
}
Upvotes: 2