如何显示充电器是否插入/拔出活动?

时间:2016-07-23 07:32:38

标签: android broadcastreceiver

我是android的新手。如果插入或拔出充电器,我想在活动中更改textview文本。为此,我已在清单中注册了一个带有意图android.intent.action.ACTION_POWER_CONNECTED android.intent.action.ACTION_POWER_DISCONNECTED

的接收器

以下是接收者的代码:

public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    if(intent.getAction() == Intent.ACTION_POWER_CONNECTED) {
        //Handle power connected
        Log.e("Charger State","power connected");
        Toast.makeText(context, "Charger PluggedIn", Toast.LENGTH_SHORT).show();
    } else if(intent.getAction() == Intent.ACTION_POWER_DISCONNECTED){
        //Handle power disconnected
        Log.e("Charger State","power disconnected");
        Toast.makeText(context, "Charger PluggedOut", Toast.LENGTH_SHORT).show();
    }

   }
}

这是完美的工作,但我希望在插入或拔出充电器的活动中显示它。请帮我完成任务。

感谢〜

2 个答案:

答案 0 :(得分:0)

有很多方法可以将数据从广播接收器传递到活动

最好的方法是使用总线

fscanf

答案 1 :(得分:0)

只需编写您在此活动中使用的代码

public class MyActivity extends Activity{

 TextView mTextView;
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTextView =(TextView) findViewById(R.id.text);

}

 public class PowerConnectionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    if(intent.getAction() == Intent.ACTION_POWER_CONNECTED) {
        //Handle power connected
        Log.e("Charger State","power connected");
        mTextView.setText("Charger PluggedIn");
        Toast.makeText(context, "Charger PluggedIn", Toast.LENGTH_SHORT).show();
    } else if(intent.getAction() == Intent.ACTION_POWER_DISCONNECTED){
        //Handle power disconnected
        Log.e("Charger State","power disconnected");
        mTextView.setText("Charger PluggedOut");
        Toast.makeText(context, "Charger PluggedOut", Toast.LENGTH_SHORT).show();
    }else{
      mTextView.setText("");
     }

   }
}