This code is supposed to suggest if the phone is charging or not in real time, changing a text view.
public class MainActivity extends AppCompatActivity {
TextView testoStatoCarica;
String positivo = "Sto caricando";
String negativo = "Non in carica";
boolean variabileStato;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testoStatoCarica = (TextView) findViewById(R.id.TestoStatoCarica);
//Ricevo lo stato di carica
registerReceiver( null ,new IntentFilter("broadcastStato"));
BroadcastReceiver ricettore = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b1 = intent.getExtras();
variabileStato = intent.getBooleanExtra("isCharging", isCharging);
}
};
}
}
And in the other class ( PowerConnectionReceiver ) i made this!
public class PowerConnectionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Bundle bundle = intent.getExtras();
Intent i1 = new Intent("broadcastStato");
i1.putExtra("isCharging", isCharging);
Intent i2 = new Intent("broadcastTipo1");
i2.putExtra("usbCharge", usbCharge);
Intent i3 = new Intent("broadcastTipo2");
i3.putExtra("acCharge", acCharge);
context.sendBroadcast(i1);
context.sendBroadcast(i2);
context.sendBroadcast(i3);
}
}
Now,the problem is that i don't understand really what to do in my MainActivity with the booleand created in this last class! Anyone can help?
Check out Monitoring the Battery Level and Charging State article, it has code sample:
First you need to specify BroadcastReceiver in your AndroidManifest:
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
Then, specify the PowerConnectionReceiver:
public class PowerConnectionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
}
}
Now, the last step to pass new value from PowerConnectionReceiver to your MainActivity:
You can find the tutorial here: https://trinitytuts.com/pass-data-from-broadcast-receiver-to-activity-without-reopening-activity/
(Once you passed new value - you can update the TextView's text)
That's it! I hope, it helps
Related
I am using below code to detect network changes
public class NetworkStateListener extends BroadcastReceiver {
public static int NETWORK_CONNECTED_TYPE_WIFI = 1;
public static int NETWORK_CONNECTED_TYPE_MOBILE = 2;
public static int NO_NETWORK_CONNECTIVITY = 0;
public static int TYPE_NOT_KNOWN = -1;
private static final List<NetworkStateChangeListener> LISTENERS = new CopyOnWriteArrayList<>();
#Override
public void onReceive(Context context, Intent intent) {
int status = getConnectivityStatus(context, intent);
networkChecking(status);
}
private void networkChecking(int noNetworkConnectivity) {
for (NetworkStateChangeListener mlistener : LISTENERS) {
if (mlistener != null) {
mlistener.onNetworkStateChanged(noNetworkConnectivity);
}
}
}
public static void registerNetworkState(NetworkStateChangeListener listener) {
synchronized (LISTENERS) {
if (!LISTENERS.contains(listener)) {
LISTENERS.add(listener);
}
}
}
public static void unregisterNetworkState(NetworkStateChangeListener listener) {
LISTENERS.remove(listener);
}
public static int getConnectivityStatus(Context context, Intent intent) {
if (intent.getExtras() != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork!=null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
return NETWORK_CONNECTED_TYPE_WIFI;
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
return NETWORK_CONNECTED_TYPE_MOBILE;
}
}
return NO_NETWORK_CONNECTIVITY;
}
return TYPE_NOT_KNOWN;
}
}
and initialising below intent filters in AndroidManifest.xml
<receiver android:name=".utils.network.NetworkStateListener">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
This code is working fine for below Marshmallow devices 6.0.1. But from 7 Nougat onwards, its not working.
What is the code change in Nougat?
Any code or gist will be appreciated. Thanks in advance.
Find the solution:
Register programmatically like this
IntentFilter intentFilter = new IntentFilter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // **For Nougat**
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
} else {
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_CHANGE));
}
registerReceiver(new NetworkConnectionReceiver(), intentFilter);
i have used the android:stopWithTask="false" but it never work with one of my services
<service android:name=".EcaService"
android:enabled="true"
android:stopWithTask="false"/>
and the service is:
package com.example.ayham.usefullalarm;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.IBinder;
import android.util.Log;
/**
* Created by ayham on 7/8/2017.
*/
public class EcaService extends Service {
private BroadcastReceiver batteryReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
registerBatteryReceiver();
}
private void registerBatteryReceiver() {
batteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (MainView.eca_activeCode < 1) {
// How are we charging?
Log.e("in first if", ": done");
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean wirelessCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if (acCharge || wirelessCharge) {
Log.e("in second if", ": done");
Intent do_Alarm = new Intent(context, BatteryAlarmView.class);
do_Alarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainView.eca_activeCode++;
context.startActivity(do_Alarm);
}
}
}
};
IntentFilter electricalAIntent = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryReceiver, electricalAIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("in the receiver","yay");
/*Intent doAlarm = new Intent(this, BatteryAlarmView.class);
doAlarm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(doAlarm);*/
return START_NOT_STICKY;
}
}
in the MainView the code is:
public class MainView extends Activity {
static int eca_activeCode = 0;
Button eca;
Intent eca_intent;
boolean eca_s;
/*#Override
public void onBackPressed() {
Intent itent = new Intent(this, MainView.class);
startActivity(itent);
}*/
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main_view);
this.context = this;
//to be used in decision of the eca
eca_s = false;
//initialize the eca button
eca = (Button)findViewById(R.id.e_status);
//initialize the textView related to the eca
ecaText = (TextView)findViewById(R.id.EText);
//add a click listener to the eca button to start the electrical alarm
eca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//decide whether to activate or not
String s ;
if(!eca_s) {
eca_activeCode = 0;
eca_s = true;
s = "ON";
eca_intent = new Intent(context,EcaService.class);
context.startService(eca_intent);
}
else {
eca_s =false;
s = "Off";
eca_intent = new Intent(context,EcaService.class);
context.stopService(eca_intent);
}
//set the button text to indicate the status of eca
eca.setText(s);
}
});
//receive the battery alarm intent
if(eca_intent != null) {
Intent b_back = getIntent();
eca_s = false;
String s = "Off";
String class_name = b_back.getExtras().getString("Class");
if (class_name.equalsIgnoreCase("BatteryAlarmView")) {
eca_intent = new Intent(context,EcaService.class);
context.stopService(eca_intent);
eca_activeCode = 0;
//set the button text to indicate the status of eca
eca.setText(s);
}
}
}
}
what is wrong with the code, it did not give any error!!
I am trying to monitor the current battery status using a Service. I wrote some code and I can show the battery level using the log once but I want to monitor the battery level according to a timer every 5 seconds.
public class ServiceStatusUpdate extends Service {
GPSTracker gps;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
while (true) {
new Handler().postDelayed(new Runnable() {
public void run() {
batteryLevel();
Log.e("Status changed", "Status changed");
}
}, 5000);
return START_STICKY;
}
}
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
Log.e("Batarry status iss", level + "mm");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
return;
}
}
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, ServiceStatusUpdate.class));
}
}
manifest.xml source:
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".ServiceStatusUpdate"
android:enabled="true" />
OnBootReceiver:
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//int batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
Intent serviceLauncher = new Intent(context, ServiceStatusUpdate.class);
context.startService(serviceLauncher);
}
}
}
I am also trying to send an HTTP request every /xxx times. The HTTP request will include some text, the battery status, and latitude and longitude.
I know how to send the request with parameters, but my service is working only once.
You are unregistering the batteryLevelReceiver after the first time it receives a broadcast. Remove this line from onReceive to continue to receive broadcasts:
context.unregisterReceiver(this);
Also, you probably only want to register and unregister your broadcast receiver once when the server is created/destroyed so you should register in onCreate and unregister in onDestroy.
Here is some code that should be very close to what you want. Note that all of this will run on the UI thread currently.
public class ServiceStatusUpdate extends Service {
private static final int CHECK_BATTERY_INTERVAL = 5000;
private GPSTracker gps;
private double batteryLevel;
private Handler handler;
private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent batteryIntent) {
int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (rawlevel >= 0 && scale > 0) {
batteryLevel = (rawlevel * 100.0) / scale;
}
Log.e("Battery status is", batteryLevel + "mm");
}
};
private Runnable checkBatteryStatusRunnable = new Runnable() {
#Override
public void run() {
//DO WHATEVER YOU WANT WITH LATEST BATTERY LEVEL STORED IN batteryLevel HERE...
// schedule next battery check
handler.postDelayed(checkBatteryStatusRunnable, CHECK_BATTERY_INTERVAL);
Log.e("Battery status is", batteryLevel + "mm cached");
}
};
#Override
public void onCreate() {
handler = new Handler();
handler.postDelayed(checkBatteryStatusRunnable, CHECK_BATTERY_INTERVAL);
registerReceiver(batInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(batInfoReceiver);
handler.removeCallbacks(checkBatteryStatusRunnable);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
I am trying to modify the BluetoothLeGatt project supplied as an example with Android Studio to send RSSI values back to the main activity for display each time a characteristic is read. I have created a new intent filter, but the receiver never receives the intent. I have tried adding it to the manifest file, but that didn't work either.
Here is the Service code:
public class BluetoothLeService extends Service {
...
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String RSSI_DATA_AVAILABLE =
"com.example.bluetooth.le.RSSI_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
public final static String EXTRA_RSSI =
"com.example.bluetooth.le.EXTRA_RSSI";
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
mBluetoothGatt.readRemoteRssi();
}
}
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
final Intent intent = new Intent();
if (status == BluetoothGatt.GATT_SUCCESS) {
intent.putExtra(EXTRA_RSSI, String.valueOf(rssi));
intent.setAction(RSSI_DATA_AVAILABLE);
sendBroadcast(intent);
}
}
And the Activity:
public class DeviceControlActivity extends Activity {
...
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
} else if (BluetoothLeService.RSSI_DATA_AVAILABLE.equals(action)) {
updateRssi(intent.getStringExtra(BluetoothLeService.EXTRA_RSSI));
}
}
};
...
}
Answer:
I had to add the action to this method in the Activity:
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.RSSI_DATA_AVAILABLE);
return intentFilter;
}
override onResume in your Activity, create an IntentFilter, adding your custom actions, and register the broadcast receiver.
IntentFilter filter = new IntentFilter();
// call addAction for every action you want to receive in your BroadcastReceiver
filter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
and then register it with
registerReceiver(mGattUpdateReceiver, filter);
override onPause and call unregeisterReceiver
unregisterReceiver(mGattUpdateReceiver);
I'm trying to change my textview, but it doesn't work.
MainActivity:
public void changeTxt(String txt){
TextView t = (TextView) findViewById(R.id.wifiName);
t.setText(txt);
}
BroadcastReceiver:
MainActivity ma;
#Override
public void onReceive(Context context, Intent intent) {
ma= new MainActivity();
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
String txt = acCharge+"";
ma.changeTxt(txt);
}
Call registerBroadCastReciever like this :
//BroadCastReciever variable in base activity or activity
private BroadcastReceiver serviceBroadcastReceiver;
//Register reciever method
void registerBroadcastReceiver(){
if (serviceBroadcastReceiver != null)
{
LocalBroadcastManager.getInstance(this.getActivity()).unregisterReceiver(this.serviceBroadcastReceiver);
LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(this.serviceBroadcastReceiver, new IntentFilter("...BROADCAST_STR"));
return;
}
this.serviceBroadcastReceiver = new BroadcastReceiver()
{
public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent)
{
//Recieve STH and call method like SetText() that initialize your textView text
}
};
LocalBroadcastManager.getInstance(this.getActivity()).registerReceiver(this.serviceBroadcastReceiver, new IntentFilter("...BROADCAST_STR"));
} //Then onResume & onPause methods in activity
#Override
public void onResume() {
super.onResume();
registerBroadcastReceiver();
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(this.serviceBroadcastReceiver);
}
Try this:
MyActivity:
public class MyActivity extends Activity {
private TextView wifi;
private BateryReceiver bateryReceiver;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wifi = (TextView) findViewById(R.id.wifiName);
wifi.setText("nothing");
bateryReceiver = new BateryReceiver(wifi);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(bateryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(bateryReceiver);
}
}
BateryReceiver: (create new class if you don't have)
public class BateryReceiver extends BroadcastReceiver {
private final TextView textView;
public BateryReceiver(TextView textView)
{
this.textView = textView;
}
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean ac = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
boolean usb = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
String plugSource = (ac == true)? "AC" : "USB";
if(isCharging)
textView.setText("charging: " + isCharging + " by " + plugSource);
else
textView.setText("not charging");
}
}
It should be working.