我是android和java开发的新手。目前,我有一个小任务,将电池信息通知为小部件。
我搜索了一下,找到了一段从电池中检索信息的源代码(http://www.tutorialforandroid.com/2009/01/getting-battery-information-on-android.html)。我尝试将其改编为小部件但我遇到了与 BroadcastReceiver 有关的问题。 我试图将电池电量值从BroadcastReceiver传递给RemoteViews。我找到了BroadcastReceiver对象的getResultData()方法,但我总是得到它的Null值。
因此,我想建议将此BroadcastReceiver值传递给RemoteViews。
为了更清楚,我在这里添加了一段代码。
public class MyBattery extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetmanager;
ComponentName thisWidget;
TextView contentTxt;
Context context;
public MyBattery(Context context, AppWidgetManager appWidgetManager){
this.appWidgetmanager = appWidgetManager;
remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
thisWidget = new ComponentName(context,widgetTest.class);
this.context = context;
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent){
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level)+"%");
this.setResultData(String.valueOf(level)+"%");
}
};
@Override
public void run() {
remoteViews.setTextViewText(R.id.battery_label,""+ this.mBatInfoReceiver.getResultData());
appWidgetmanager.updateAppWidget(thisWidget, remoteViews);
}
}
答案 0 :(得分:0)
查看本教程,因为它将帮助您在BraodCastReceiver上构建您的概念: