error launching application for second time - android

I have this error i try to do a lot of things but i can't find the solution, when i start the application the first time i got the login activity and work fine, i close the application and start again, then the application crash, this is stack trace:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.app.Application.getApplicationContext()' on a null object reference
at com.rrms.jrperera.rapidsentry.poco.AppManager.isConnected(AppManager.java:70)
at com.rrms.jrperera.rapidsentry.activities.MainActivity.CheckInternetConnection(MainActivity.java:54)
at com.rrms.jrperera.rapidsentry.activities.MainActivity.HandleSignIn(MainActivity.java:61)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4015)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
When i start the application from android studio this problem doesn't happen.
When i start the application in some point i start a service that it is running in background, the code for the methods: isConnected and CheckInternetConnection is implementing in a separate class that i'm using to manage all the application:
public class AppManager {
public static final String SESSION_DATA = "com.rrms.jrperera.rapidsentry.MiOSSession";
public static final String SERVICEURL = "https://xxxxxxx.com/RapidSentry/MiOSService.svc";//https://xxxxxxx.com/RapidSentry/MiOSService.svc//http://10.10.20.137/RapidMiOSApi/MiOSService.svc
private static AppManager manager = null;
private static Application application;
private Boolean isServiceRunning = null;
protected AppManager(Application app) {
this.setApplication(app);
}
public static AppManager getManager(Application app) {
if (manager == null) {
manager = new AppManager(app);
}
return manager;
}
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}
public boolean isConnected() {
boolean connected = true;
ConnectivityManager connMgr = (ConnectivityManager)
getApplication().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
connected = true;
return connected;
}
}
When the application crash i start again the application and again work fine.
Please any idea of what is going on with that?
this is the activity code:
public class MainActivity extends AppCompatActivity {
protected AppManager manager = null;
protected EditText tbLoginUser = null;
protected EditText tbLoginPassword = null;
protected CheckBox cbLoginSaveCredentials = null;
protected ProgressBar pbLogin = null;
protected Button btSignIn = null;
protected Identity myIdentiy = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isMyServiceRunning();
tbLoginUser = (EditText) findViewById(R.id.tb_login_user);
tbLoginPassword = (EditText) findViewById(R.id.tb_login_password);
pbLogin = (ProgressBar) findViewById(R.id.loginProgressBar);
pbLogin.setVisibility(View.INVISIBLE);
btSignIn = (Button) findViewById(R.id.bt_login_signin);
cbLoginSaveCredentials = (CheckBox) findViewById(R.id.cb_login_save_credential);
manager = AppManager.getManager(getApplication());
if (manager.fileExistance("rapid-sentry-identity.txt")) {
pbLogin.setVisibility(View.VISIBLE);
new GetIdentityFile().execute();
}
}
private boolean CheckInternetConnection() {
manager = AppManager.getManager(getApplication());
boolean isConnected = false;
isConnected = manager.isConnected();
return isConnected;
}
public void HandleSignIn(View view) {
pbLogin.setVisibility(View.VISIBLE);
manager = AppManager.getManager(getApplication());
if (!CheckInternetConnection()) {
Toast.makeText(manager.getApplication().getApplicationContext(), R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
String user = tbLoginUser.getText().toString();
String password = tbLoginPassword.getText().toString();
new Login().execute(user, password);
}
}
private void SaveSharePreferences() {
manager.SaveSharedIdentityObject(myIdentiy);
}
private class Login extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = null;
try {
Identity identity = manager.VerifyLogin(params[0], params[1]);
myIdentiy = identity;
} catch (Exception ex) {
result = null;
}
return result;
}
#Override
protected void onPostExecute(String result) {
pbLogin.setVisibility(View.INVISIBLE);
if (cbLoginSaveCredentials.isChecked()) {
new SaveIdentityFile().execute(myIdentiy.getIdentityUser(), myIdentiy.getIdentityPassword());
}
if (myIdentiy == null) {
Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
tbLoginUser.startAnimation(shake);
tbLoginPassword.startAnimation(shake);
Toast.makeText(manager.getApplication().getApplicationContext(), R.string.login_error_login, Toast.LENGTH_SHORT).show();
} else {
SaveSharePreferences();
pbLogin.setVisibility(View.INVISIBLE);
Intent intentGateway = new Intent(getApplication(), GatewayActivity.class);
startActivity(intentGateway);
}
}
}
private class GetIdentityFile extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
String[] ident;
try {
ident = manager.RetrieveIdentityFromFile();
} catch (FileNotFoundException ex) {
ident = null;
}
return ident;
}
#Override
protected void onPostExecute(String[] aVoid) {
if (aVoid != null) {
new Login().execute(aVoid[0], aVoid[1]);
}
}
}
private class SaveIdentityFile extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
manager.SaveIdentityFile(params[0], params[1]);
} catch (FileNotFoundException ex) {
return null;
}
return null;
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ((UpdateShareDataService.class).getName().equals(service.service.getClassName())) {
Intent intentService = new Intent(getApplicationContext(), UpdateShareDataService.class);
stopService(intentService);
return true;
}
}
return false;
}
}

