How to start activity as its first created - android

How to start same activity again as its created first time. I used INTET to start activity again . but If user press home button at mobile this intent not works . is there anyother way to startactivity as its first created when its in background. Pls help this I shall be very thankful to you for this.
private void sendNextMessage(){
Log.i("Is there are sms sendNextMessage", thereAreSmsToSend()+"");
if(thereAreSmsToSend()){
Log.i("sendNextMessage mMessageSentParts", mMessageSentParts+"");
Log.i("sendNextMessage mMessageSentTotalParts", mMessageSentTotalParts+"");
Log.i("sendNextMessage mMessageSentCount", mMessageSentCount+"");
Log.i("sendNextMessage Phone list", list_phone.get(mMessageSentCount)+"");
sendSMS(list_phone.get(mMessageSentCount),list_MESSAGE_BODY.get(mMessageSentCount));
}else{
Toast.makeText(getBaseContext(), "All SMS have been sent",
Toast.LENGTH_SHORT).show();
new AddNewCategory().execute();
h.removeCallbacks(r);
h.postDelayed(new Runnable() {
public void run() {
// I used this code to start activity again but if user press home button this intent not works .
Intent i = new Intent();
i.setClass(MainActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
Log.e("Time", "60000 intent");
h.removeCallbacks(r);
}
}, 30000);
h.removeCallbacks(r);
h.removeCallbacks(r);
}
}

How about using the SharedPreferences with a boolean value;
Make a class for this:
private Context context;
public boolean saveFirsTime(boolean firstime)
{
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("FirstTime", firstime);
return editor.commit();
}
public boolean loadFirsTime() {
SharedPreferences sharedPreferences = getSharedPreferences();
boolean firstimeMap = sharedPreferences.getBoolean("FirstTime", true);
return firstimeMap;
}
public boolean clearFirsTime() {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("FirstTime");
return editor.commit();
}
private SharedPreferences getSharedPreferences() {
return context.getSharedPreferences("SharedPrefereneces",Context.MODE_PRIVATE);
}
And then implement saveFirstTime(false) in your Activity onCreate();

Write a service and broadcast receiver something like below :
This Activity start activity on reboot similarly u can write ur event on which activity is called :
public class BootStartUpReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// Start Service On Boot Start Up
Intent service = new Intent(context, TestService.class);
context.startService(service);
//Start App On Boot Start Up
Intent App = new Intent(context, MainActivity.class);
App.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(App);
}
}

Related

How to stop service from logout button?

Hello I am building an app where I am using service for locations. That service have to work all the time, so I set that when service goes to onDestroy, then intent is sent to BroadcastReceiver who starts service again, and on that way, my service always works. But I want to stop service when user click on button logout. How to prevent that,when service goes to onDestroy, don't send intent to broadcast(but only when user clicks on logout)?
This is my logout from MainActivity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_log_out) {
if (isNetworkConnected()) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "Logout!");
Log.d("MAIN_ACTIVITY " , "Internet access ");
}
else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.need_internet), Toast.LENGTH_SHORT).show();
}
}
These are methods onStartCommand, onCreate and onDestroy in location service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand" , "LocationService");
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
isEnded = false;
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
Bugsnag.init(this, BUGSNAG_API_KEY);
buildGoogleApiClient();
Log.d("onCreateService", "onCreateService");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "onDestroy!");
timeWhenServiceDestroyed = DateFormat.getTimeInstance().format(new Date());
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.user_location), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("onDestroyService", timeWhenServiceDestroyed);
editor.apply();
stopLocationUpdates();
Log.d("onDestroyService", "onDestroy: + " + timeWhenServiceDestroyed);
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
And this is my BroadCastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LocationServiceRestartBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, LocationService.class));
}
How to prevent that when user clicks on logout button, my service don't create again? Thanks in advance.
You could use static boolean variable shouldRestart that is false only when logout button is clicked, otherwise true.
Add to your activity :
public static boolean shouldRestart=true;
Add to your "logout button click event" this line:
shouldRestart=false;
And add this lines in onDestroy method of service :
if (MainActivity.shouldRestart){
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
MainActivity.shouldRestart=true;

Android SharedPreferences value not update in BroadcastReceiver

I create a SharedPreferences called ALARM with a map called ("alarm",boolean), ("alarm",boolean)'s boolean value changed time to time in MainActivity, and received in a BroadcastReceiver.
The problem is: when I change the value in MainActivity time to time, BroadcastReceiver only change once. What's wrong with my code?
In below code, the start() align to a button, when clicked, change boolean to true. I can see a true value received in the BroadcastReceiver as well. But then I click the stop(), boolean change to false in MainActivity, but still see a true value received in BroadcastReceiver.
If I click stop() first, then I always see false value in BroadcastReceiver.(even I click start() many time)
Thanks.
MainActivity:
public class MainActivity extends AppCompatActivity {
SharedPreferences ALARM;
SharedPreferences.Editor editorALARM;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ALARM = getSharedPreferences("ALARM", MODE_PRIVATE);
editorALARM = ALARM.edit();
}
// start data service
public void start(View view) {
editorALARM.putBoolean("alarm", true).apply();
Log.e("start",""+ALARM.getBoolean("alarm", false));
Intent intent = new Intent();
intent.setAction("xxx.ALARM");
sendBroadcast(intent);
}
// stop data service
public void stop(View view) {
editorALARM.putBoolean("alarm", false).apply();
Log.e("stop",""+ALARM.getBoolean("alarm", true));
Intent intent = new Intent();
intent.setAction("xxx.ALARM");
sendBroadcast(intent);
}
}
BroadcastReceiver:
public class Receiver extends BroadcastReceiver {
SharedPreferences ALARM;
#Override
public void onReceive(Context context, Intent intent) {
ALARM = context.getSharedPreferences("ALARM", Activity.MODE_PRIVATE);
Log.e("actual",""+ALARM.getBoolean("alarm", false));
}
}
It is due to the android: process =":remote" in manifests.xml, after remove it. I got correct boolean.
replace-
editorALARM.putBoolean("alarm", true).apply();
with-
editorALARM.putBoolean("alarm", true).commit();
will work for you

