How to keep service alive even when I close the app? - android

I am new to android. I have developed a small chat application, which is having register page, login screen and friendslist screen. When the user register and login, he will be redirected to the friends list page. And it is working good. I used sharedpreference for once the user register second time they directly redirected to the friends list page. But here it is not I close my application.
Can anyone help me?
Thanks in advance.
This is my Registration.java
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
imService = null;
Toast.makeText(SignUp.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_screen);
setTitle("Sign up");
Button signUpButton = (Button) findViewById(R.id.signUp);
Button cancelButton = (Button) findViewById(R.id.cancel_signUp);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
passwordAgainText = (EditText) findViewById(R.id.passwordAgain);
eMailText = (EditText) findViewById(R.id.email);
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
Intent intent = new Intent(this, FriendList.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.putString("username", usernameText.getText().toString());
ed.putString("password", passwordText.getText().toString());
ed.commit();
}
signUpButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
if (usernameText.length() > 0 &&
passwordText.length() > 0 &&
passwordAgainText.length() > 0 &&
eMailText.length() > 0
)
{
if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){
if (usernameText.length() >= 5 && passwordText.length() >= 5) {
Thread thread = new Thread(){
String result = new String();
#Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
handler.post(new Runnable(){
public void run() {
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
/*editor.putString("register","true");
editor.commit();*/
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
startActivity(new Intent (SignUp.this, Login.class));
SignUp.this.finish();
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
//showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
}
}
});
}
};
thread.start();
}
else{
Toast.makeText(getApplicationContext(),R.string.username_and_password_length_short, Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(),R.string.signup_type_same_password_in_password_fields, Toast.LENGTH_LONG).show();
//showDialog(TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS);
}
}
else {
Toast.makeText(getApplicationContext(),R.string.signup_fill_all_fields, Toast.LENGTH_LONG).show();
}
}
});
}
This is Login.java
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
if (imService.isUserAuthenticated() == true)
{
Intent i = new Intent(Login.this, FriendList.class);
startActivity(i);
Login.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Login.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Login.this, IMService.class));
setContentView(R.layout.login_screen);
setTitle("Login");
Button loginButton = (Button) findViewById(R.id.login);
cancelButton = (Button) findViewById(R.id.cancel_login);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
loginButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
if (imService == null) {
Toast.makeText(getApplicationContext(),R.string.not_connected_to_service, Toast.LENGTH_LONG).show();
return;
}
else if (imService.isNetworkConnected() == false)
{
Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();
}
else if (usernameText.length() > 0 &&
passwordText.length() > 0)
{
Thread loginThread = new Thread(){
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(usernameText.getText().toString(), passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null || result.equals(AUTHENTICATION_FAILED))
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();
}
});
}
else {
handler.post(new Runnable(){
public void run() {
Intent i = new Intent(Login.this, FriendList.class);
//i.putExtra(FRIEND_LIST, result);
startActivity(i);
Login.this.finish();
}
});
}
}
};
loginThread.start();
}
else {
Toast.makeText(getApplicationContext(),R.string.fill_both_username_and_password, Toast.LENGTH_LONG).show();
}
}
});
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
imService.exit();
finish();
}
});
}

Maybe the 'foreground' service is what you want.
http://developer.android.com/guide/components/services.html#Foreground
A foreground service is a service that's considered to be something
the user is actively aware of and thus not a candidate for the system
to kill when low on memory. A foreground service must provide a
notification for the status bar, which is placed under the "Ongoing"
heading, which means that the notification cannot be dismissed unless
the service is either stopped or removed from the foreground.
For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware
of its operation...

Related

Delay application close and make an send a message

