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
Related
I have a timer but I want it to also run in the background, I created a new Service, I think it works but I have a problem with it, I want also to change the layout attributes, like changing TextView text using setText method, I prefer doing it with BroadCastReceiver so I have the following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.setText("hey");
}
};
registerReceiver(receiver, filter);
buttonStart = (Button) findViewById(R.id.start);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(new Intent(MainActivity.this, LocalService.class));
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
I registered here the Receiver so it will happen when I am broadcasting from the Service and change the text to "hey" - I wanted it just to check if the broadcast is working. on the Service I used a code that runs a timer and when it start it will broadcast the message, it is the first time I am using broadcasting receiver for sending actions and not just to wait until Bluetooth is on and stuff like this, here is my Service code:
public class LocalService extends Service
{
private static Timer timer = new Timer();
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
Intent intent = new Intent();
intent.setAction("SOME_ACTION");
sendBroadcast(intent);
}
}
public void onDestroy()
{
super.onDestroy();
}
}
Thanks for helping.
I know this question might be replica of another question but can someone help me figure out where I have gone wrong and possibly correct it if possible?
public class MainActivity extends ActionBarActivity {
TextView ford;
public String TAG=MainActivity.class.getSimpleName();
protected static final long TIME_DELAY = 1000;
//the default update interval for your text, this is in your hand , just run this sample
TextView mTextView;
Handler handler=new Handler();
Random trust = new Random();
int count =0;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView=(TextView)findViewById(R.id.textview);}
protected void onResume({
super.onResume();handler.post(updateTextRunnable);}
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Runnable updateTextRunnable=new Runnable(){
public void run() {
if (networkInfo != null && networkInfo.isConnected()) {
mTextView.setText("connected!");
} else {
mTextView.setText("No network connection available.");
}
}
};
}
Efficient way is to create a broacast receiver which will reguralry check wifi status. Register receiver like this-
WifiMonitor wifiMonitor = new WifiMonitor();
registerReceiver(wifiMonitor, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
registerReceiver(wifiMonitor, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
public class WifiMonitor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do your work here
}
}
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();
}
}
}
hi this is my first question because i'm new to android world programs
I want to take wifi rssi reading and disply it on list
I write the code below and when run it on my phone ,the program stop and say "sorry program is stop "
I dont know why??? could any one help me please ???
public class MainActivity extends ActionBarActivity {
ListView list;
WifiManager wifiManager;
IntentFilter filter;
String wifi [];
WifiScanClass myClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.list1);
wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);
myClass = new WifiScanClass();
registerReceiver(myClass,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
}
protected void onResume()
{
filter=new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(myClass,filter);
super.onResume();
}
protected void onPause()
{
unregisterReceiver(myClass);
super.onPause();
}
class WifiScanClass extends BroadcastReceiver {
#SuppressLint("UseValueOf")
public void onReceive(Context context, Intent intent) {
List<ScanResult> listResult=wifiManager.getScanResults();
wifi=new String[listResult.size()];
int i;
for (i=0;i<listResult.size();i++);
wifi[i]=((listResult.get(i)).toString());
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifi));
}
}
}
Please add the Logcat output for the error.
A possible source of the problem could be that getApplicationContext() needs to be called on the supplied context. So try to replace getApplicationContext() with context.getApplicationContext().
public class MainActivity extends ActionBarActivity {
ListView list;
WifiManager wifiManager;
IntentFilter filter;
String wifi [];
WifiScanClass myClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.list1);
wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);
myClass = new WifiScanClass();
wifiManager.startScan();
}
protected void onResume()
{
filter=new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(myClass,filter);
super.onResume();
}
protected void onPause()
{
unregisterReceiver(myClass);
super.onPause();
}
class WifiScanClass extends BroadcastReceiver {
#SuppressLint("UseValueOf")
public void onReceive(Context context, Intent intent) {
List<ScanResult> listResult=wifiManager.getScanResults();
wifi=new String[listResult.size()];
int i;
for (i=0;i<listResult.size();i++)
wifi[i]=((listResult.get(i)).toString());
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifi));
}
}
}
finally i found the error
";" in for loop .
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.