i try to check internet connection with BroadcastReceiver.i wrote some code witch can to check connection.and now,i want to check connection for example every 5 min
this is a my code
public class BroadCastSampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
getApplicationContext().registerReceiver(
mConnReceiver,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
}, 2000);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent
.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(
ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if (currentNetworkInfo.isConnected()
|| otherNetworkInfo.isConnected()) {
Toast.makeText(getApplicationContext(), "Connected",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Not Connected",
Toast.LENGTH_LONG).show();
}
}
};
}
how i can write to can check connection everytime,(every 5 min)
if anyone knows solution please help me.thanks
You should use AlarmManager to check the Internet-connection.Check the official example and check out this tut.
I hope it should do the trick
You can use Timer for repeating a task at fixed interval.
Timer timer = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
boolean internetConnected = checkInternetConnection();
}
}, 0, 300000); //for repeating every 5 minutes
public boolean checkInternetConnection (){
//your code
}
Hope it helps.
Related
I followed this to Run a Service for Every 5 Min
Till now Its working fine.. But I have added a Intent for Next service in TimeDisplay But its working fine only for the First Time But the second Activity is not running for Every 30 seconds...Its only Working on First Run..
this is MyService
public class ServMain1 extends Service {
private static final String TAG = "ServMain1";
public static final int notify = 30000;
private Handler mHandler = new Handler();
private Timer mTimer = null;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
}
//class TimeDisplay for handling task
class **TimeDisplay** extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show();
startService(new Intent(ServMain1.this, ServMain2.class));
}
});
}
}
}
Here at TimeDisplay I am using this to start second service startService(new Intent(ServMain1.this, ServMain2.class));
How ever I am getting Toast for Every 30 Seconds But Along with that toast I am using a intent is not working...
Its working only for the first time... but I am getting toast of every 30seconds
Can Any one suggest me How to using this kind of activity
A service will only run once even after you call startService multiple times.
If you want to keep restarting the service in your handler, you need to first check if it already running, kill it if it is already running and call startService post that.
You can check if the service is running using
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
And inside your handler make these changes
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(ServMain1.this, "ServMain1 : Service is running", Toast.LENGTH_SHORT).show();
if(!isMyServiceRunning(ServMain2.class)){
startService(new Intent(ServMain1.this, ServMain2.class));
} else{
stopService(ServMain2.class);
startService(new Intent(ServMain1.this, ServMain2.class));
}
}
});
Hi I have been creating an app that would check if the phone is using wifi or mobile data, using timerTask to inform the user and broadcast Receivers to check if WIFI or MOBILE DATA is open.
Even after I cancel the timerTask it goes to an Error notification and then the wifi notification runs again.
I have been stuck with this problem for hours now and I decided to ask for some help.
This is my MainActivity Class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public String getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
String status = null;
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
status = "WIFI";
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
status = "DATA";
}
else{
status = "ERROR";
}
return status;
}
And this is my NetworkChangeReceiver Class:
public class NetworkChangeReceiver extends BroadcastReceiver {
//WIFI TIMER
public void startWIFITimer() {
wifiTimer = new Timer();
initializeWIFITimer();
wifiTimer.schedule(wifiTimerTask, 1000, 5000);
}
public void stopWIFITimer() {
if (wifiTimer != null) {
wifiTimer.cancel();
wifiTimer = null;
}
}
public void initializeWIFITimer() {
wifiTimerTask = new TimerTask() {
public void run() {
wifiHandler.post(new Runnable() {
public void run() {displayNotificationWIFI();
}
});
}
};
}
#Override
public void onReceive(Context context, final Intent intent) {
contexts = context.getApplicationContext();
String status = main.getConnectivityStatus(context);
if (status.contains("WIFI")){
startWIFITimer();
}
else if (status.contains("DATA")){]
}
else if (status.contains("ERROR")){
displayNotificationERROR();
stopWIFITimer();
}
}
And if someone decides to downvote, it would be nice to get a reason why. Thanks again in advance for any help! :D
Each time you receive a broadcast message, a new instance of the BroadcastReceiver is created. So when you call stopWIFITimer() you are actually trying to stop a never started timer, because the started timer is an object of another instance of the BroadcastReceiver.
So, you should move your timer somewhere else.
Currentlly I am implementing pattern lock application and I want to set limit when user enter wrong pattern many time.Example,If user enter wrong pattern at that time set limit(3 or 4 time limit) and set delay 30 second and after 30 second give permission to enter pattern.
So,If anyone know how i can do this please give idea of that.
Here this my Reciever
public class LockScreenReceiver extends DeviceAdminReceiver {
Context context;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Action...","..."+action);
//If the screen was just turned on or it just booted up, start your Lock Activity
if(action.equals(Intent.ACTION_SCREEN_OFF) || action.equals(Intent.ACTION_BOOT_COMPLETED))
{
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
#Override
public void onPasswordFailed(Context ctxt, Intent intent) {
DevicePolicyManager mgr = (DevicePolicyManager) ctxt.getSystemService(Context.DEVICE_POLICY_SERVICE);
int no = mgr.getCurrentFailedPasswordAttempts();
if (no >= 3) {
context.startActivity(new Intent(context,ChangeActivity.class));
}
}
}
Service
public class LockScreenService extends Service {
DeviceAdminReceiver receiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
// Register for Lockscreen event intents
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new LockScreenReceiver();
registerReceiver(receiver, filter);
startForeground();
return START_STICKY;
}
// Run service in foreground so it is less likely to be killed by system
private void startForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText("Running")
.setContentIntent(null)
.setOngoing(true)
.build();
startForeground(9999,notification);
}
#Override
#SuppressWarnings("deprecation")
public void onCreate() {
KeyguardManager.KeyguardLock key;
KeyguardManager km = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
//This is deprecated, but it is a simple way to disable the lockscreen in code
key = km.newKeyguardLock("IN");
key.disableKeyguard();
//Start listening for the Screen On, Screen Off, and Boot completed actions
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
//Set up a receiver to listen for the Intents in this Service
receiver = new LockScreenReceiver();
registerReceiver(receiver, filter);
super.onCreate();
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
}
Activity
public class MainActivity extends ActionBarActivity {
private Lock9View lock9View;
private static String MY_PREFS_NAME = "PatternLock";
private static String PATTERN_KEY;
SharedPreferences prefs;
Button btnChange;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(MainActivity.this, LockScreenService.class));
makeFullScreen();
setContentView(R.layout.activity_main);
btnChange = (Button)findViewById(R.id.btnChange);
btnChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(MainActivity.this,ChangeActivity.class);
startActivity(in);
}
});
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
lock9View = (Lock9View) findViewById(R.id.lock_9_view);
lock9View.setCallBack(new Lock9View.CallBack() {
#Override
public void onFinish(String password) {
PATTERN_KEY = prefs.getString("Pattern", "invalid");
if (PATTERN_KEY.equals("invalid")) {
Toast.makeText(MainActivity.this, "Options --> Create new Pattern", Toast.LENGTH_LONG).show();
} else {
if (password.equals(PATTERN_KEY)) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}else{
Context context = getApplicationContext();
// Create layout inflator object to inflate toast.xml file
LayoutInflater inflater = getLayoutInflater();
// Call toast.xml file for toast layout
View toastRoot = inflater.inflate(R.layout.layout_toast3, null);
Toast toast = new Toast(context);
// Set layout to toast
toast.setView(toastRoot);
toast.setGravity(Gravity.HORIZONTAL_GRAVITY_MASK | Gravity.BOTTOM,
0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
}
}
});
}
private void makeFullScreen() {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if(Build.VERSION.SDK_INT < 19) { //View.SYSTEM_UI_FLAG_IMMERSIVE is only on API 19+
this.getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
} else {
this.getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
}
}
#Override
public void onBackPressed() {
return; //Do nothing!
}
public void unlockScreen(View view) {
//Instead of using finish(), this totally destroys the process
android.os.Process.killProcess(android.os.Process.myPid());
}
}
So,How i can achieve this...
Have a int field like failedCounter and increment it each time user inputs invalid patterns check if reached the limit then disable the input interface and have a handler to reset the value after the time delay.
int failedCount = 0;
final static int LIMIT = 5; //set your limit here
private void invalidPattern() {
if (++failedCount == LIMIT) {
//disable the input
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//reset the failed count
faildCount = 0;
//Enable the input interface here
}
}, 30000); // 30Sec delay
}
}
Use this two methods -
ScheduledThreadPoolExecutor c1;
private void IncorrectCallCounter() {
if (failedCounter>=0)
{
c1.shutdownNow();
LockScreenFor30Second();
}else
{
if (c1!=null)
c1.shutdownNow();
}
c1 = new ScheduledThreadPoolExecutor(1);
c1.schedule(new Runnable() {
#Override
public void run() {
failedCounter=0;
c1.shutdownNow();
}
}, 15, TimeUnit.SECONDS);
}
ScheduledThreadPoolExecutor c2;
private void LockScreenFor30Second() {
//Lock Screen Here
c2 = new ScheduledThreadPoolExecutor(1);
c2.schedule(new Runnable() {
#Override
public void run() {
//Unlock Screen Here
c2.shutdownNow();
}
}, 30, TimeUnit.SECONDS);
}
Declare failedCounter globally
private int failedCounter=0;
And call this method when you detect wrong pattern -
failedCounter=failedCounter+1;
IncorrectCallCounter();
If user enter wrong pattern 4 times in 15 seconds then this will call LockScreenFor30Second method. and inside LockScreenFor30Second add your code.
public class MainActivity extends ActionBarActivity {
CheckinternetConnection internet;
TextView textview;
int tempint = 100;
private static final long REPEAT_TIME = 1000 * 5;
private PendingIntent pendingIntent;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
internet = new CheckinternetConnection();
schedueService();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(internet, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(internet);
}
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Utils.isNetworkAvailable(MainActivity.this)) {
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
schedueService();
//setMobileDataEnabled(getApplicationContext(), true);
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
CancelAlarm();
}
}
}
this is my code using this code i am able to display Connected and disconnected when application Launch i want as i Enable data connection from Setting or Top of device then there should show Data is connected and as i will Off data connection then it should display data is not connected actully i want start service when My application has network connection and stop service when notwork is not connected suggest me how to implement this.
Try with this receiver
Also make sure you have the permissions in the Manifest
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conn.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected==true)
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
schedueService();
//setMobileDataEnabled(getApplicationContext(), true);
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
CancelAlarm();
}
}
}
String data ="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver
{
public void onReceive(Context c, Intent intent)
{
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
List<ScanResult> wifiScanList = mainWifiObj.getScanResults(); int signalLevel =
0; StringBuilder sb = new StringBuilder();
data = wifiScanList.get(8).toString();
TextView tv = new TextView(this);
tv.setText(sb);
setContentView(tv);
}
handler.post(runnable);
I want to add my timer such that this code should run 5 times and it should run every 2 seconds. I am new to android. I found the timer code from the internet, but whenever and whichever code i try to implement, it gives me error. Basically, I think I am not adding the code at proper place.
But, I am unaware, where should I keep it. In the oncreate method or the onCreate method should be between the run().
I am new so asked this question. Can anyone please help me out.
Here, the answers given run but I am unable to print the code
do something like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2000); //2 seconds
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
}
}; }}
//start it with:
handler.post(runnable);
hope this helps..
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 2000); //2 seconds
//////Process to be executed every 2 seconds ////
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
//////////
}
};
//start it with:
handler.post(runnable);
}
You can create a BroadcastReceiver that handles wifi connection changes.
To be more precise, you will want to create a class - say NetWatcher:
public class NetWatcher extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//here, check that the network connection is available. If yes, start your service. If not, stop your service.
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
//start service
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
else {
//stop service
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}
}}
Also, in your AndroidManifest, you need to add the following lines:
<receiver android:name="Yourpakege name.NetWatcher">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
also more info : http://android-er.blogspot.in/2011/01/monitor-wifi-status-and-information.html