我有一个发送广播的应用程序小部件,然后广播接收器将启动服务,问题是当单击小部件时它只能在第一次工作,然后我必须打开应用程序来停止服务。
这个小部件代码:
public class Widget extends AppWidgetProvider {
int appWidgetId;
RemoteViews views;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
for (int i = 0; i < appWidgetIds.length; i++) {
appWidgetId = appWidgetIds[i];
views = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent bIntent = new Intent(context,BroadCast.class);
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, bIntent,0);
views.setOnClickPendingIntent(R.id.widgetbtn, pIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
广播:
public class BroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent serviceIntent=new Intent(context,Service.class);
if (!isServiceOn) {
context.startService(serviceIntent);
} else {
context.stopService(serviceIntent);
}
}
}
但是当我从主要活动发送广播时,它工作正常。