在Activity中使用finish()方法

时间:2014-09-16 13:38:19

标签: android android-activity android-service activity-finish

我有一个应用程序,其中包含带有文本框和按钮的活动,以及使用此用户在文本框中输入的名称的服务。一旦我输入名称并启动服务(在按钮上单击),我调用finish()来销毁Activity,如下面的代码所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_start);
    Log.e("onCreate", "Activity");

    final Button button = (Button) findViewById(R.id.startServiceBTN);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            EditText mEdit = (EditText) findViewById(R.id.nameTB);
            if (!hit) {
                hit = true;
                if (mEdit.getText().toString().trim().length() > 0) {
                    Intent intent = new Intent(StartActivity.this, BLEService.class);
                    intent.putExtra("Name", mEdit.getText().toString());
                    startService(intent);
                    StartActivity.this.finish();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Please Enter a Valid Name", Toast.LENGTH_LONG)
                            .show();
                }
            }

        }
    });
} 

我面临的问题是,虽然我称之为finish(),但我可以看到最近打开的应用程序图标托盘中的应用程序活动(最右边的软按钮),它位于Nexus 5的后退和主页按钮旁边。

在最近打开的应用程序托盘中单击应用程序时,我将使用空文本框获取应用程序。所以我在setOnClickListener按钮点击事件之前用一个检查修改了上面的代码,以确保在返回Activity时,我使用下面的代码片段用用户输入的文本预填充文本框。

if (hit) {
        EditText mEdit = (EditText) findViewById(R.id.nameTB);
        mEdit.setText(BLEService.NameFromActivity);
        finish();
    }

虽然上面的代码段有助于文本框不具有空值,但应用活动在“最近的应用程序托盘”中再次可用。

这是我的问题。如果我在最近的应用程序托盘中滑动关闭/滑动应用程序以完全清除它,我开始在服务日志中将Name作为Name的值而不是用户输入的Name。

2 个答案:

答案 0 :(得分:1)

您只需在清单文件的activity标记中添加以下行

即可

android:excludeFromRecents="true"

将其设置true会将此Activity排除在最近的托盘中。见下文,

<activity
            android:name="com.example.MainActivity"
            android:excludeFromRecents="true"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

参考 http://developer.android.com/guide/topics/manifest/activity-element.html

答案 1 :(得分:1)

如果您想保留用户输入的文字,可以使用Shared Preferences进行保存。

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("PREFERENCE_NAME", mEdit.getText().toString());
editor.commit();

同样在您的onCreate中,您可以获取该偏好。

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultName = "John Doe";
String name = sharedPref.getString("PREFERENCE_NAME", defaultName);
mEdit.setText(name);