每天尝试运行功能

时间:2019-01-21 12:56:15

标签: android service gcm-network-manager

即使用户杀死我的应用程序,只要用户检查了我应用程序中的某个开关,我也会尝试每分钟显示一次Toast。我已经使用SharedPreferences保存了开关值。我不知道如何有条件地调用服务,到目前为止,我的代码正在产生错误“无法在尚未调用Looper.prepare()的线程内创建处理程序”。

MyService.xml:

public class MyService extends GcmTaskService {
    @Override
    public int onRunTask(TaskParams taskParams) {
        Toast.makeText(this, "Periodic one eh", Toast.LENGTH_SHORT).show();
        return 0;
    }
}

SettingsActivity.java(句柄开关):

    public class SettingsActivity extends AppCompatActivity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_page);
        Switch auto = findViewById(R.id.auto);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;

        getWindow().setLayout((int) (width * 0.9), (int) (height * 0.8));

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean silent = settings.getBoolean("switchKey", false);
        auto.setChecked(silent);

        auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {

                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("switchKey", isChecked);
                editor.commit();
            }

        });

        handler();

    }

    public void handler() {
        SharedPreferences shared = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        Boolean channel = (shared.getBoolean("switchKey", false));
        String tag = "periodic";

        GcmNetworkManager mScheduler = GcmNetworkManager.getInstance(getApplicationContext());

        long periodSecs = 10L;// 1 minute

        PeriodicTask periodic = new PeriodicTask.Builder()
                .setService(BackgroundWallpaperSetter.class)
                .setPeriod(periodSecs)
                .setTag(tag)
                .setPersisted(true)
//                .setUpdateCurrent(true).setRequiredNetwork(com.google.android.gms.gcm.Task.NETWORK_STATE_CONNECTED)
                .build();
        mScheduler.schedule(periodic);
    }
}

请帮助。 :)

0 个答案:

没有答案