我在点击小部件中的按钮后试图启动服务,但不知何故该服务没有启动。我在互联网上看,并没有找到答案。
这是onUpdate方法
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Create an intent to launch the service
Intent serviceIntent = new Intent(context, MyService.class);
// PendingIntent is required for the onClickPendingIntent that actually
// starts the service from a button click
PendingIntent pendingServiceIntent =
PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the layout for the App Widget and attach a click listener to the
// button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.meat);
appWidgetManager.updateAppWidget(appWidgetIds, views);
Log.i(TAG, "onUpdate is on");
views.setOnClickPendingIntent(R.id.button, pendingServiceIntent);
context.startService(serviceIntent);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
我也试过onRecive方法
@Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent (context, MyService.class);
intent1.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService (intent1);
super.onReceive(context, intent);
}
我尝试用吐司信息测试它
public class MyService extends Service {
Context context = getApplicationContext();
@Override
public void onCreate() {
Toast.makeText(context, "the service started", Toast.LENGTH_SHORT).show();
}
这是onStartCommand
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer = new MyCounter(21600000,1000);
RemoteViews v = new RemoteViews(getPackageName(),R.layout.meat);
v.setTextViewText(R.id.textView2, getCurrentTime());
appWidgetManager.updateAppWidget(thisWidget, v);
timer.start();
Toast.makeText(context, "the service started", Toast.LENGTH_SHORT).show();
appWidgetManager.updateAppWidget(thisWidget, v);
return START_STICKY;
}
我的清单
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".meat" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/meat_info" />
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="ACTION_WIDGET_CLICK_RECEIVER"/>
</intent-filter>
</service>
</application>
答案 0 :(得分:0)
要启动服务,您必须在onReceive中调用startService方法。所以只需替换这一行:
context.startActivity (intent1);
有了这个:
context.startService(intent1);
并且还要确保覆盖启动服务的onStartCommand方法