2016-08-16 72 views
0

我有这个服务,其中包括 - 更新一个TextView,每次它被破坏(TextView是“txtCounter”)。通过更新它,我的意思是它每次向TextView添加1(一)。所以,我第一次调用这个服务时,TextView应该是1.第二次应该是2等等。为什么SharedPreferences只更新一次TextView?

不幸的是,它只能使用一次,每当我杀的应用,甚至是1消失。有任何想法吗?

MainActivity:

public class MainActivity extends AppCompatActivity { 

public TextView txtCounter; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final Button startApp = (Button) findViewById(R.id.startApp); 
    final EditText timer = (EditText) findViewById(R.id.insertTimer); 

    assert startApp != null; 
    startApp.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Toast.makeText(MainActivity.this, "Countdown, Started", Toast.LENGTH_SHORT).show(); 

      Intent startMain = new Intent(Intent.ACTION_MAIN); 
      startMain.addCategory(Intent.CATEGORY_HOME); 
      startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      startActivity(startMain); 

      Intent intent = new Intent(MainActivity.this, MainService.class); 
      assert timer != null; 
      intent.putExtra("timer", timer.getText().toString()); 
      startService(intent); 

      Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000); 

      registerReceiver(broadcastReceiver, new IntentFilter(MainService.BROADCAST_ACTION)); 
     } 
    }); 
} 

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { updateUI(intent); } 
}; 

private void updateUI(Intent intent) { 
    txtCounter = (TextView) findViewById(R.id.txtCounter); 
    String counter = intent.getStringExtra("counter"); 

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE); 
    SharedPreferences.Editor editor = pref.edit(); 
    editor.putString(counter,String.valueOf(txtCounter)); 
    editor.apply(); 

    assert txtCounter != null; 
    txtCounter.setText(counter); 
} 

@Override 
public void onDestroy() { 
    try { unregisterReceiver(broadcastReceiver); } catch (IllegalArgumentException ignored) {} 

    super.onDestroy(); 
} 

MainService:

public class MainService extends Service { 

static String BROADCAST_ACTION = "com.example.vladpintea.friendsbeforecents.displayevent"; 
Handler handler = new Handler(); 
int counterr = 0; 
Intent intentt; 

String usedTimer; 
long interval; 

//TimerTask that will cause the run() runnable to happen. 
TimerTask myTask = new TimerTask() { 
    public void run() { stopSelf(); } 
}; 
//Timer that will make the runnable run. 
Timer myTimer = new Timer(); 

@Override 
public void onCreate() { 
    Toast.makeText(MainService.this, "Service, Created", Toast.LENGTH_SHORT).show(); 

    intentt = new Intent(BROADCAST_ACTION); 

    registerReceiver(counter, new IntentFilter(Intent.ACTION_SCREEN_ON)); 
} 

private BroadcastReceiver counter = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     myTimer.cancel(); 

     Toast.makeText(MainService.this, "Whoops! You've Lost.", Toast.LENGTH_SHORT).show(); 

     Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000); 
    } 
}; 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Toast.makeText(MainService.this, "Service, Started", Toast.LENGTH_SHORT).show(); 

    usedTimer = intent.getStringExtra("timer"); 
    try { 
     interval = Long.parseLong(usedTimer); 
    } catch (NumberFormatException ignored) { 
    } 

    myTimer.schedule(myTask, interval); 

    handler.removeCallbacks(sendUpdatesToUI); 
    handler.postDelayed(sendUpdatesToUI, 1000); 

    return super.onStartCommand(intent, flags, startId); 
} 

private Runnable sendUpdatesToUI = new Runnable() { 
    public void run() { 
     handler.postDelayed(this, 1000); } 
}; 

public void DisplayLoggingInfoPlus() { 
    intentt.putExtra("counter", String.valueOf(++counterr)); 
    sendBroadcast(intentt); 
} 

@Override 
public void onDestroy() { 
    unregisterReceiver(counter); 

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK 
      | PowerManager.ACQUIRE_CAUSES_WAKEUP 
      | PowerManager.ON_AFTER_RELEASE, "MyWakeLock"); 
    if ((wakeLock != null) && (!wakeLock.isHeld())) { wakeLock.acquire(); } 

    Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 30000); 

    DisplayLoggingInfoPlus(); 
} 

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

回答

2

你是不是真正的保值增值。首先,在您的广播目的中,您正在初始化counter = 0,然后在发送时,您将其增加1.因此,您并不需要它。当我们收到广播时,我们可以在活动中更新它。所以,在你Service,你的代码可以是:

// Get rid of counter variable elsewhere too 
public void DisplayLoggingInfoPlus() { 
    sendBroadcast(intentt); 
} 

现在,在您的Activity,我们必须得更新的价值,所以我们可以修改代码:

private void updateUI(Intent intent) { 
    txtCounter = (TextView) findViewById(R.id.txtCounter); 
    // String counter = intent.getStringExtra("counter"); 

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE); 
    int counter = pref.getInt("counter", 0); // Getting int now instead of String 
    SharedPreferences.Editor editor = pref.edit(); 
    editor.putInt("counter", ++counter); 
    editor.apply(); 

    assert txtCounter != null; 
    txtCounter.setText(String.valueOf(counter)); 
} 
+0

你是我的最新英雄。谢谢!奇迹般有效。 –