Recently I have been interested in Android Development and a friend gave me the book "Android Application Development for Dummies". In the book, there is a example app entitled Silent Toggle Mode. Later on there it teaches you to make a home screen widget for the app. I have typed in everything from the book exactly but it still gives me an error notifying me that the onReceive() method is never called. Here is the code:
package com.example.myapplication;
import android.app.Activity;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.widget.RemoteViews;
public class AppWidget extends AppWidgetProvider {
@Override
public void onRecieve(Context context, Intent intent) {
if(intent.getAction()==null) {
context.startService(new Intent(context, ToggleService.class));
} else {
super.onReceive(context, intent);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
context.startService(new Intent(context, ToggleService.class));
}
public static class ToggleService extends IntentService {
public ToggleService() {
super("AppWidget$ToggleService");
}
@Override
protected void onHandleIntent(Intent intent) {
ComponentName me=new ComponentName(this, AppWidget.class);
AppWidgetManager mgr=AppWidgetManager.getInstance(this);
mgr.updateAppWidget(me, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context) {
RemoteViews updateViews=new RemoteViews(context.getPackageName(),R.layout.widget);
AudioManager audioManager=(AudioManager)context.getSystemService(Activity.AUDIO_SERVICE);
if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT) {
updateViews.setImageViewResource(R.id.phoneState,R.drawable.phone_state_normal);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
} else {
updateViews.setImageViewResource(R.id.phoneState,R.drawable.phone_state_silent);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
Intent i=new Intent(this, AppWidget.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
return updateViews;
}
}
}
You have a typo, it's onReceive()
and not onRecieve()
. Write it like this:
public void onReceive(Context context, Intent intent)
This is a good example of why we should always use the @Override
annotation, it simplifies finding bugs such as this one.
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.