如果BroadcastReceiver运行,则在Android中不执行任何操作

时间:2016-12-07 23:48:46

标签: java android android-studio android-broadcastreceiver

我是Android新手, 请原谅我的低级经验。

我需要这项服务来检查BroadcastReceiver是否每一段时间都在运行。

如果它正在运行,那么我希望它什么都不做,但如果没有运行,我希望它能够运行它。

在这段代码中,服务每20秒运行一次接收器,但是它没有检查接收器是否运行,所以每20秒我会得到新的接收器和正在运行的接收器。

有什么想法解决这个问题吗?

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();

}

}

1 个答案:

答案 0 :(得分:-3)

我想你只是忘记在清单中注册接收器。 尝试在menifest〜

中添加服务
append

PS。确保您的服务已经启动。或者尝试在你的活动中调用它

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

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