簡體   English   中英

Android活動僅在主要活動下才能正常運行嗎?

[英]Android activity only works properly if it is the main activity?

當我將一個活動設置為啟動器時,它可以正常工作,但是當我從另一個活動中啟動該活動時,它將按顯示方式很好地打開,某些功能可以工作,而某些功能不可以! 對我來說很困惑。

基本上,如果我將其打開,因為啟動器數據可以通過串行發送和接收。 但是,如果我從另一個活動中打開它,則絕對廢話會通過串行發送,並且什么也不會回來。 但是,某些部分的工作,例如建立串行連接?!

在啟動活動中,這是打開我想要的活動的代碼:

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>

完整清單:

<?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();
}

}

在這里,您已經將此用於上下文,首先您應該了解不同的上下文。

  • this是指您當前的對象。 在您的情況下,您必須在一個內部類或某個ClickEvent中實現了意圖,這就是它所指向的內容。

  • Activity.this指向您當前所在的Activity的實例。

  • getApplicationContext()引用應用程序的上下文。

現在,如果this上下文直接位於活動的oncreate()下,而不位於任何其他類或某個按鈕的onClick()事件中,則該上下文與活動的上下文相同。

但是,當活動結束時,最好使用getApplicationContext() ,因為活動的上下文會消失。

我在啟動活動的onCreate()中找到了罪魁禍首,那是一個庫調用。 我要做的就是將其從啟動活動移至被調用活動。 這將教會我盲目地遵循API指令。

所以我有SlickUSB2Serial.initialize(this); 在錯誤的活動中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM