1

在 MainActivity 中,我创建了一个意图并使用putExtra()方法将数据传递给我的意图服务。在我的意图服务中,我创建 HTTP 请求并获取响应,我想将响应传递回 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*/

    }
}

意向服务代码:

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


    }
}

在我的情况下如何做到这一点?

4

1 回答 1

0

将 Handler 放入您的活动中,例如

Handler mHandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

并将消息从服​​务传递给处理程序。

  if (mHandler != null) {
        Message m = new Message();
        m.obj = "completed";
        mHandler.sendMessage(m);
    }
于 2018-05-15T10:31:32.240 回答