片段活动中的Android电池统计信息

时间:2015-02-18 17:11:32

标签: java android fragment battery

有关此主题的所有教程似乎都假设您正在使用基本活动来检索电池信息。我试图从片段活动中获取信息。我已经知道这是如何在一次活动中获得我正在寻找的东西。

public class Main extends Activity {
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
  int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
  batteryTxt.setText(String.valueOf(level) + "%");
}
};
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}

但是,我无法弄清楚它需要哪些更改才能适应片段活动,因为它似乎是一个稍微不同的过程。

public class HomeFragment extends Fragment {

public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    return rootView;
}
}

2 个答案:

答案 0 :(得分:1)

public class HomeFragment extends Fragment {

private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
  int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
  batteryTxt.setText(String.valueOf(level) + "%");
}
};

public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    batteryTxt = (TextView) rootView.findViewById(R.id.batteryTxt);
    getActivity().registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    return rootView;
}
}

答案 1 :(得分:0)

管理以获得一个基本的工作示例。

public class HomeFragment extends Fragment {
private TextView batteryTxt;
int health = 0;


public HomeFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();

    batteryTxt=(TextView)getActivity().findViewById(R.id.batteryTxt);
    setare();

}

public void setare(){

    batteryTxt.setText("Health: " + health + "%");



}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getActivity().registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        health= intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);


    }
};

}