1

最近对Android开发很感兴趣,朋友给了我一本书《Android Application Development for Dummies》。在书中,有一个名为 Silent Toggle Mode 的示例应用程序。稍后它会教您为应用程序制作主屏幕小部件。我已经准确地输入了书中的所有内容,但它仍然给我一个错误,通知我永远不会调用 onReceive() 方法。这是代码:

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;
    }
}
}
4

1 回答 1

2

你有一个错字,它是onReceive()而不是onRecieve()。像这样写:

public void onReceive(Context context, Intent intent) 

这是为什么我们应该始终使用@Override注释的一个很好的例子,它简化了查找诸如此类的错误。

于 2013-09-20T15:22:21.933 回答