How do I keep an updated TextView (via SharedPreferences) on the UI? - android

I've got this TextView (txtCounter), which updates itself every time I run a service. Said process runs smoothly, but whenever I close the application and open it up again, the TextView doesn't show the actual variable, only after I once again run the service.
I know I need to do something in the onCreate (or onResume?) method, something along the lines of receiving the updated TextView from the method which updates it (in my case, it's "UpdateUI") but I don't know what.
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);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
int counter = pref.getInt("counter", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("counter", ++counter);
editor.apply();
assert txtCounter != null;
txtCounter.setText(String.valueOf(counter));
}
#Override
public void onDestroy() {
try { unregisterReceiver(broadcastReceiver); } catch (IllegalArgumentException ignored) {}
super.onDestroy();
}

Call the following method in onResume():
// read counter variable and update the textview
private void updateTextView() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
int counter = pref.getInt("counter", 0);
setCounterTV(counter);
}
// Update the textview with a counter value
private void setCounterTV(int counter) {
txtCounter = (TextView) findViewById(R.id.txtCounter);
assert txtCounter != null;
txtCounter.setText(String.valueOf(counter));
}
// Method to be called by your service
private void updateUI() {
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyFile", MODE_PRIVATE);
int counter = pref.getInt("counter", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("counter", ++counter);
editor.apply();
setCounterTV(counter);
}

Related

After exit an app. How to open next activity after timer end count?

I have CountDownTimer which is running after I exit an app:
countDownTimer = new CountDownTimer(timeLeftMilis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftMilis = millisUntilFinished;
updateCountTextView();
}
#Override
public void onFinish() {
runnning = false;
textView.setText("00:00:00");
Intent intent = new Intent(MainActivity.this, Sound.class);
startActivity(intent);
}
}.start();
runnning = true;
onStop and onStart methods:
#Override
protected void onStop() {
super.onStop();
SharedPreferences shpref = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = shpref.edit();
editor.putLong(END_TIME,endTime);
editor.putLong(MILISECOND_START, mTimeStartMilis);
editor.putLong(MILISECOND_LEFT, timeLeftMilis);
editor.putBoolean(RUNNING, runnning);
editor.apply();
if(countDownTimer != null){
countDownTimer.cancel();
}
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
endTime = sharedPreferences.getLong(END_TIME,0);
mTimeStartMilis = sharedPreferences.getLong(MILISECOND_START, -1);
timeLeftMilis = sharedPreferences.getLong(MILISECOND_LEFT, -1);
runnning = sharedPreferences.getBoolean(RUNNING, false);
if (runnning) {
timeLeftMilis = endTime - System.currentTimeMillis();
if (timeLeftMilis < 0) {
timeLeftMilis = 0;
runnning = false;
updateCountTextView();
updateButtons();
} else {
startTimer();
}
}
}
The problem is when I exit an app and time is end, beacuse method onFinish() not start Sound.class
How to start an intent after exit app? Do I have to register receiver ?
EDIT
My Alarm Class
public class Alarm extends AppCompatActivity {
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.dsh);
mediaPlayer.start();
}
public void onClickOff(View view){
mediaPlayer.stop();
finishAndRemoveTask();
}
#Override
protected void onDestroy(){
super.onDestroy();
mediaPlayer.stop();
}
public static class Second extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context,Alarm.class);
context.startActivity(intent1);
}
}
}
Manifest:
<activity android:name=".Alarm"/>
<receiver android:name=".Alarm$Second"/>
When I have Activity opened it is working but when exit, it is not working.
I have this code in onFinish method.
Intent intent = new Intent(MainActivity.this, Alarm.Second.class);
PendingIntent pd = PendingIntent.getBroadcast(getApplication(),1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Calendar c = Calendar.getInstance();
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() + 1, pd);
you can use handle same as a splash screen if you work with
for eg. a splash screen timer is 2 second then you can call handler for 2 second
a perfect example is below
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashActivity.this,NavigationMenuActivity.class);
startActivity(intent);
finish();
}
},2500);

how to pass a string data to my activity from a service