Actually i have a TCP Client that onStart connect to the server and send the device IP and number to it, but now i want that when the application is getting closed ( onDestroy ) delay it for some seconds ( the right time to reopen the connection and send another message ) and send another message in which i'm saying that the device is offline.
I've tryed to do it onDestroy method but probably it's madness and obviously
that didn't worked ( i tryed to do the following stuff onDestroy :
protected void onDestroy() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage(trm + "OFFLINE");
}
if (client != null) {
client.stopClient();
}
super.onDestroy();
server.onDestroy();
}
Here is my MainActivity code where i evocate the TCP Client and sending start message:
public class MainActivity extends AppCompatActivity {
Server server;
static Client client;
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
static TextView msgServer;
static String ipp;
static String trm;
static DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
msgServer = (TextView) findViewById(R.id.serverMSG);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
startService(new Intent(MainActivity.this,FinalizingOperationsService.class));
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
startConnection.postDelayed(runnableConnection,5000);
startMessage.postDelayed(runnableMessage,5500);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public static class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
msgServer.setTextColor(Color.parseColor("#00FF00"));
msgServer.setText("ONLINE");
Log.d("test", "response " + values[0]);
}
}
static Handler startConnection = new Handler();
static Runnable runnableConnection = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
}
};
static Handler startMessage = new Handler();
static Runnable runnableMessage = new Runnable() {
#Override
public void run() {
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
if (client != null) {
client.sendMessage(ipp + "#" + trm);
}
}
};
static Handler startMessageClose = new Handler();
static Runnable runnableMessageClose = new Runnable() {
#Override
public void run() {
if (client != null) {
client.sendMessage(trm + "IS OFFLINE");
}
}
};
}
The right command for open the connection is new ConnectTask().execute("");
while i'm sending the message with if (client != null) { client.sendMessage(ipp + "#" + trm); }
FinalizingOperationsService.java code:
public class FinalizingOperationsService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("FOService", "Service Started");
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("FOService", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("FOService", "Service Ends");
MainActivity.startConnection.removeCallbacks(MainActivity.runnableConnection);
MainActivity.startConnection.postDelayed(MainActivity.runnableConnection,100);
MainActivity.startMessageClose.removeCallbacks(MainActivity.runnableMessageClose);
MainActivity.startMessageClose.postDelayed(MainActivity.runnableMessageClose,110);
stopSelf();
}
}
Create a new service like this,
public class FinalizingOperationsService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("FOService", "Service Started");
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("FOService", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("FOService", "Service Ends");
// write server updation code here
// after completing code perform stopself() to stop this service;
}
}
And define this service in manifest file like this,
<service android:name=". FinalizingOperationsService" android:stopWithTask="false"/>
Finally start service in onCreate method of your main activity
startService(newIntent(getContext(),FinalizingOperationsService.class));
Explanation:
onTaskRemoved() method of the service is called when application is killed or destroyed, so in this method you can perform your final operations to notify server and stop your service after operations done. Hope it will help you.

How to run countdown timer in background