registerOnSharedPreferenceChangeListener Stops getting called after some time

I have a sharedPreference that that gets updated continuously (around every second)from a Class which extends BroadcastReceiver.
The first few times, the registerOnSharedPreferenceChangeListener gets called, but after a while, it stops getting called(I dont even press any button on my emulator).
I know that the sharedPreference is still getting updated because I have seen my log. It is a problem with the registerOnSharedPreferenceChangeListener.
This is the code for the listener(using the suggestion from here)
My shared preference is getting updated almost once every second.
Here is the code for my listener:
SharedPreferences.OnSharedPreferenceChangeListener listener=new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if(key=="TIME")
{
Log.v("Tagger","Value has changed");
long L=-2;
if(sharedPreferences.contains("TIME"))
{
L=sharedPreferences.getLong("TIME", 0);
long HH=(L/1000)/3600;
long MM=((L/1000)/60)%60;
long SS=(L/1000)%60;
MILLIS-=1000;
mainHH.setText(Long.toString(HH));
mainMM.setText(Long.toString(MM));
mainSS.setText(Long.toString(SS));
}
if(L<=0)
{
Editor edit=sharedPreferences.edit();
edit.remove("TIME");
edit.commit();
Log.v("VALUE",Long.toString(454L));
Intent intent = new Intent(getApplicationContext(), TimerAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
TimerAlarmReceiver.alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
TimerAlarmReceiver.alarmMgr.cancel(pendingIntent);
start.setText("Start the Test?");
TimerOn=false;
edit.putBoolean("TimerOn", TimerOn);
edit.commit();
}
}
}};
sharedPreferences.registerOnSharedPreferenceChangeListener(listener);
I have provided the full code because something else might be the problem.
EDIT::
here is my BroadcastReceiver class
public class TimerAlarmReceiver extends BroadcastReceiver {
public static long TIME;
public static Boolean TimerOn=false;
public static AlarmManager alarmMgr ;
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
/* SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.commit();*/
SharedPreferences time = PreferenceManager
.getDefaultSharedPreferences(context);
long T = time.getLong("TIME",594554L);
Editor editor=time.edit();
editor.putLong("TIME", T-1000);
editor.commit();
Log.v("Tag", Long.toString(T));
//this gets updated and i can see the new values of T
}
public static void setTime(long T)
{
TIME=TimerActivity.DMILLIS;
}
}
OnSharedPreferenceChangeListeners are registered via weak reference. Make sure you keep a reference to the listener by setting it to an instance variable.

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

How to get arguments for starting a service after device has been started?

I'm trying to start a service after the device has been started. The problem is that the service needs some arguments which it normally gets this way:
public class ServiceClass extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
searchString = (String) intent.getExtras().get(GET_SEARCHSTRING_AFTER_START);
[...]
return START_STICKY;
public static final String GET_SEARCHSTRING_AFTER_START = "SEARCHVALUE";
public class OnStartupStarter[...]
}
But when the service should be started via a BroadcastReceiver when the device has started I can't put the searchString because this is given by an activity. When the service starts after the device has been started the service should start with the searchString it had before the device was turned off.
The BroadcastReceiver is a subclass from the service's class:
public static class OnStartupStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/* TODO: Start the service with the searchString it
* had before the device has been turned off...
*/
}
}
Normally the service is started like this:
private OnCheckedChangeListener ServiceSwitchCheckedStatusChanged
= new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Intent s = new Intent(getBaseContext(), ServiceClass.class);
s.putExtra(ServiceClass.GET_SEARCHSTRING_AFTER_START, <ARGUMENT>);
if(isChecked)
startService(s);
else
stopService(s);
}
};
Save last search string in SharedPreference in activity onPause method, retrieve last search string when you receive BootCompleted broadcast and start your service as usually.
Activity:
protected void onPause() {
super.onPause();
SharedPreferences pref = getSharedPreferences("my_pref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("last_search", mLastSearch);
editor.commit();
}
BroadcastReceiver:
public static class OnStartupStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
SharedPreferences pref = context.getSharedPreferences("my_pref", MODE_PRIVATE);
String lastSearch = pref.getString("last_search", null);
if (lastSearch != null) {
// TODO: Start service
}
}
}
}

Categories

Resources