我正在構建我的應用程序,並使用socket.io與Web服務器進行通信。我有java文件,照顧那些不是活動,並在後臺運行。因此,要啓動它們,它將在一個活動中實例化,套接字將運行。現在,web服務器觸發我在回調中處理的消息並將數據傳遞給活動。現在我正在尋找將數據從正在運行的非活動類傳遞到當前正在運行的活動的最佳方式。如何將數據從非活動類傳遞給android中的活動?
我之前所做的是使用非活動類創建的意圖,該類將數據發送到當前正在運行的活動。爲了避免活動繼續自行重啓,必須將活動改爲單實例或單線。 問題是,形式我的主要行動我不能使用單頂發射模式,因爲我需要在某些情況下刷新本身的行動。
所以我不能正確地處理主要活動的套接字,因爲我只能接收數據,如果我將主要活動更改爲不適合該應用程序的singletop。我首先嚐試在非活動類中調用的活力命名函數,但看起來這是非法的,所以我很困難。
@Override
public void on(String event, IOAcknowledge ack, Object... data) {
System.out.println("Server may have triggered event '" + event + "'");
if (event.equals("message")) {
System.out.println(data[2]);
Intent newIntent = new Intent(Chat.mContent, Chat.class);
Bundle extras=new Bundle();
extras.putString("name", (String)data[1]);
extras.putString("MSG", (String)data[2]);
newIntent.putExtras(extras);
Chat.mContent.startActivity(newIntent);
}
if (event.equals("ready")) {
System.out.println("Received the ready callback");
try{
Intent newIntent = new Intent(TabExercise.mContext, TabExercise.class);
newIntent.putExtra("ready", event);
TabExercise.mContext.startActivity(newIntent);
}catch(Exception e){
System.out.println("Caught an error");
}
}
}
這是發送數據的非活動類中的方法。
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle extras=intent.getExtras();
if (intent.hasExtra("ready")) {
// Retrieve the message and call getMsg(String)
connect.starter(SaveSharedPreference.getName(TabExercise.this), SaveSharedPreference.getUserId(TabExercise.this));
}
}
這是哪裏的意圖被捕獲在MainActivity。不理想。
共享PERF可能工作 – KOTIOS
嗯,我不明白如何,將工作,因爲它需要實時工作。 –