题目描述
使用broadcastreceiver获得android手机的电池电量,并把电量显示到activity中。
技术分析
用接口传。定义一个接口 让 Activity实现这个接口,然后接受者调用接口里面的方法把要传递的参数传进去。
效果
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MainActivity"
/>
</LinearLayout>
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ht.dianliang"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk android:minSdkVersion="7"/>
<application
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
>
<activity
android:name="MainActivity"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name=".DianLiangBR"/>
</application>
</manifest>
广播接收者子类书写
package com.ht.dianliang;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
/**
* Created by annuo on 2015/5/16.
*/
public class DianLiangBR extends BroadcastReceiver {
private BRInteraction brInteraction;
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
//获取当前电量
int current = bundle.getInt("level");
//获取总电量(电池的电池容量)
int total = bundle.getInt("scale");
brInteraction.setText("当前电量:" + current + ",总电量:" + total);
}
public interface BRInteraction {
public void setText(String content);
}
public void setBRInteractionListener(BRInteraction brInteraction) {
this.brInteraction = brInteraction;
}
}
activity书写
package com.ht.dianliang;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.text);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
DianLiangBR dianLiangBR = new DianLiangBR();
registerReceiver(dianLiangBR, intentFilter);
dianLiangBR.setBRInteractionListener(new DianLiangBR.BRInteraction() {
@Override
public void setText(String content) {
if (content != null) {
textView.setText(content);
}
}
});
}
}
时间: 2024-11-29 09:04:54