我遇到了一个非常有趣的问题 - 我有一个小部件,当按下时,会触发一个OnClickPendingIntent来调用一个可以播放声音的服务。但是,不时大约一个小时,它本身就会发射。
插件:
public class WidgetActivity extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent intent = new Intent(context.getApplicationContext(), SilentService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getService(
context.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.layout, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
context.startService(intent);
}
}
服务:
public class SilentService extends Service {
@Override
public void onStart(Intent intent, int startId) {
Log.e("UpdateWidgetService", "Called");
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (appWidgetIds.length > 0) {
for (final int widgetId : appWidgetIds) {
final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget_layout);
remoteViews.setImageViewResource(R.id.ivc, R.drawable.pic1);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
MediaPlayer mpl = MediaPlayer.create(this, R.raw.music1);
int intRand = random.nextInt(5)+1;
Log.e("r",String.valueOf(intRand));
mpl.start();
mpl.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
remoteViews.setImageViewResource(R.id.ivc, R.drawable.pic2);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
});
}
stopSelf();
}
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
谢谢!
答案 0 :(得分:1)
我有一种感觉Android正在查杀您的服务,然后您的代码正试图再次启动它。我见过类似的问题。请阅读:http://developer.android.com/guide/topics/fundamentals.html#proclife
当Android尝试恢复内存后,当您的服务重新启动时,它会尝试启动该服务,从而创建一个新的媒体播放器并重新启动它。这是我的假设,但不知道代码是如何设置的,但基于我认为最有可能出现的问题。