I have the answer for this problem, i was running a service in background pooling data, but in this service i was using the application context, when the application was close the service was restarting several times. The solution was call the method onDestroy() of every activity to be sure that when you close the application the service will destroy too using stopService. Thanks to all!!
#Override
protected void onDestroy() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ((UpdateShareDataService.class).getName().equals(service.service.getClassName())) {
Intent intentService = new Intent(getApplicationContext(), UpdateShareDataService.class);
stopService(intentService);
}
}
refreshData.cancel();
super.onDestroy();
}

Related

Service still running despite the App is killed

I am trying to understand the difference bwtettn STICKY and NOT_STICKY intent of a service in onStartCommand().
I created the MainActivity and the Service shown in the code below. I expected when I press the button mBtnStopApp, the onDestroy() wil be called and then
I should receive this log ** Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS NOT RUNNING ++++++++")); **
because onStartCommand() returns NOT_STICKY intnet which means, when the App is killed, the service should also be stopped
but that never happens.
what happens is, when i press the button mBtnStopApp, the App is finished but i receive the following log:
** Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS RUNNING ++++++++")); **
please let me know why the service is still running despite it returns START_NOT_STICKY and the App was killed
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView mTv = null;
private Button mBtnStartStickyService = null;
private Button mBtnStartNonStickyService = null;
private Button mBtnStopApp = null;
private Button mBtnStopNonStickyService = null;
private Button mBtnStopStickyService = null;
private ServicesUtils mServiceUtils = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.w(TAG, SubTag.bullet("#onCreate"));
this.mServiceUtils = new ServicesUtils(this);
this.mBtnStartNonStickyService = (Button) findViewById(R.id.btnNonStickyService);
this.mBtnStartStickyService = (Button) findViewById(R.id.btnStickyService);
this.mBtnStopApp = (Button) findViewById(R.id.btnStopApp);
this.mBtnStopNonStickyService = (Button) findViewById(R.id.btnStopNonStickyService);
this.mBtnStopStickyService = (Button) findViewById(R.id.btnStopStickyService);
this.mTv = (TextView) findViewById(R.id.tv);
this.mBtnStartNonStickyService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ComponentName componentName = startService(setRunningStateForService(NonStickyService.class, "start"));
Log.i(TAG, "#mBtnStartNonStickyService: componentName: " + componentName);
}
});
this.mBtnStopNonStickyService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ComponentName componentName = startService(setRunningStateForService(NonStickyService.class, "stop"));
Log.i(TAG, "#mBtnStopNonStickyService: componentName: " + componentName);
}
});
this.mBtnStopApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private Intent setRunningStateForService(Class<NonStickyService> serviceClass, String state) {
Log.w(TAG, SubTag.bullet("#setRunningStateForService"));
Intent intent = new Intent(this, serviceClass);
intent.putExtra("running", state);
return intent;
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.w(TAG, SubTag.bullet("#onDestroy"));
if (this.isNonStickyServiceRunning()) {
Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS RUNNING ++++++++"));
} else {
Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS NOT RUNNING ++++++++"));
}
}
private boolean isNonStickyServiceRunning() {
ActivityManager manager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (NonStickyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
code:
public class NonStickyService extends Service {
private static final String TAG = NonStickyService.class.getSimpleName();
private HeavyWorkRunnable mHeavyWorkRunnable = null;
private String running = null;
#Override
public void onCreate() {
super.onCreate();
Log.w(TAG, SubTag.bullet("#onCreate"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, SubTag.bullet("#onStartCommand"));
running = intent.getStringExtra("running");
if (running != null && !running.isEmpty() && running.equals("start")) {
this.StartHeavyWorkThread();
}
return Service.START_NOT_STICKY;
}
private void StartHeavyWorkThread() {
Log.w(TAG, SubTag.bullet("#StartHeavyWorkThread"));
this.mHeavyWorkRunnable = new HeavyWorkRunnable();
new Thread(this.mHeavyWorkRunnable).start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.w(TAG, SubTag.bullet("#onBind"));
return null;
}
#Override
public void onDestroy() {
Log.w(TAG, SubTag.bullet("#onDestroy"));
super.onDestroy();
this.running = "stop";
}
class HeavyWorkRunnable implements Runnable {
int counter = 0;
private Bundle b = null;
public void run() {
Log.w(TAG,SubTag.bullet("#HeavyWorkRunnable"));
while(running.equals("start")) {
b = new Bundle();
b.putInt("what", ++counter);
Log.w(TAG,SubTag.bullet("#HeavyWorkRunnable: counter: " + counter));
Log.w(TAG,SubTag.bullet("#HeavyWorkRunnable: b.getInt('what'): " + b.getInt("what")));
Message msg = handler.obtainMessage();
msg.setData(b);
handler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i(TAG,SubTag.bullet("NonStickyService will Stop"));
stopSelf();
}
}
android.os.Handler handler = new android.os.Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int what = msg.getData().getInt("what");
Log.w(TAG,SubTag.bullet("#handler: what: " + what));
}
};
}

Check Internet Connection from an AsyncTask

This is not a duplicate
I want to check real-time internet connection from my activity using AsyncTaskand Handler to display or hide TexView if a connection is available or not. But it doesn't work.
My code throws NetworkOnMainThreadException even using AsyncTask
I'm using this code:
class CheckNetWorkConnection extends AsyncTask<String, Void,Boolean>{
MyActivity activity;
public checkNetWorkConnection(MyActivity activity) {
this.activity= activity;
}
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible;
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
}
});
// doInBackground always retun false
return networkAvalaible;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
// Using handler to repeat Task
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (aBoolean){
activity.noConnection.setVisibility(View.GONE);
}else {
activity.noConnection.setVisibility(View.VISIBLE);
}
}
},3000);
super.onPostExecute(aBoolean);
}
}
to use it, you call
new CheckNetWorkConnection().execute();
you will want your async task to run indefinitely until an internet connection is lost. your current code will only check one time.
you need to change your codes to be polling for it to work.
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible = false;
do {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
sleep(5000); //check connection every 5 seconds.
// you can call publish progress here to tell your process that
// connection is available
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
} while (networkAvalaible);
//you only exit and asyncTask when connection is lost.
return networkAvalaible;
}
AsyncTask is not the right way to do it though... take a look at the following article below.
https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
Put this Class into your util Package to chack internet connection anywhere into your project.
ConnectionDetector.java
package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by Pranav on 29/08/16.
*/
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
Here is a code snippet if MainActivity.java to check internet connection and if internet connection is on then call asynctask otherwise give toast message.
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
import util.ConnectionDetector;
/**
* Created by Pranav on 29/08/16.
*/
public class CaseDetaiksActivity extends Activity {
public static Context context;
ConnectionDetector mConnectionDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
mConnectionDetector = new ConnectionDetector(context);
setContentView(R.layout.activity_mail);
if (mConnectionDetector.isConnectingToInternet()) {
MyAyncTask MyTask = new MyAyncTask();
MyTask.execute();
} else {
Toast.makeText(context, getString(R.string.please_check_internet), Toast.LENGTH_SHORT).show();
}
}
public static class MyAyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// You can track you progress update here
}
#Override
protected Void doInBackground(Void... params) {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
}
return null;
}
}
}
Hope this helps you
a .Create a broadcast receiver class
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if(checkInternet(context)){
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
public boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
b. Create a Service manager class
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Register permissions in the Android Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Declare Broadcast Receiver in the Android Manifest
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
In your activity :
a. register your broadcast receiver in onResume()
registerReceiver(new NetworkChangeReceiver() , new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
b. unregister your broadcast receiver in onPause();
unregisterReceiver(new NetworkChangeReceiver());

Context issue with AsyncTask

When clicking a button then I want to show an alertDialog showing an animationDrawable and performing an asyncTask. I found that when I set the context of the dialog to getApplicationContext() then the app crashed , and when I set the context to the parent class activity then the dialog is dismissed very well when I call the dismiss method in the activity class ; but when I want to dismiss it in the onPostExecute of the AsyncTask then the dialog is not dismissed ! Here are codes :
public class SyncActivity extends Activity {
...
private MessageDialogView dlg = null; // an AlertDialog showing a message
private Patienter dwait = null; // an AlertDialog containing an imageview showing an animation-list
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.synchro);
...
dlg = new MessageDialogView(SyncActivity.this, getLayoutInflater());
dwait = new Patienter(SyncActivity.this, getLayoutInflater());
...
}
public void synchroniser(View view) { // called when a button is clicked
dwait.show();
new RequestTask().execute("http://192.168.1.8/impots/data/syncro/webVersAndroid/parcelles.txt");
}
private class RequestTask extends AsyncTask<String, Void, Void> {
private String err = "";
private boolean error = false;
private String[] enregs;
#Override
protected Void doInBackground(String... s_url) {
enregs = new String[s_url.length];
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null) {
if (networkInfo.isAvailable() && networkInfo.isConnected()) {
System.setProperty("http.keepAlive", "false");
HttpURLConnection con = null;
BufferedReader reader = null;
for (int u=0; u<s_url.length; u++) {
String tmp;
String lines = "";
try {
URL url = new URL(s_url[u]);
if (url != null) {
con = (HttpURLConnection) url.openConnection();
if (con != null && con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
boolean firstLine = true;
while ((tmp = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
lines += tmp;
}
else
lines += "\r\n" + tmp;
}
enregs[u] = lines;
}
}
} catch (MalformedURLException e) {
error = true;
err = getResources().getString(R.string.errBadUrl);
} catch (IOException e) {
error = true;
err = getResources().getString(R.string.errAccessError);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (con != null)
con.disconnect();
}
}
}
else {
error = true;
err = getResources().getString(R.string.errNotConnected);
}
} else {
error = true;
err = getResources().getString(R.string.errNoNetwork);
}
if (!error)
populateDB();
return null;
}
#Override
protected void onPostExecute(Void result) {
dwait.dismiss();
if (error) {
displayError(err);
}
}
private void displayError(String msg) {
dlg.setTitre(getString(R.string.titreErrMsgBox));
dlg.setMsg(msg);
dlg.show();
}
...
}
}
}
Code of the dialog :
public class Patienter extends AlertDialog {
private View contenu;
AnimationDrawable frameAnimation = null;
public Patienter(Context context, LayoutInflater inflater) {
super(context);
contenu = inflater.inflate(R.layout.patienter, null);
setCancelable(false);
setCanceledOnTouchOutside(false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(contenu);
ImageView img = (ImageView)contenu.findViewById(R.id.imgWait);
img.setBackgroundResource(R.drawable.wait);
frameAnimation = (AnimationDrawable) img.getBackground();
frameAnimation.start();
}
}
So how to work with the context ?
Set your Context in Constructor of AsyncTask & pass the context from where AsyncTask called.
Show your Dialogue in onPreExecute() of AsyncTask
Cancel your Dialogue on onPostExecute().
private class RunInBackground extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private Context contextInsideDialogue;
public RunInBackground(Context activity) {
try {
this.contextInsideDialogue = activity;
dialog = new ProgressDialog(activity,
android.R.style.Theme_DeviceDefault_Light_Panel);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.getWindow().setGravity(Gravity.BOTTOM);
} catch (Exception e) {
}
}
#Override
protected void onPreExecute() {
try {
dialog.setMessage("Please wait. . ");
dialog.show();
} catch (Exception e) {
}
}
#Override
protected void onPostExecute(Void result) {
try {
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
}
& Invoke it as
RunInBackground task = new RunInBackground (MyActivity.this);
task.execute();

How to perform AsyncTask for checking internet connection

I have the following code, and what I'm trying to do is to programmatically check if there is an internet connection or not.
Since I'm getting a NetworkOnMainThreadException, and have been advised to use AsyncTask.
I want to perform network operation on hasActiveInternetConnection(Context context)and return true if connected to a network, else false .
How do I do this using AsyncTask?
public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;
public NetworkUtil(Context context){
this.context = context;
}
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {
}
}
// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
use this class for checking internet connectivity...
public class CheckNetwork {
private Context context;
public CheckNetwork(Context context) {
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
then.....
use the this ASynTask for httppost.
public class NetworkUtil extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
// your get/post related code..like HttpPost = new HttpPost(url);
} else {
// No Internet
// Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
There is no way to get an Internet connexion state, you will always have the network connection state.
But I found a pretty nice answer here: you send a request to google.com !! :) you can also try to ping to google by unix commandes if you want !!
here the guy is using a thread , and waiting a little bit for the answer, then returning a boolean . you do your staff in the handler . this is his code :
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
#Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
}
catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
Then, I define the handler:
Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
...and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Your AsyncTask should look like this:
private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{
Context context;
public NetworkUtilTask(Context context){
this.context = context;
}
protected Boolean doInBackground(Void... params) {
return hasActiveInternetConnection(this.context);
}
protected void onPostExecute(Boolean hasActiveConnection) {
Log.d(LOG_TAG,"Success=" + hasActiveConnection);
}
}
You would then execute it like the following:
NetworkUtilTask netTask = new NetworkUtilTask(context);
netTask.execute();

show notification from google chat activity only when activity is in background

This is a Google Chat application. When I get a message from Google Chat I want to show it in the status bar as a notification when the activity is in background.
I tried setting boolean values in the onPause() method but it did not work.
public void addMessage(String chatid, String msg) {
// I want to the execute this line only when the activity is in background
notify.getCurrentActivity(getApplicationContext(), msg, fromName, chatid);
}
public void getCurrentActivity(Context context, String msg){
showNotification(context, msg, fromName, fromChatID);
}
try to do below
try{
boolean foregroud = new ForegroundCheckTask().execute(context).get();
if(foregroud)
{
//app is foreground
}
else
{
//app is not foreground }
}catch(Exception e)
{
e.toString();
}
add below async
//Foreground check
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
#Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
I find out solution myself
private int key; // Declare as global
protected void onPause
{
key=1;
super.onpause();
}
protected void onResume{
key=0;
super.onResume();
}
public void addMessage(String chatid, String msg) {
if(key==1)
{
notify.getCurrentActivity(getApplicationContext(), msg, fromName, chatid);
}
}

Categories

Resources