使用广播接收器每15秒呼叫后台服务

时间:2016-01-07 07:47:17

标签: java android broadcastreceiver android-service

我尝试每15秒向服务器发送一次数据,所以我使用广播接收器和Android服务,但它不再工作。我检查互联网连接每15秒,当连接可用时,它将数据发送到服务器。

Test.java

public class Test extends AppCompatActivity {
   private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        this.context = this;
        Intent alarm = new Intent(this.context, AlarmReceiver.class);
        boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
        if(alarmRunning == false) {
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15000, pendingIntent);
        }

    }

AlarmReceiver.java

    public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent background = new Intent(context, BackgroundService.class);
        context.startService(background);
    }
}

BackgroundService.java

    public class BackgroundService extends Service {
    private boolean isRunning;
    private Context context;
    private Thread backgroundThread;

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

    @Override
    public void onCreate() {
        this.context = this;
        this.isRunning = false;
        this.backgroundThread = new Thread(myTask);
    }

    private Runnable myTask = new Runnable() {
        public void run() {
           // Do something here
           internet();
           System.out.println("call every 15 seconds");
           Log.d("Background","Services run every 15 second");
           stopSelf();
        }
    };

    @Override
    public void onDestroy() {
        this.isRunning = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!this.isRunning) {
            this.isRunning = true;
            this.backgroundThread.start();
        }
        return START_STICKY;
    }

    private void internet() {
        Helper hp = new Helper(context);
        if (hp.isonline() == true) {
            System.out.println("net connect");
        } else {
            System.out.println("net not available");

        }
    }

    }

}

的Manifest.xml

   <service android:name=".service.BackgroundService" />
        <receiver android:name=".service.AlarmReceiver"></receiver>

只能在logcat打印消息中返回一次井号,而不是每15秒一次。

0 个答案:

没有答案