在MainActivity中,我创建了一个intent并使用putExtra()
方法将数据传递给我的Intent Service。在我的Intent Service中,我创建HTTP请求并获得响应,我想将响应传递回MainActivity。
MainActivity 代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] a0 = {"first","second"};
int[] a1 = {1,2,3};
Intent intent = new Intent(MainActivity.this,BackGround.class);
intent.putExtra("a0",a0);
intent.putExtra("a1",a1);
intent.putExtra("numberOfArguments",2);
intent.putExtra("fileName","program.java");
startService(intent);
/* i want to continue the program here after getting
the response and do some stuff*/
}
}
IntentService 代码:
public class BackGround extends IntentService {
final static String NAME = "BackGround";
public BackGround(String name) {
super(NAME);
}
public BackGround(){
super(NAME);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Bundle bundle = intent.getExtras();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://68d1e2eb.ngrok.io")
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
ServerJsonObject serverJsonObject = new ServerJsonObject(bundle.getString("fileName"),
new NestedObject(bundle.getStringArray("a0"),bundle.getIntArray("a1")),bundle.getInt("numberOfArguments"));
Call<Result> call = api.sendData(serverJsonObject);
try {
Response<Result> response = call.execute();
// i want to return Result to main activity
} catch (IOException e) {
e.printStackTrace();
}
}
}
在我的情况下如何做到这一点?
答案 0 :(得分:0)
将Handler放入您的活动中,如
`stDao.save()`
并将消息从服务传递给处理程序。
Handler mHandler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});