I am creating an android launcher and want to implement appWidgets. For testing, I am using the com.android.quicksearchbox
widget and adding it to the top of the screen. Problem is, I am using AppWidgetHostView and it seems not to notice any click or touch events the user does. Can anybody tell me why ? Here is all my code for appWidgets (in the onCreate(Bundle)
function) :
android.appwidget.AppWidgetManager appWidgetManager = android.appwidget.AppWidgetManager.getInstance(this);
android.appwidget.AppWidgetHost appWidgetHost = new android.appwidget.AppWidgetHost(this, 0);
android.appwidget.AppWidgetProviderInfo newAppWidgetProviderInfo = new android.appwidget.AppWidgetProviderInfo();
int appWidgetId = appWidgetHost.allocateAppWidgetId();
List<android.appwidget.AppWidgetProviderInfo> appWidgetInfos = new ArrayList<android.appwidget.AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();
for(int j = 0; j < appWidgetInfos.size(); j++)
{
if (appWidgetInfos.get(j).provider.getPackageName().equals("com.android.quicksearchbox"))
{
newAppWidgetProviderInfo = appWidgetInfos.get(j);
break;
}
}
android.appwidget.AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);
android.widget.LinearLayout ll = (android.widget.LinearLayout) findViewById(R.id.loll);
ll.addView(hostView, 0);
loll is my LinearLayout.
So anybody knows how can I enable events ? Or if there is another method of adding app-widgets to my launcher ?
Thank you.
I am not sure the code is complete , but you need to add at least the following in your activity .
@Override
protected void onStart() {
super.onStart();
Host.startListening();
}
@Override
protected void onStop() {
super.onStop();
Host.stopListening();
}
Does this make sense?
You need to bind the widget to make it interactive and allow it to update:
boolean allowed = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, newAppWidgetProviderInfo.provider);
if (!allowed) {
// Request permission
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, newAppWidgetProviderInfo.provider);
final int REQUEST_BIND_WIDGET = 1987;
myActivity.startActivityForResult(intent, REQUEST_BIND_WIDGET);
}
Additionally, as mentioned in @Sergey's response, you need to add the following in your activity or fragment:
@Override
protected void onStart() {
super.onStart();
appWidgetHost.startListening();
}
@Override
protected void onStop() {
super.onStop();
appWidgetHost.stopListening();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.