Force Activity to have Single Instances

To force a Activity to have a Single Instances, you can include android:launchMode="singleTask" under <activity> in AndroidManifest.xml.

android:launchMode determine how the activity should be launched. With android:launchMode="singleTask", The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.

Example:

force Single Instances for Activity
force Single Instances for Activity


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

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidlaunchmode.MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>


package com.example.androidlaunchmode;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

TextView prompt;
int counter;

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

prompt = new TextView(this);
setContentView(prompt);

counter = 0;
prompt.setText("number of onNewIntent() called = " + counter);
}

@Override
protected void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
super.onNewIntent(intent);
Toast.makeText(getApplicationContext(),
"onNewIntent()",
Toast.LENGTH_LONG).show();
counter++;
prompt.setText("number of onNewIntent() called = " + counter);
}

}


0 Response to "Force Activity to have Single Instances"

Posting Komentar