Update database field before the connections changed and turned off in android studio

huangapple go评论77阅读模式
英文:

Update database field before the connections changed and turned off in android studio

问题

我有一个即时通讯应用,数据库中有一个离线字段,希望在用户关闭WiFi或移动数据时更新此字段,就像WhatsApp和Telegram一样。
我该如何实现这个?我还使用了广播和一个服务来监听网络连接状态的变化,但我在解决这个问题时感到困惑。

英文:

I have a messenger app and I have an offline field in my database and want to update this field when user turn off the wifi or mobile data? like whats app and telegram?
How can I do that? I also use broadcast and a service to listen to the connectivity state change but I'm confuse to resolve this.

答案1

得分: 1

使用 JobService...
以这个示例为例:

OfflineJob 类:

public class OfflineJob extends JobService {

    @Override
    public boolean onStartJob(JobParameters params) {
        // 在这里编写你的代码
        Toast.makeText(this, "任务已开始!", Toast.LENGTH_SHORT).show();

        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }
}

你的活动:

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);
    schedulerService();
}

private void schedulerService() {
    // 在网络可用时将调用你的调度器服务
    ComponentName component = new ComponentName(getPackageName(),
            OfflineJob.class.getName());

    JobInfo.Builder builder = new JobInfo.Builder(123, component);
    // 设置其他约束条件
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
    // 调度任务
    mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    mJobScheduler.schedule(builder.build());
}
英文:

Use JobService...
Take this example:

OfflineJob class:

public class OfflineJob extends JobService {

@Override
public boolean onStartJob(JobParameters params) {
    //write your code here
    Toast.makeText(this, "job started!", Toast.LENGTH_SHORT).show();

    return false;
}

@Override
public boolean onStopJob(JobParameters params) {
    return false;
}
}

Your activity:

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);
    schedulerService();
}
private void schedulerService() {
    
    // Your scheduler service will be called when the network is available.
    ComponentName component = new ComponentName(getPackageName(),
            OfflineJob.class.getName());

    JobInfo.Builder builder = new JobInfo.Builder(123, component);
    // Set some other constraints
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
    // Schedule it
    mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    mJobScheduler.schedule(builder.build());

}

huangapple
  • 本文由 发表于 2020年9月23日 19:48:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64027291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定