gpt4 book ai didi

android - 如何在 Intent Service 中获取 Activity

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:18 25 4
gpt4 key购买 nike

我想在意向服务中获得 Activity 。在 Intent 服务中,向列表控件填充数据。当我在 FloatSomeService(IntentService) 中调用 DictionaryListAdapter 时,没有 Activity 。
(FloatSomeService.java) 服务

 public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
// Find Controls
LayoutInflater inflater = LayoutInflater.from(this);
viewFloat = inflater.inflate(R.layout.float_view, null);
listview = (ListView)viewFloat.findViewById(R.id.listDic);
this.generateData();

// *** Error : When create adapter, get activity from base context *** //
myAdapter = new DictionaryListAdapter((Activity)getBaseContext(), myListItem);

listview.setAdapter(myAdapter);
......................
windowManager.addView(viewFloat, parameters);
}

(DictionaryListAdapter.java)

public class DictionaryListAdapter extends BaseAdapter{
private Activity myContext;
private ArrayList<HistoryListItem> myItems;
public DictionaryListAdapter(Activity activity, ArrayList<DictionaryListItem> items){
this.myContext = activity;
this.myList = items;
}

public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater layoutInflater = this.myContext.getLayoutInflater();
convertView = layoutInflater.inflate(R.layout.history_list_item, null);
}
ImageView imgPerson = (ImageView)convertView.findViewById(R.id.imgPerson);
...........................
}}

最佳答案

使用广播通知将数据从服务传递到 Activity ,并在收到广播通知时更新 Activity 中的 View 。

比如在服务类中定义一个braoadcast通知函数,

public void sendBroadcastNotification(Bundle extras) {
if (CoreApplication.DEBUG)
Log.d(TAG, "Sending broadcast notification" + mIntentMsgId);
Intent intentBroadcast = new Intent(BROADCAST_MESSAGE_NAME);
intentBroadcast.putExtra(CoreConstants.EXTRA_INTENT_MSG_ID,
mIntentMsgId);

sendBroadcast(intentBroadcast);
}

并在服务类中像这样设置通知

sendBroadcastNotification(extras)

在您的 Activity 中定义接收器类

private BroadcastReceiver gpsBRec = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {

//Implement UI change code here once notification is received
}
}

在activity类中,在onResume()中注册接收者,在onStop()中注销接收者

@Override
public void onStop() {
super.onStop();
try {
unregisterReceiver(gpsBRec);
} catch (IllegalArgumentException e) {

}

}



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

registerReceiver(gpsBRec, new IntentFilter(
RetrieveLastTrackDBService.BROADCAST_MESSAGE_NAME));


}

关于android - 如何在 Intent Service 中获取 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22602781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com