Android活动只有在主要活动时才能正常运行?

时间:2012-12-13 09:41:29

标签: java android android-intent android-activity

当我将一个活动设置为启动器时,它工作正常,但是当我从另一个活动启动此活动时,它将以显示方式打开,一些功能正常工作,而其中一些功能不起作用?!对我来说很困惑。

基本上,如果我打开它,因为Launcher数据可以通过串行发送和接收。但是,如果我从另一个活动中打开它,而绝对的垃圾邮件会通过串行发送而没有任何东西回来。但是有些部分可以工作,例如建立串行连接?!

在启动活动中,这是打开我想要的活动的代码:

public void openTextTerminal(View view)
{
    Intent intent = new Intent(this, TextBoxActivity.class);
    startActivity(intent);      
}

这是清单: (我认为我甚至不需要意图过滤器?!)

<activity
        android:name="com.example.TextBoxActivity"
        android:label="@string/title_activity_text_box" >

        <intent-filter>
            <action android:name="android.intent.action.TextBoxActivity" />

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

</activity>

Full Manifest:

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

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

<uses-feature
    android:name="android.hardware.touchscreen"
    android:required="false" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<permission
    android:name="com.example.permission.RUN_SCRIPT"
    android:description="@string/permdesc_run_script"
    android:label="@string/perm_run_script"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="dangerous" />
<permission
    android:name="com.example.permission.APPEND_TO_PATH"
    android:description="@string/permdesc_append_to_path"
    android:label="@string/perm_append_to_path"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="dangerous" />
<permission
    android:name="com.example.permission.PREPEND_TO_PATH"
    android:description="@string/permdesc_prepend_to_path"
    android:label="@string/perm_prepend_to_path"
    android:permissionGroup="android.permission-group.SYSTEM_TOOLS"
    android:protectionLevel="dangerous" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/application_terminal" >
    <activity
        android:name="com.example.Term"
        android:configChanges="keyboard|keyboardHidden|orientation"
        android:launchMode="singleTask"
        android:theme="@style/Theme"
        android:windowSoftInputMode="adjustResize|stateAlwaysVisible" >
        <intent-filter>
            <action android:name="android.intent.action.TERM" />

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

    <activity-alias
        android:name="com.example.TermInternal"
        android:exported="false"
        android:targetActivity="Term" >
        <intent-filter>
            <action android:name="com.example.private.OPEN_NEW_WINDOW" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.example.private.SWITCH_WINDOW" />

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

    <activity
        android:name="com.example.RemoteInterface"
        android:excludeFromRecents="true" >
        <intent-filter>
            <action android:name="com.example.OPEN_NEW_WINDOW" />

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

    <activity-alias
        android:name="com.example.RunScript"
        android:permission="com.example.permission.RUN_SCRIPT"
        android:targetActivity="RemoteInterface" >
        <intent-filter>
            <action android:name="com.example.RUN_SCRIPT" />

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

    <activity
        android:name="com.example.TermPreferences"
        android:label="@string/preferences" />
    <activity
        android:name="com.example.WindowList"
        android:label="@string/window_list" />

    <service android:name="com.example.TermService" />

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.TextBoxActivity"
        android:label="@string/title_activity_text_box" >

        <intent-filter>
            <action android:name="android.intent.action.TextBoxActivity" />

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

    </activity>
    <activity
        android:name="com.example.SerialTerminalActivity"
        android:label="@string/title_activity_serial_terminal"
        android:screenOrientation="landscape" >
    </activity>
</application>

</manifest>

我自己在程序中复制代码(即使用一个活动来启动第二个活动而不使用其他不相关的类)并且它工作正常。我只是复制和粘贴。我对所有文件做了一个差异,并且几乎没有什么不同,只是在我看到的清单中无关的东西。我将在明天完成整个清单(我花了整整一天时间调试才发现这个错误)并重写它或者其他东西。

我只是好奇它是如何看起来一切正常,但事实并非如此。我会想到,一旦我启动活动,无论我如何启动它,一切都完全相同(因为我什么也没有通过)。

可能传递错误的上下文,这里是完整的代码:

