如何通过线程更新非主活动活动?



我想更新一个不是主活动的活动。

所以我通过 MainActivity 中的 onClick 方法启动第二个活动。

现在,Activty "SecondActivity"在前面。 当我在"主活动"中启动线程时,我如何引用"第二活动"来更新他们的文本视图等等?

伪代码

public class activity_MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ThreadSome threadSome= new ThreadSome();
threadSome.start()
}

onClick(View View){
Intent intent = new Intent(this, activity_Second.class);
startActivity(intent);
}
}

内螺纹


public class ThreadSome extends Thread {
@Override
public void run() {
//This is what I don't know, so I just write what I want to do.
// I know the following Code is wrong and not working.
activity_Second.someTextView.setText("Hi");
}
}

弱引用是执行此操作的最佳方法,还是更好地处理静态 TextView 对象?你会如何解决这个问题?

根据您的描述,我认为您想做一些事情,即根据在forground活动中执行的某些事件,活动堆栈中会有一些UI更改。有一个很好的方法可以通过startActivityForResult()使用onActivityResult(),但如果这不能直接满足您的要求,那么您可以尝试如下方法:

/**
UpdateActivity is the activity where some ui update or action will be taken based on event in EventActivity.
**/
public class UpdateActivity extends Activity {
private BroadcastReceiver mReceiver;
public static final String ACTION_UPDATE = "com.my.internal.activity.action";
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
......
//Prepared Intent for broadcast receiver
IntentFilter intentFilter = new IntentFilter(ACTION_UPDATE);
//registering our receiver
this.registerReceiver(mReceiver, intentFilter);
.....
}
//This is the receiver section where you need to do the ui update
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
String some_msg = intent.getStringExtra("msg_1"); //parameter received if passed in intent when broadcast called.
//log our message value
Log.i("Message", some_msg);
updateActivityUi();
}
};
private void updateActivityUi() {
// you need to write the code for the update which you want to do after an event done in other activity.
}
@Override
protected void onDestroy() {
super.onDestroy();
//unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
}
public class EventActivity extends Activity {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
......
//Sending BroadcastReceiver against the action ACTION_UPDATE and it will be received by UpdateActivity.
if(condition_for_event) {
Intent i = new Intent(UpdateActivity.ACTION_UPDATE).putExtra("msg_1", "Hey! an event performed here.");
this.sendBroadcast(i);
}
.....
}
....
}

让我知道它是否解决了您的问题。

最新更新