I want to get activity in intent service. In intent service, fill data to list control.
When i call the DictionaryListAdapter in FloatSomeService(IntentService) don't get activity.
(FloatSomeService.java) Service
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);
...........................
}}
Use broadcast notification to pass data from service to activity and update views in activity when broadcast notification is received.
For example, in service class define a braoadcast notification function,
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);
}
and set notification like this inside service class
sendBroadcastNotification(extras)
Define receiver class in your activity
private BroadcastReceiver gpsBRec = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Implement UI change code here once notification is received
}
}
In activity class, register receiver in onResume() and unregister the receiver in onStop() like this
@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));
}