Firebase作业调度程序仅调用一次

时间:2017-04-04 11:32:47

标签: android firebase firebase-realtime-database firebase-job-dispatcher

我是新手,我已经从firebase作业调度API的官方报告中实现了一个演示引用。

我想每2分钟运行一次特定任务,然后致电Firebase并从那里获取单个值并更新我的TextView。

发生了几次,我等了5分钟,但没有调用,我调试了应用程序,发现onStartJob()没有被调用。

很多时候它只调用一次,然后停止,再也没有再调用过。

以下是代码:

  

DeviceSpaceService

public class DeviceSpaceService extends JobService {

    private static final String TAG = "DeviceSpaceService";

    private int val = 0;

    @Override
    public boolean onStartJob(final JobParameters job) {

        Log.e(TAG, "onStartJob() called with: job = [" + job + "]");

//        if (Build.VERSION.SDK_INT >= 18)
//            Log.e("DEVICE_SPACE",
//                    "Free space is " +
//                            (statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong() / 1024) + " Kb"
//            );


        new Thread(new Runnable() {
            @Override
            public void run() {
                complteJob(job);
            }
        }).start();
        return true;
    }

    private void complteJob(JobParameters job) {

        if (val == 10) {
            jobFinished(job, false);
            return;
        }
        Home.setAndSend(String.valueOf(val));
        val++;
        Log.e(TAG, "complteJob() called with: job = [" + val + "]");
    }

    @Override
    public boolean onStopJob(JobParameters job) {
        Log.e(TAG, "onStopJob() called with: job = [" + job + "]");
        return false;
    }
}
  

家庭活动

public class Home extends AppCompatActivity {

    static TextView tvMain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        tvMain = (TextView) findViewById(R.id.tv_main);

        //Added dispatcher object as it is must to diapatch the job declared.
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));

        Job job = dispatcher.newJobBuilder().setLifetime(Lifetime.UNTIL_NEXT_BOOT)
                .setService(DeviceSpaceService.class).setTag("DeviceSpaceCheck").setRecurring(true).setReplaceCurrent(false)
                .setTrigger(Trigger.executionWindow(0,120)).build();

        dispatcher.mustSchedule(job);
    }

    public static void setAndSend(String val) {
        // Write a message to the database
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("message" + val);

        myRef.setValue("Hello, World!" + val);

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (tvMain != null)
                    tvMain.setText(dataSnapshot.getValue().toString());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

0 个答案:

没有答案