如何将数据从服务发送回活动?

时间:2021-02-25 20:58:56

标签: android android-activity android-service

我创建了一个简单的服务,并将根据活动计算的 BMI 传递到服务中。在基于 BMI 值的服务中,我已确定其是否健康、超重或体重不足。现在我希望将该字符串返回到 Main 活动。试图在服务中创建广播,但无法理解如何在主要活动中接收该广播。任何帮助将不胜感激。

我的主要活动

<块引用>

公共类 MainActivity 扩展 AppCompatActivity {

<块引用>
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn);

    height = (EditText) findViewById(R.id.height);
    weight = (EditText) findViewById(R.id.weight);
<块引用>
    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,second.class);

            String str1 = weight.getText().toString();
            String str2 = height.getText().toString();
            float weight = Float.parseFloat(str1);
            float height = Float.parseFloat(str2)/100;
            float bmiValue = calculateBMI(weight, height);
            intent.putExtra("number1",bmiValue);
            startActivityForResult(intent,1);

// 将 BMI 值从活动发送到服务

<块引用>
            Intent intent2 = new Intent(MainActivity.this,MyService.class);
            Bundle extras = new Bundle();
            extras.putFloat("key", bmiValue);
            intent2.putExtras(extras);

            startService(intent2);



        }
    });

}


//Calculate BMI
private float calculateBMI (float weight, float height) {
    return (float) (weight / (height * height));
}
}

//内部服务

<块引用>

公共类 MyService 扩展服务 { @Nullable @覆盖 公共IBinder onBind(意图意图){ 返回空; }

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
       // receiving BMI Value from service 
        Float BMI;
        Bundle b=intent.getExtras();
        BMI = b.getFloat("key",0);
        Log.d("testone", String.valueOf(BMI));
     // sending string as a broadcast
<块引用>
        Intent sendLevel = new Intent();
>             sendLevel.setAction("sending data");
>             sendLevel.putExtra( "DATA",Bmi(BMI));
>              LocalBroadcastManager.getInstance(this).sendBroadcast(sendLevel);
>             //sendBroadcast(sendLevel);
> 
>         return START_STICKY`;
<块引用>
}

@Override
public void onDestroy() {
    super.onDestroy();
}


public String Bmi(float bmi){
 String type;
    if(bmi<=18.5) {
        type = "under weight";
    }   else if(bmi<=35){type="healthy";}
    else{
        type="obese";
    }
    return type;
} }

0 个答案:

没有答案
相关问题