简体   繁体   中英

service and broadcastreceiver

I am trying to create a service in which i am calling a method repeatedly after 5000ms.This method increments a counter and when it reaches to 6 i want to call another activity through a broadcast receiver. But i am getting an error "Are you missing a call to unregisterreceiver()".Can anyone tell me what exactly the problem is?

Main activity

public class ServicesExampleActivity extends Activity implements OnClickListener 
{
Button start,stop;
IntentFilter intentfilter;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_services_example);

    intentfilter = new IntentFilter();
    intentfilter.addAction("LOCATION_REACHED");


    registerReceiver(intentreceiver, intentfilter);

    start = (Button) findViewById(R.id.start);
    stop = (Button) findViewById(R.id.stop);

    start.setOnClickListener(this);
    stop.setOnClickListener(this);
}

@Override
public void onClick(View v) 
{
    if(v.getId()==R.id.start)
    {
        startService(new Intent(getApplicationContext(),ServiceClass.class));
    }
    else if(v.getId()==R.id.stop)
    {
        stopService(new Intent(getApplicationContext(),ServiceClass.class));
    }       
}

private BroadcastReceiver intentreceiver = new BroadcastReceiver()
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {

        if(intent.getAction().equals("LOCATION_REACHED"))
        {   
            Intent intent1 = new Intent(getApplicationContext(),LocationReached.class);
            startActivity(intent1);
        }
    }
};


}

ServiceClass.java

public class ServiceClass extends Service
{
int counter = 0;
static final int UPDATE_INTREVAL = 5000;    //in milliseconds
private Timer timer = new Timer();

@Override
public IBinder onBind(Intent arg0) 
{
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
    doSomeThingRepeatedly();
    return START_STICKY;
}

@Override
public void onDestroy() 
{
    super.onDestroy();
    if(timer!=null)
    {
        timer.cancel();
    }
    Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
}

private void doSomeThingRepeatedly()
{
    timer.scheduleAtFixedRate(new TimerTask()
    {

        @Override
        public void run() 
        {

            Toast.makeText(getApplicationContext(), ""+counter, Toast.LENGTH_SHORT).show();
            counter++;              

            if(counter==6)
            {

                Intent broadcastintent = new Intent();
                broadcastintent.setAction("LOCATION_REACHED");
                getApplicationContext().sendBroadcast(broadcastintent);
            }
        }
    }, 0, UPDATE_INTREVAL); 
}

}

andridmanifest.xml

<activity
        android:name="com.vallabh.servicesexample.ServicesExampleActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name="com.vallabh.servicesexample.ServiceClass"></service>
    <activity android:name="com.vallabh.servicesexample.LocationReached"></activity>

"Are you missing a call to unregisterReceiver()"

means you forget to unregister BroadcastReceiver when Activity is not running. so use onStop() method of Activity to unregister BroadcastReceiver as:

@Override
protected void onStop()
{
    if(null !=intentreceiver)
      unregisterReceiver(intentreceiver);

    super.onStop();
}

and instead of registering BroadcastReceiver in onCreate of Activity use onResume method for registering Broadcast because when you came back from next Activity then it will register again.

您应该使用unregisterReceiver(theReceiver)覆盖Activity.onPause()并取消注册您已注册的接收者;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM