我正在设计一个切换小部件,用于静音和取消静音媒体音量。它工作得很好,直到我安装任何新应用程序...然后它就停止工作。没有力量关闭或任何东西,当我按下它时它什么都不做。 (如果我删除小部件并再次添加它,它将再次开始工作。)对于log cat,我没有看到任何与我的应用程序相关的消息。
我已经在下面发布了代码,但是如果你能够在概念上告诉我在安装新应用时主屏幕会发生什么,而且基本上我可以排除故障也会有所帮助。
感谢您的帮助。我已经在这几天了,只是想不出来。我有现货android 4.04 Galaxy Nexus。
public class JCrashWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_RECEIVER = "com.JCrash.widget.ACTION_WIDGET_RECEIVER";
public static String ACTION_WIDGET_CONFIGURE = "com.JCrash.widget.ACTION_WIDGET_CONFIGURE";
private RemoteViews remoteViews = new RemoteViews("com.JCrash", R.layout.widgetstyle1 );
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
Intent mediaClick = new Intent(context, JCrashWidget.class);
mediaClick.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, mediaClick, 0);
remoteViews.setOnClickPendingIntent(R.id.headphonesid, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds,remoteViews );
}
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName cn = new ComponentName(context, JCrashWidget.class);
int cVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SharedPreferences myPrefs = context.getSharedPreferences("myPrefs", Context.MODE_WORLD_WRITEABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
if (cVol == 0)
{
cVol = myPrefs.getInt("PREVIOUS_VOLUME", 0);
remoteViews.setImageViewResource(R.id.headphonesid,R.drawable.headphones);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, cVol,
AudioManager.FLAG_SHOW_UI);
cVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
else
{
prefsEditor.putInt("PREVIOUS_VOLUME", cVol);
prefsEditor.commit();
cVol = myPrefs.getInt("PREVIOUS_VOLUME", 0);
remoteViews.setImageViewResource(R.id.headphonesid,R.drawable.headphones_off);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_SHOW_UI);
cVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
AppWidgetManager.getInstance(context).updateAppWidget(cn, remoteViews);
}
}
}
答案 0 :(得分:2)
想出来!我不得不在OnReceive方法和OnUpdate方法中再次设置OnClickPendingIntent。我只是创建一个函数来设置窗口小部件的挂起意图,并从OnReceive和OnUpdate调用它。