-1

I'm new at Android, so please excuse my low experience.

I need this service to check if BroadcastReceiver is running or not every period of time.

If it's running then I want it to do nothing, but if not running I want it to run it.

In this code the service run the receiver every 20 sec, but it didn't check if receiver running or not, so every 20 sec I will get new receiver and the running receiver.

Any idea to solve this problem please?

Receiver.java

public class Receiver extends BroadcastReceiver
{
     int numberr =0;
    private static final String TAG = "RestartServiceReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
         int delay = 0;

         int period = 10000;

         Timer basic_timer = new Timer();
             basic_timer.scheduleAtFixedRate(new TimerTask() {
             public void run() {

                Log.e("view", ""+numberr );

                numberr++;

         }
       }, delay, period);

    }

}

Service1.java

public class Service1 extends Service {

public Service1() {
}

@Override
 public int onStartCommand(Intent intent, int flags, int startId) {

             int delay = 0;
             int period =20000;

             Timer basic_timer = new Timer();
                 basic_timer.scheduleAtFixedRate(new TimerTask() {
                 public void run() {

                         sendBroadcast(new Intent("run"));

             }
           }, delay, period);


    return Service.START_STICKY;
}


@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onCreate() {
    Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();

}

@Override
public void onStart(Intent intent, int startId) {

    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();

}

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}

}

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Saymon
  • 1
  • 5
  • 1
    `BroadcastReceiver`s aren't meant to run continuously. They're done when `onReceive()` finishes. Beyond that, it's rather unclear what exactly you're trying to accomplish. – Mike M. Dec 08 '16 at 00:22
  • I don't want `onReceive()` to duplicate because of that service that what I need – Saymon Dec 08 '16 at 02:44

1 Answers1

-3

I think u just forget to register the receiver in menifest. try to add this beside service in menifest~

    <receiver android:name=".Receiver">
        <intent-filter>
            <action android:name="run" />

        </intent-filter>
    </receiver>
    <service ...

ps. make sure your service has been started . or try to call this in your activity

    startService(new Intent(this, Service1.class));
NateZh
  • 81
  • 1
  • 3