内容观察者的更改在启动时不会被调用

时间:2013-07-05 11:56:09

标签: java android broadcastreceiver contentobserver

我正在开发一个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);
      }

请帮忙!谢谢!

1 个答案:

答案 0 :(得分:0)

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