public class MainActivity extends Activity implements OnClickListener,       OnItemSelectedListener, AdapterConnectionListener, DataListener{


private Spinner mBaudSpinner;
private Spinner mDataSpinner;
private Spinner mParitySpinner;
private Spinner mStopSpinner;
private Spinner mDeviceSpinner;
private Button mConnect;
private ArrayList<String> mDeviceOutputs;
private ArrayList<USB2SerialAdapter> mDeviceAdapters;
private ArrayAdapter<CharSequence> mDeviceSpinnerAdapter;
private USB2SerialAdapter mSelectedAdapter;
private TextView mCurrentSettings;

private Button mUpdateSettings;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    mConnect = (Button)findViewById(R.id.deviceConnect);
    mConnect.setOnClickListener(this);
    mUpdateSettings = (Button)findViewById(R.id.updateSettings);
    mUpdateSettings.setOnClickListener(this);


    mBaudSpinner = (Spinner)findViewById(R.id.baudSpinner);
    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mBaudSpinner.setAdapter(adapter);
    String[] tempArray = SlickUSB2Serial.BAUD_RATES;
    for(int i=0;i<tempArray.length;i++) 
    {
        adapter.add(tempArray[i]);
    }
    mBaudSpinner.setSelection(SlickUSB2Serial.BaudRate.BAUD_9600.ordinal());

    mDataSpinner = (Spinner)findViewById(R.id.dataSpinner);
    adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mDataSpinner.setAdapter(adapter);
    tempArray = SlickUSB2Serial.DATA_BITS;
    for(int i=0;i<tempArray.length;i++)
    {
        adapter.add(tempArray[i]);

    }
    mDataSpinner.setSelection(SlickUSB2Serial.DataBits.DATA_8_BIT.ordinal());

    mParitySpinner = (Spinner)findViewById(R.id.paritySpinner);
    adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mParitySpinner.setAdapter(adapter);
    tempArray = SlickUSB2Serial.PARITY_OPTIONS;
    for(int i=0;i<tempArray.length;i++)
    {
        adapter.add(tempArray[i]);

    }
    mParitySpinner.setSelection(SlickUSB2Serial.ParityOption.PARITY_NONE.ordinal());

    mStopSpinner = (Spinner)findViewById(R.id.stopSpinner);
    adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mStopSpinner.setAdapter(adapter);
    tempArray = SlickUSB2Serial.STOP_BITS;
    for(int i=0;i<tempArray.length;i++)
    {
        adapter.add(tempArray[i]);

    }
    mStopSpinner.setSelection(SlickUSB2Serial.StopBits.STOP_1_BIT.ordinal());

    mDeviceAdapters = new ArrayList<USB2SerialAdapter>();
    mDeviceOutputs = new ArrayList<String>();

    mDeviceSpinner = (Spinner)findViewById(R.id.deviceSpinner);
    mDeviceSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
    mDeviceSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mDeviceSpinner.setAdapter(mDeviceSpinnerAdapter);
    mDeviceSpinner.setOnItemSelectedListener(this);

    mCurrentSettings = (TextView)findViewById(R.id.currentSettings);


    SlickUSB2Serial.initialize(this);



}

public void openTerminal(View view) {
    // Do something in response to button
    Intent intent = new Intent(this, Term.class);
    startActivity(intent);
}

public void openTextTerminal(View view) {
    // Do something in response to button
    Intent intent = new Intent(this, TextBoxActivity.class);
    startActivity(intent);

}

public void openSerialTerminal(View view) {
    // Do something in response to button
    Intent intent = new Intent(this, SerialTerminalActivity.class);
    startActivity(intent);

}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // TODO Auto-generated method stub
    changeSelectedAdapter(mDeviceAdapters.get(position));
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub
}

public void changeSelectedAdapter(USB2SerialAdapter adapter){
    Toast.makeText(this, "in changeselectedadapter", Toast.LENGTH_SHORT).show();
    //if(mSelectedAdapter!=null){
        //mDeviceOutputs.set(mDeviceSpinnerAdapter.getPosition(mSelectedAdapter.getDeviceId()+""),mReceiveBox.getText().toString());

    mSelectedAdapter = adapter;
    mBaudSpinner.setSelection(adapter.getBaudRate().ordinal());
    mDataSpinner.setSelection(adapter.getDataBit().ordinal());
    mParitySpinner.setSelection(adapter.getParityOption().ordinal());
    mStopSpinner.setSelection(adapter.getStopBit().ordinal());

    updateCurrentSettingsText();

    //mReceiveBox.setText(mDeviceOutputs.get(mDeviceSpinner.getSelectedItemPosition()));
    Toast.makeText(this, "Adapter switched toooo: "+adapter.getDeviceId()+"!", Toast.LENGTH_SHORT).show();
}