I have an activity that runs a timer and I want to broadcast that timer and set a receiver to my activity and display the timer. I know that it can be done using a broadcast and receiving that broadcast intent but I don't know how to do it.
here are my codes
public class MyService extends Service {
private Vibrator v;
NotificationCompat.Builder notification;
private static final int uniqueID = 71399;
#Override
public void onCreate() {
super.onCreate();
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences = getSharedPreferences("Timer", Context.MODE_PRIVATE);
int dur = sharedPreferences.getInt("duration", 0);
//background timer
CountDownTimer countDownTimer = new CountDownTimer(dur, 1000) {
#Override
public void onTick(long dur) {
long millis= dur;
String hms= String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
//seconds
,TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
startnotif(hms);
startBroadcast(hms);
}
#Override
public void onFinish() {
long n[] = {1,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000,500,1000};
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(n, -1);
endnotif();
onDestroy();
}
};
countDownTimer.start();
return START_STICKY;
}
public void onDestroy() {
stopSelf();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//notification
public void startnotif(String hms)
{
String noT = hms;
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setTicker("apps are blocked!");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Be productive!");
notification.setContentText(hms);
ClickNotif();
}
public void endnotif(){
notification.setContentText("00:00");
notification.setTicker("apps are now unblocked!");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("You survived!");
notification.setContentText("Apps are now unblocked!");
ClickNotif();
}
//other parts of notif
public void ClickNotif(){
Intent intent1 = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
The Target activity
public class Main2Activity extends AppCompatActivity {
private Button btntest;
private TextView timer;
private Spinner spinner, spinner2;
public int hours, mins, duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btntest = (Button) findViewById(R.id.startbtn);
timer = (TextView) findViewById(R.id.Timertxt);
//setting up 2 spinners
spinner = (Spinner) findViewById(R.id.hrspinner);
String [] values = {"00","01","02","03","04","05","06"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);
spinner2 = (Spinner) findViewById(R.id.minspinner);
String [] values2 = {"00","01","10","20","30","40","50","60"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, values2);
adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner2.setAdapter(adapter2);
//button start
btntest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String spin=spinner.getSelectedItem().toString();
hours = Integer.parseInt(spin);
hours = hours*3600000;
String spin2=spinner2.getSelectedItem().toString();
mins = Integer.parseInt(spin2);
mins = mins*60000;
duration = hours+mins;
setParam(duration);
startService(duration);
}
});
}
/*timer part
public void setParam(int param){
CountDownTimer countDownTimer = new CountDownTimer(param, 1000) {
#Override
public void onTick(long param) {
long millis= param;
String hms= String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))
//seconds
,TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
timer.setText(hms);
}
#Override
public void onFinish() {
timer.setText("00:00");
}
};
countDownTimer.start();
}*/
//saving data and passing intent to service
public void startService(int duration)
{
int d = duration;
SharedPreferences sharedPreferences = getSharedPreferences("Timer", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("duration", d);
editor.apply();
Intent intent = new Intent(this,MyService.class);
startService(intent);
}
}
how can I show that timer to my text field? Please help!
you can use LocalBroadcastManager like this :
in your service
private LocalBroadcastManager broadcaster;
#Override
public void onCreate() {
broadcaster = LocalBroadcastManager.getInstance(this);
}
private void sendData(){
Intent intent = new Intent("MyData");
broadcaster.sendBroadcast(intent);
}
and call sendData() wherever you want, and in your activity write
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
/*
this called when app receive notification and MainActivity is opened
* see FcmMessagingService.class to see where it called
*/
#Override
public void onReceive(Context context, Intent intent) {
// Log.d("broadcaster", "onReceive BaseActivity");
// write whatever you want and you cant use intent.getString("key");
}
};
#Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((mMessageReceiver), new IntentFilter("MyData"));
}

Android BroadcastReceiver finish and open activity

