码迷,mamicode.com
首页 > 其他好文 > 详细

2月4日

时间:2020-02-06 13:07:15      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:word   apply()   ack   sources   resource   edit   private   code   value   

今天主要研究了安卓系统关于如何保持后台运行的相关方面。

 

package com.eb.myapplicationsd;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import com.eb.myapplicationsd.databinding.ActivityMainBinding;
 
public class MainActivity extends AppCompatActivity {
        MyViewModel myViewModel;
        ActivityMainBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binding=DataBindingUtil.setContentView(this,R.layout.activity_main);
         myViewModel = ViewModelProviders.of(thisnew SavedStateViewModelFactory(getApplication(),this)).get(MyViewModel.class);
         binding.setData(myViewModel);
         binding.setLifecycleOwner(this);}
 
    @Override
    protected void onPause() {
        super.onPause();
        myViewModel.save();}}
 
 
package com.eb.myapplicationsd;
 
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;
 
public class MyViewModel extends AndroidViewModel {
    SavedStateHandle savedStateHandle;
    String key=getApplication().getResources().getString(R.string.data_key);
    String shpname=getApplication().getResources().getString(R.string.shp_name);
    public MyViewModel(@NonNull Application application,SavedStateHandle savedStateHandle) {
        super(application);
        this.savedStateHandle=savedStateHandle;
        if(!savedStateHandle.contains(key))
        {}}
  public  LiveData<Integer>getNumber(){
        return savedStateHandle.getLiveData(key);}
    public void load(){
        SharedPreferences sharedPreferences=getApplication().getSharedPreferences(shpname, Context.MODE_PRIVATE);
        int x=sharedPreferences.getInt(key,0);
        savedStateHandle.set(key,x);}
    public void save(){
        SharedPreferences sharedPreferences=getApplication().getSharedPreferences(shpname,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putInt(key,getNumber().getValue());
        editor.apply();}
    public void add(int x){
        savedStateHandle.set(key,getNumber().getValue()+x);}}

2月4日

标签:word   apply()   ack   sources   resource   edit   private   code   value   

原文地址:https://www.cnblogs.com/dg1137/p/12268036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!