I'm doing a project that need countdown timer to limit time for 1 hour.
I have coded this but the countdown timer goes to start at begin every time that I refresh activity.
How should I do.
Here is my code
new CountDownTimer(3600000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
mTimer.setText("" + String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
}
#Override
public void onFinish() {
mTimer.setText("");
unlock();
mStatus.setTextColor(Color.parseColor("#f9d540"));
}
}.start();
Thank you :)
These are my activity codes. I have tried to do it in AsyncTask (just only //waiting)
String ipParse;
long CountTimer;
TextView mName,mUsername,mLicense,mLot,mStatus, mDate, mPayment, mTel,mTimer,mconfirm;
ImageView imageView,Ask;
Button unlock, layout, logout;
private String login_name, user_license, lot_lot;
private IPManager ipManager;
private LoginManager loginManager;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginManager = new LoginManager(this);
ipManager = new IPManager(this);
ipParse = ipManager.Read_ip();
login_name = getIntent().getStringExtra("username");
user_license = getIntent().getStringExtra("license");
lot_lot = getIntent().getStringExtra("lot");
mName = (TextView) findViewById(R.id.name);
mUsername = (TextView) findViewById(R.id.user_username);
mLicense = (TextView) findViewById(R.id.license_user);
mLot = (TextView) findViewById(R.id.yourlot);
mStatus = (TextView) findViewById(R.id.status_parking);
mDate = (TextView) findViewById(R.id.date);
mPayment = (TextView) findViewById(R.id.payment);
mTel = (TextView) findViewById(R.id.tel);
mTimer = (TextView) findViewById(R.id.Timer);
mconfirm = (TextView) findViewById(R.id.confirmation);
imageView = (ImageView) findViewById(R.id.pic_parking);
Ask = (ImageView) findViewById(R.id.pic_Ask);
unlock = (Button) findViewById(R.id.button_unlock);
layout = (Button) findViewById(R.id.layout_building);
logout = (Button) findViewById(R.id.log_out);
unlock.setVisibility(View.GONE);
PostFunction postM =new PostFunction();
//Check Status
try {
String resp = postM.postCheck2a(ipParse, user_license, lot_lot);
JSONObject object = new JSONObject();
try {
object = new JSONObject(resp);
int status = object.getInt("status");
int status_2a = object.getInt("status_2a");
//waiting
if (status == 0 && status_2a == 1){
unlock.setVisibility(View.VISIBLE);
Ask.setVisibility(View.GONE);
mconfirm.setText("time for confirmation");
mStatus.setTextColor(Color.parseColor("#20b2aa"));
new UpdateCountdownTask().execute();
}
//wrong lot!!!!
else if (status == 0 && status_2a == 2){
unlock.setVisibility(View.VISIBLE);
Ask.setVisibility(View.GONE);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" Smart Parking");
alertDialog.setMessage(" Wrong lot!! please go to your lot....");
alertDialog.show();
TextView textView = (TextView) alertDialog.findViewById(android.R.id.message);
textView.setTextSize(25);
textView.setTextColor(Color.RED);
mStatus.setTextColor(Color.RED);
Ask.setVisibility(View.GONE);
}
//Parking
else if (status == 0 && status_2a == 3){
unlock.setVisibility(View.VISIBLE);
Ask.setVisibility(View.GONE);
mStatus.setTextColor(Color.parseColor("#0dce5e"));
}
// getting out
else if (status == 0 && status_2a == 4){
mStatus.setTextColor(Color.parseColor("#f9d540"));
}
else if (status == 1) {
Toast.makeText(MainActivity.this, "Sorry the connection failed......" , Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
//show User info
try {
String resp = postM.postMain(ipParse,login_name);
JSONObject object = new JSONObject();
try {
object = new JSONObject(resp);
int status = object.getInt("status");
if (status == 0) {
mName.setText(object.getString ("name"));
mUsername.setText(object.getString("username"));
mLicense.setText(object.getString("license"));
mLot.setText(object.getString("lot"));
mStatus.setText(object.getString("user_status"));
mDate.setText(object.getString("date"));
mPayment.setText(object.getString("payment"));
mTel.setText(object.getString("tel"));
} else if (status == 1) {
Toast.makeText(MainActivity.this, "Sorry something wrong..." , Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
Ask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AskFloor.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("username", login_name);
intent.putExtra("license", user_license);
intent.putExtra("lot", lot_lot);
startActivity(intent);
}
});
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Layout.class);
startActivity(intent);
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginManager.remove_ExistLogin();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
unlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unlock();
}
});
}
public void unlock(){
PostFunction postM =new PostFunction();
try {
String resp = postM.postUnlock(ipParse ,login_name, user_license);
JSONObject object = new JSONObject();
try {
object = new JSONObject(resp);
int status = object.getInt("status");
if (status == 0) {
Toast.makeText(MainActivity.this, "UNLOCKED! thank you for coming......", Toast.LENGTH_LONG).show();
Intent intent = getIntent();
startActivity(intent);
finish();
} else if (status == 1) {
Toast.makeText(MainActivity.this, "UNLOCK FAILED...", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class UpdateCountdownTask extends AsyncTask<Long, Long, Void> {
#Override
protected Void doInBackground(Long... millisUntilFinished) {
CountDownTimer myCounter = new CountDownTimer(3600000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
publishProgress(millisUntilFinished);
}
#Override
public void onFinish() {
mTimer.setText("");
unlock();
mStatus.setTextColor(Color.parseColor("#f9d540"));
}
};
myCounter.start();
return null;
}
#Override
protected void onProgressUpdate(Long... millisUntilFinished) {
super.onProgressUpdate(millisUntilFinished);
long millis = millisUntilFinished[0];
mTimer.setText("" + String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mTimer.setText("");
}
}
}
Creating CountDown Timer :
Use Static variables so that it will not start as your Activity loads again as :
static long v1=60000;
static long v2=1000;
new CountDownTimer(v1, v2) {
public void onTick(long millisUntilFinished) {
/*for one second*/
textViewFacebook.setText("seconds remaining: " + millisUntilFinished / v2);
//here you can have your logic to set text to edittext
}
public void onFinish() {
textViewFacebook.setText("done!");
}
}.start();
Just put this code inside AsyncTask backgroud event to run it in background.

Exit from application from home screen and close it

I want to close my application from splash screen automatically after showing an message if there is no internet connection available or any error occurs due to response error. My code closes the application but cant close the splash screen.Times of India(TOI) application does like this. How to implement this feature.
my splash screen activity is like this..
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 8000;
static String MENU = null;
ArrayList<String> ls = new ArrayList<String>();
private String[] categoryType;
private boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// requesting data for menu items in navigation drawer
String url = "http://guwahatinow.com/?json=get_category_index";
if (isOnline()) {
JsonObjectRequest jsonObjReqMenu = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayMenu= response.getJSONArray("categories");
Log.d("request", "menu");
int loop;
ls.add("Top Stories");
for (loop = 0; loop <jsonArrayMenu.length() ; loop++) {
JSONObject jsonObj = (JSONObject) jsonArrayMenu.get(loop);
String category =jsonObj.getString("title") ;
//menu.add(category);
ls.add(loop+1, category);
Log.d("menu added", category);
Log.d("element in ls", ls.get(loop));
}
ls.add("Exit");
int i = ls.size();
categoryType = new String[i];
for (int j = 0; j < i; j++) {
categoryType[j] = ls.get(j);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Please check your internet connection and try again...", Toast.LENGTH_LONG).show();
VolleyLog.d("menu error", "Error: " + error.getMessage());
flag = false;
//finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
//System.exit(0);
}
});
RequestQueue menuQueue = Volley.newRequestQueue(this);
menuQueue.add(jsonObjReqMenu);
if (flag) {
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
Log.d("main activity called", "true");
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
} else {
Toast.makeText(getApplicationContext(), "Internet connection error...", Toast.LENGTH_LONG).show();
finish();
System.exit(0);
}
/*new Handler().postDelayed(new Runnable() {
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
Log.d("main activity called", "true");
// close this activity
finish();
}
}, SPLASH_TIME_OUT);*/
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Calling the finish() method on an Activity when there is no connection available in your case or any other at where you want to close app.
In you major else block of if block for checking internet call finish() method. eg
You have you code as
if (isOnline()) {
// your Code for calling API and starting timer
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
}
Change it to
if (isOnline()) {
// your Code for calling API and starting timer
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
finish();
}
Hi please replace your code with below code where you used handler thread
CountDownTimer m_countDownTimer;
m_countDownTimer = new CountDownTimer(8000,1000) {
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
if(!isFinishing())
{
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
finish();
}
}
}.start();
Cancel CountDownTimer object in OnDestroy()
#Override
protected void onDestroy()
{
if(m_countDownTimer != null)
{
m_countDownTimer.cancel();
}
super.onDestroy();
}

Automatic Login Always Returns Null

At present, the login of my app prompts a user with an input for username and password and then submission of a button to send the info to the service and my server:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
if (imService.isUserAuthenticated() == true) {
Intent i = new Intent(LoggingIn.this, MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
/*
* Start and bind the imService
*/
startService(new Intent(LoggingIn.this, MessagingService.class));
usernameText = (EditText) findViewById(R.id.username);
passwordText = (EditText) findViewById(R.id.password);
loginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (imService == null) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_service,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_SERVICE);
return;
} else if (imService.isNetworkConnected() == false) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_network,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_NETWORK);
} else if (usernameText.length() > 0
&& passwordText.length() > 0) {
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
usernameText.getText().toString().trim(),
passwordText.getText().toString().trim());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null
|| result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
/*
* if result not equal to authentication failed,
* result is equal to friend and group list of
* the user 0: is for friends, 1: is for groups
*/
handler.post(new Runnable() {
public void run() {
// If log in successful, then save
// username and password to shared
// preferences:
SaveSharedPreference.setUserName(
getApplicationContext(),
usernameText.getText()
.toString());
SaveSharedPreference.setPassword(
getApplicationContext(),
passwordText.getText()
.toString());
Intent i = new Intent(LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
} else {
/*
* Username or Password is not filled, alert the user
*/
Toast.makeText(getApplicationContext(),
R.string.fill_both_username_and_password,
Toast.LENGTH_LONG).show();
// showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
}
}
});
Which works just fine. What I wish to implement is the automatic login of a user given they have already logged in and thus the username and password is stored in shared preferences.
So when they access the app again, it should auto log them in as:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
if (imService.isUserAuthenticated() == true) {
Intent i = new Intent(LoggingIn.this, MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
startService(new Intent(LoggingIn.this, MessagingService.class));
final String userName = SaveSharedPreference.getUserName(getApplicationContext());
final String password = SaveSharedPreference.getPassword(getApplicationContext());
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
userName.trim(),
password.trim());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null
|| result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
handler.post(new Runnable() {
public void run() {
Intent i = new Intent(LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
The users info is successfully stored in shared preferences, but upon executing this code block, it always returns NullPointerException on line:
result = imService.authenticateUser(
userName.trim(),
password.trim());
In the try {} catch block.
I have attempted placing a timer within the app that perhaps the service does not have time to boot up, but even after 20+ sec that still does not work.
How can I get the automatic login work and not return?
UPDATE NOTE: private Manager imService; is an interface as:
public interface Manager {
public boolean isNetworkConnected();
public boolean isUserAuthenticated();
}

User automatic log in with SaveSharedPreference -- InvocationTarget and NullPointer Exceptions

I am using Androids SaveSharedPreference to allow a user to auto login once they already logged in previously. For a user to gain access, their login information must be sent to my server using webscokets, and once a connection is made they will be able to access their accounts.
In terms of present functionality, the users can log into the app the first time and use all the features. The problem arises as the user closes out, not logs out, and attempts to access again and the error below is thrown and the app crashes:
and then
I have seen that the NullPoint error on line 207 of LoggingIn is at:
result = imService.authenticateUser(
SaveSharedPreference
.getUserName(getApplicationContext()),
SaveSharedPreference
.getPassword(getApplicationContext()));
The remaining code of the class in the onCreate method of the LoggingIn class called once app starts:
protected static final int NOT_CONNECTED_TO_SERVICE = 0;
protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
public static final String AUTHENTICATION_FAILED = "0";
public static final String FRIEND_LIST = "FRIEND_LIST";
protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
protected static final int NOT_CONNECTED_TO_NETWORK = 3;
private EditText usernameText;
private EditText passwordText;
private Manager imService;
public static final int SIGN_UP_ID = Menu.FIRST;
public static final int EXIT_APP_ID = Menu.FIRST + 1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
imService = ((MessagingService.IMBinder) service).getService();
if (imService.isUserAuthenticated() == true) {
// Intent i = new Intent(LoggingIn.this, ListOfFriends.class);
Intent i = new Intent(LoggingIn.this, MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
imService = null;
Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* Start and bind the imService
*/
startService(new Intent(LoggingIn.this, MessagingService.class));
setContentView(R.layout.loggin_in);
setTitle("Login");
ImageButton loginButton = (ImageButton) findViewById(R.id.button1);
usernameText = (EditText) findViewById(R.id.username);
passwordText = (EditText) findViewById(R.id.password);
// If not logged in already
if (SaveSharedPreference.getUserName(getApplicationContext()).length() == 0) {
loginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (imService == null) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_service,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_SERVICE);
return;
} else if (imService.isNetworkConnected() == false) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_network,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_NETWORK);
} else if (usernameText.length() > 0
&& passwordText.length() > 0) {
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
usernameText.getText().toString(),
passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null
|| result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
/*
* if result not equal to authentication
* failed, result is equal to friend and
* group list of the user 0: is for friends,
* 1: is for groups
*/
handler.post(new Runnable() {
public void run() {
// If log in successful, then save
// username and password to shared
// preferences:
SaveSharedPreference.setUserName(
getApplicationContext(),
usernameText.getText()
.toString());
SaveSharedPreference.setPassword(
getApplicationContext(),
passwordText.getText()
.toString());
Intent i = new Intent(
LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
} else {
/*
* Username or Password is not filled, alert the user
*/
Toast.makeText(getApplicationContext(),
R.string.fill_both_username_and_password,
Toast.LENGTH_LONG).show();
// showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
}
}
});
} else {
// If already logged in, pull the information and send to server to
// auto log in
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
SaveSharedPreference
.getUserName(getApplicationContext()),
SaveSharedPreference
.getPassword(getApplicationContext()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null || result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
/*
* if result not equal to authentication failed, result
* is equal to friend and group list of the user 0: is
* for friends, 1: is for groups
*/
handler.post(new Runnable() {
public void run() {
Intent i = new Intent(LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
}
}
How can I allow the users to automatically login with my service successfully?

Categories

Resources