@Override
public void onClick(View v) {

    if(v==mConnect){
        SlickUSB2Serial.autoConnect(this);
        if(mSelectedAdapter==null){
            Toast.makeText(this, "no adapters detected", Toast.LENGTH_SHORT).show();
            return;
            //String data = mSendBox.getText().toString() + "\r\n";
        //  mSelectedAdapter.sendData(data.getBytes());
            //mSendBox.setText("");

            }

        Intent intent = new Intent(this, SerialTerminalActivity.class);
        startActivity(intent);
    }


    else if(v==mUpdateSettings){
        if(mSelectedAdapter==null){
            return;
        }

        mSelectedAdapter.setCommSettings(BaudRate.values()[mBaudSpinner.getSelectedItemPosition()],
                DataBits.values()[mDataSpinner.getSelectedItemPosition()],
                ParityOption.values()[mParitySpinner.getSelectedItemPosition()],
                StopBits.values()[mStopSpinner.getSelectedItemPosition()]);

        updateCurrentSettingsText();
        Toast.makeText(this, "Updated Settings", Toast.LENGTH_SHORT).show();

    }

}

@Override
public void onAdapterConnected(USB2SerialAdapter adapter) {
    adapter.setDataListener(this);
    mDeviceAdapters.add(adapter);
    mDeviceOutputs.add("");
    mDeviceSpinnerAdapter.add(""+adapter.getDeviceId());
    mDeviceSpinner.setSelection(mDeviceSpinnerAdapter.getCount()-1);

    Toast.makeText(this, "Adapter: "+adapter.getDeviceId()+" Connected!", Toast.LENGTH_SHORT).show();
    //Toast.makeText(this, "Baud: "+adapter.getBaudRate()+" Connected!", Toast.LENGTH_SHORT).show();
}

@Override
public void onAdapterConnectionError(int error, String msg) {
    // TODO Auto-generated method stub
    if(error==AdapterConnectionListener.ERROR_UNKNOWN_IDS){
        final AlertDialog dialog = new AlertDialog.Builder(this)
        .setIcon(0)
        .setTitle("Choose Adapter Type")
        .setItems(new String[]{"Prolific", "FTDI"}, new   DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int optionSelected){
                if(optionSelected==0)
                    {
                        SlickUSB2Serial.connectProlific(MainActivity.this); 
                    }
                else
                    {
                            SlickUSB2Serial.connectFTDI(MainActivity.this);     
                    }       
            }
        }).create();
        dialog.show();
        return;
    }
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}

private void updateCurrentSettingsText(){
    mCurrentSettings.setText("Current Settings Areeee:     "+mBaudSpinner.getSelectedItem().toString()
            +", "+mDataSpinner.getSelectedItem().toString()
            +", "+mParitySpinner.getSelectedItem().toString()
            +", "+mStopSpinner.getSelectedItem().toString());
    }

@Override
public void onDataReceived(int arg0, byte[] arg1) {
    // TODO Auto-generated method stub
    Toast.makeText(this, "IN ONDATARECIEVED OHOH", Toast.LENGTH_SHORT).show();
}


public void onDestroy() {
    SlickUSB2Serial.cleanup(this);
    super.onDestroy();
}

}

2 个答案:

答案 0 :(得分:1)

在这里您已经使用 this 作为上下文,首先您应该了解不同的上下文。

  • this指的是您当前的对象。在你的情况下,你必须在内部类或一些ClickEvent中实现intent,这就是它指向的内容。

  • Activity.this指向您当前所在活动的实例。

  • getApplicationContext()指的是应用程序的上下文。

现在,如果this上下文直接位于活动的oncreate()下,而不是任何其他类或某个按钮的onClick()事件,那么它与Activity的上下文相同

但是,当同一活动结束时,当活动的上下文消亡时,最好使用getApplicationContext()

答案 1 :(得分:0)

我在启动活动的onCreate()中找到了罪魁祸首,这是一个库调用。我所要做的就是将它从启动活动转移到被调用的活动。这将教会我盲目地遵循API指令。

所以我在错误的活动中遇到了 SlickUSB2Serial.initialize(this);

initialize(android.content.Context context) 
initialize must be called when your app first starts up (in onCreate).