1

我正在开发一个 android 应用程序,我在其中注册我的 ContentObserver 类以检测 VOLUME_RING 中的变化。

我的问题是,我在手机启动时调用 ContentObserver 类,并且我能够进入 Contentobserver 类,但未调用 onchange 方法(即未检测到音量变化)。

请查看下面的代码,

 //BootupReceiver code.

            public class Bootupreceiver extends BroadcastReceiver 
               {
                 @Override
                 public void onReceive(Context context, Intent intent) 
                    {
                    Intent startServiceIntent = new Intent(context,ServiceforVolumeChecker.class);
                    startServiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startService(startServiceIntent);
                    }
               }


 //code to register the Content observer class.

public class ServiceforVolumeChecker extends Service
{

private VolumeChecker Volume;

@Override
public void onCreate() 
{
    super.onCreate();

    Log.e("Service","Service");

    Volume = new VolumeChecker(this,new Handler());

    String vol_ring = android.provider.Settings.System.VOLUME_RING;

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;


    if (currentapiVersion >= 17)
    {
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, Volume );
    }
    else
    {
        getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.getUriFor(vol_ring), true, Volume);
    }

    stopService(new Intent(this, ServiceforVolumeChecker.class));
}

@Override
public IBinder onBind(Intent intent) 
{
    // TODO Auto-generated method stub
    return null;
}


   //code of ContentObserver class.


     public class VolumeChecker extends ContentObserver 
        {

          public VolumeChecker(Context c, Handler handler)
        {
            super(handler);
            context=c;
            this.handler = handler;

        }

@Override
public boolean deliverSelfNotifications()
{
    return super.deliverSelfNotifications();
}

@Override
public void onChange(boolean selfChange) 
      {
       super.onChange(selfChange);
      }

请帮忙!谢谢!

4

1 回答 1

0

将服务任务放在onStartCommand中,而不是使用onCreate

于 2013-07-05T12:12:12.860 回答