I found in the forum, the code that allows me to close all activities and opening another, when the device screen turns off. I stored in a sharedpreference a boolean value which when true, must launch BroadcastReceiver. The problem is that the BroadcastReceiver is launched even when the Boolean value is false.
public class Impostazioni extends AppCompatActivity {
private BroadcastReceiver mReceiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.impostazioni);
Switch swChiusura = (Switch) findViewById(R.id.switch1);
SharedPreferences settings_chiusura = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
boolean vero_falso = settings_chiusura.getBoolean("pref_chiusura_automatica", false);
if(vero_falso){
swChiusura.setChecked(true);
}else{
swChiusura.setChecked(false);
}
swChiusura.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
SharedPreferences settings_percorso = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings_percorso.edit();
prefEditor.putBoolean("pref_chiusura_automatica", true);
prefEditor.apply();
}else{
SharedPreferences settings_percorso = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings_percorso.edit();
prefEditor.putBoolean("pref_chiusura_automatica", false);
prefEditor.apply();
//disable reciver
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
}
});
#Override
protected void onPause() {
super.onPause();
SharedPreferences settings_chiusura = getSharedPreferences(CHIUSURA_AUTOMATICA, Context.MODE_PRIVATE);
boolean vero_falso = settings_chiusura.getBoolean("pref_chiusura_automatica", false);
if (vero_falso) {
/**
* initialize receiver
*/
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a screen state change
Log.e("MYAPP", "SCREEN TURNED OFF");
}
} else {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
mReceiver = null;
}
}
Receiver
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
intent = new Intent(context, Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
}
}
}
This may be a bad solution but, try putting your SharedPreferences boolean into the ScreenReceiver's if block. Because right know, when your screen goes off it works without requiring the boolean value. I mean:
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
if(sharedPref.getBoolean(yourBoolean)){ //...

Android : after changing value of Shared Preference key in service class, it displays default value

After changing value of session key in service class, it displays default value, while calling activity using pendingIntent
0) here is my SharedPreference file
public class SessionCounter {
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "AndroidCounterPref";
private static final String sessionCounter = "session_Counter";
public SessionCounter(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createCounterSession(Integer name){
editor.putInt(sessionCounter, name);
editor.commit();
}
public int getCounterSession(){
int val=pref.getInt(sessionCounter, 0);
return val;
}
}
1) here is my service class CaptureImagesService class
public static int COUNTER=-1;
public int onStartCommand(Intent intent, int flags, int startId){
context=this;
this.startId=startId;
randomTime=getRandom(time_interval) * 30 * 1000 ;
timer1=new Timer();
timer1.schedule(new TimerTask() {
#Override
public void run() {
sessionCounter.createCounterSession(1);
startAlarm();
}
}, randomTime);
return START_STICKY;
}
public void startAlarm()
{
sessionCounter.createCounterSession(1);
manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(CaptureImagesService.this, HomeActivity.class);
alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent=PendingIntent.getActivity(getBaseContext(), 1001, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Log.d("CaptureImagesService", "after pendingIntent");
long whenToTrigger=Calendar.getInstance().getTimeInMillis();
manager.set(AlarmManager.RTC_WAKEUP, whenToTrigger, pendingIntent);
}
2) Here is my MainActivity onResume method where i want to use this value and if value of COUNTER is 1 then perform action
protected void onResume() {
super.onResume();
if(sessionCounter.getCounterSession()==1)
WakeUpDevice();
askForPicture();
//etc
}
}
public void addCall(View v) {
if (sfStore.getString(KEY_CURRENT_CALL_ID, "-1").equalsIgnoreCase("-1")) {
startService(new Intent(getBaseContext(), CaptureImagesService.class));
}
Please help me to solve this issue
I used getBroadcast instead of getActivity
public class CaptureBroadcast extends BroadcastReceiver{
public static boolean counterNew;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
counterNew=true; //and check if counter is true then
// do some code in onResume method of HomeActivity
contextStart=context;
Intent intentHome=new Intent(context, HomeActivity.class);
intentHome.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentHome);
}
}
In HomeActivity onResume
protected void onResume() {
super.onResume();
if(CaptureBroadcast.counterNew==true){
// some code
}
}

show splash screen one time only

I have a radio aac player I added a splash screen at the beginning, but I would like to show it just one time, because if user press back button my app stays on background with a music service playing, but when I go back to the app shows splash screen again. Here is my actual splashscreen code:
public class Inicio extends Activity {
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
Intent i = new Intent(Inicio.this, ScreenTabs.class);
Inicio.this.startActivity(i);
Inicio.this.finish();
}
};
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("first_time", false))
{
/*
// we will set this true when our ScreenTabs activity
ends or the service playing music is stopped.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
*/
Intent i = new Intent(Inicio.this, ScreenTabs.class);
this.startActivity(i);
this.finish();
}
else
{
this.setContentView(R.layout.inicio);
handler.sendEmptyMessageDelayed(0, 2000);
}
}
}
Ondestroy of screentabs.java
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
if(radioService!=null) {
if(!radioService.isPlaying() && !radioService.isPreparingStarted()) {
//radioService.stopSelf();
radioService.stop();
radioService.stopService(bindIntent);
radioService.exitNotification();
}
}
}
What can I change or add in order to show splash screen just first time app is initiated?
public class Inicio extends Activity {
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
Intent i = new Intent(Inicio.this, ScreenTabs.class);
Inicio.this.startActivity(i);
Inicio.this.finish();
}
};
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("first_time", false))
{
/*
// we will set this true when our ScreenTabs activity
ends or the service playing music is stopped.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
*/
Intent i = new Intent(Inicio.this, ScreenTabs.class);
this.startActivity(i);
this.finish();
}
else
{
this.setContentView(R.layout.inicio);
handler.sendEmptyMessageDelayed(0, 2000);
}
Implement onDestory of the ScreenTabs activity and onDestroy method of the service and there
#Override
public void onDestory(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
}
and similarly in onDestory of the service
#Override
public void onDestory(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
}
What we do here that the preference value first_time which checks that Splash should be shown or not is set to true only when the ScreenTabs activity is finished or the music playing service is stopped.
Add a shared preference with Boolean type and make it false and after first time splash page make it true so it will no go inside that method-
On Start Of Actitity-
SharedPreferences sharedPref;
Context context;
boolean isScrennoFill = false;
And below OnCreate()-
context = this;
/**
* get user login preference
*/
sharedPref = context.getSharedPreferences("savecredentails",
MODE_PRIVATE);
isScrennoFill = sharedPref.getBoolean("isScrennoFill", false);
if (isScrennoFill == false) {
Intent intent = new Intent(context,
SplashPage.class);
startActivity(intent);
} else {
Intent intent = new Intent(context,
Next.class);
startActivity(intent);
}
in your AndroidManifest.xml you can use android:noHistory="true" in the activity you want to disable going back to

Categories

Resources