Can't change textview (broadcastreceiver) - android

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.

Related

android:stopWithTask="false" but the service did close

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!!

Android Check Internet connection continuously

I want to check internet connection continuously on every activity with the broadcastreceiver. I already write the code and it perfectly working. But I want to use it in every activity. How can I modify this code?
public class MainActivity extends Activity {
private static final String LOG_TAG = "CheckNetworkStatus";
private NetworkChangeReceiver receiver;
private boolean isConnected = false;
private TextView networkStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
networkStatus = (TextView) findViewById(R.id.networkStatus);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onDestroy() {
Log.v(LOG_TAG, "onDestory");
super.onDestroy();
unregisterReceiver(receiver);
}
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
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) {
if(!isConnected){
Log.v(LOG_TAG, "Now you are connected to Internet!");
networkStatus.setText("Now you are connected to Internet!");
isConnected = true;
//do your processing here ---
//if you need to post any data to the server or get status
//update from the server
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
networkStatus.setText("You are not connected to Internet!");
isConnected = false;
return false;
}
}
}
I want to use it in every activity. How can I modify this code?
Create a BaseActivity class which extends AppCompatActivity, and then make all of your Activity classes extend this BaseActivity class. Put your code to check internet connection in the BaseActivity class. cheers :)
Create a BaseActivity without a layout which extends to AppCompatActivity or Activity.
Extend all the other activities (or the one where you need to check for internet connectivity) of your app to the BaseActivity.
Now use a broadcast receiver in the BaseActivity which constantly checks for network and connectivity state.
Reference code for BaseActivity. (In my case, I show a snackbar when there is no connection detected.)
public class BaseActivity extends AppCompatActivity {
private static final int WIFI_ENABLE_REQUEST = 0x1006;
private BroadcastReceiver mNetworkDetectReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
checkInternetConnection();
}
};
private AlertDialog mInternetDialog;
private boolean isConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isConnected = false;
registerReceiver(mNetworkDetectReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onDestroy() {
unregisterReceiver(mNetworkDetectReceiver);
super.onDestroy();
}
private void checkInternetConnection() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
isConnected =true;
showNoConnectionSnackBar("Connected", isConnected, 1500);
} else {
isConnected= false;
showNoConnectionSnackBar("No active Internet connection found.", isConnected,6000);
}
}
private void showNoConnectionSnackBar(String message, boolean isConnected, int duration) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content),
message, duration);
View sbView = snackbar.getView();
TextView textView = (TextView) sbView
.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(ContextCompat.getColor(this, android.R.color.white));
if (isConnected){
sbView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}else{
sbView.setBackgroundColor(getResources().getColor(R.color.google_button_color));
snackbar.setAction("Turn On", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent internetOptionsIntent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(internetOptionsIntent, WIFI_ENABLE_REQUEST);
}
});
snackbar.setActionTextColor(getResources().getColor(R.color.colorPrimary));
}
snackbar.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == WIFI_ENABLE_REQUEST) {
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Create a service. start the service in the launcher activity and put the network check code in that service.
public class NetworkServiceextends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//register receiver here
// connection check code
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onDestroy() {
super.onDestroy();
// unregister receiver
}
}
You can put your BroadcastReceiver in it's own class, and then declare/register it in your Manifest. That way it will share the lifetime of your application.
An additional benefit is that you dont have to worry about unregistering it, so you won't have to worry about memory leaks.
Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.SumonHub:EagleEye:1.0.0'
}
If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:name="org.sumon.eagleeye.EagleEyeApplication" >
...
</application>
</manifest>
If you do override the Application class, change it to extend EagleEyeApplication (if possible) as follows:
public class MyApplication extends EagleEyeApplication { ... }
In youre activity/fragment get status like below
EagleEyeObserver.setConnectivityListener(new OnChangeConnectivityListener() {
#Override
public void onChanged(boolean status) {
Toast.makeText(MainActivity.this, "" + status, Toast.LENGTH_SHORT).show();
}
});
more info here

BroadcastReceiver for "USER_PRESENT" leaking memory

I have an application containing Activity A, Service S and BroadcastReceiver BR. What I want the application to do is to listen to when the user unlocks the phone. This is currently achieved by having A start S and bind to it. S will start and register BR to listen for "android.intent.action.USER_PRESENT".
The application should theoretically be able to listen for phone unlocks indefinitely in the background. My application completes its purpose, but i have seen in the Android Monitor that memory usage steadily increases, and will increase by approximately 0,033MB for each unlock (every time onReceive is called(?)).
Following is the code.
Activity:
public class MainActivity extends Activity implements BackgroundService.ServiceCallbacks
{
private TextView lastUnlock;
private boolean isBound = false;
private BackgroundService backgroundService;
private ServiceConnection serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
BackgroundService.LocalBinder binder = (BackgroundService.LocalBinder) service;
backgroundService = binder.getServiceInstance();
backgroundService.registerActivity(MainActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name)
{
isBound = false;
backgroundService = null;
}
};
/** Activity is created, start service and bind to it **/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastUnlock = (TextView) findViewById(R.id.lastUnlock_TW);
Intent serviceIntent = new Intent(this, BackgroundService.class);
startService(serviceIntent);
bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
isBound = true;
}
/** Activity is destroyed, it should unbind from the service **/
#Override
protected void onDestroy()
{
super.onDestroy();
if (isBound)
{
backgroundService.unregisterActivity();
unbindService(serviceConnection);
isBound = false;
}
}
/** The service can call this method to update the lastUnlock TextView **/
#Override
public void updateClient(String data)
{
lastUnlock.setText(data);
}
}
Service:
public class BackgroundService extends Service
{
ServiceCallbacks activity;
private final IBinder LOCAL_BINDER = new LocalBinder();
private UserPresentReceiver userPresentReceiver;
SharedPreferences sharedPreferences;
/** The service is created, receivers are registered here **/
#Override
public void onCreate()
{
super.onCreate();
userPresentReceiver = new UserPresentReceiver();
registerReceiver(userPresentReceiver, new IntentFilter("android.intent.action.USER_PRESENT"));
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
/** An activity called startService() or the process was killed, returning START_STICKY
** which restarts the service and this method is called **/
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
/** An activity just bound to the service **/
#Override
public IBinder onBind(Intent intent)
{
return LOCAL_BINDER;
}
/** Service is destroyed, unregister the receivers **/
#Override
public void onDestroy()
{
super.onDestroy();
unregisterReceiver(userPresentReceiver);
}
/** **/
public class LocalBinder extends Binder
{
public BackgroundService getServiceInstance()
{
return BackgroundService.this;
}
}
/** Update the activity if it is connected, and save the unlockStatus in the preferences **/
public void updateActivity(String unlockStatus)
{
if (activity != null)
{
this.activity.updateClient(unlockStatus);
}
SharedPreferences.Editor spEditor = sharedPreferences.edit();
spEditor.putString("saved_last_unlock", unlockStatus);
spEditor.apply();
}
/** Methods an activity can call to register or unregister itself to the service **/
public void registerActivity(Activity activity)
{
this.activity = (ServiceCallbacks) activity;
// If the last unlock is saved in the preferences, retrieve it from there
String savedLastUnlock = sharedPreferences.getString("saved_last_unlock", null);
if (savedLastUnlock != null)
{
this.activity.updateClient(savedLastUnlock);
}
}
public void unregisterActivity()
{
activity = null;
}
/** An activity has to implement this interface so that the service can send commands to it **/
public interface ServiceCallbacks
{
void updateClient(String data);
}
}
BroadcastReceiver:
public class UserPresentReceiver extends BroadcastReceiver
{
private final String TAG = "UserPresentReceiver";
UnlockStatus unlockStatus;
public UserPresentReceiver()
{
unlockStatus = new UnlockStatus();
}
#Override
public void onReceive(Context context, Intent intent)
{
unlockStatus.setStatus(new Date());
BackgroundService service = (BackgroundService) context;
service.updateActivity(unlockStatus.getStatus());
}
}
UnlockStatus:
public class UnlockStatus
{
private Calendar calendar;
private final SimpleDateFormat SDF = new SimpleDateFormat("dd.MM.yyyy' kl. 'HH:mm:ss");
private boolean unlockRegistered = false;
public UnlockStatus()
{
calendar = Calendar.getInstance();
}
public String getStatus()
{
if (unlockRegistered)
return SDF.format(calendar.getTime());
else
return null;
}
public void setStatus(Date date)
{
unlockRegistered = true;
calendar.setTime(date);
}
}
Please find the solution
public class MyApplication extends Application implements HM_Constants, Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
public static String stateOfLifeCycle = "";
public static boolean wasInBackground = false;
private static HydratemateApplication mInstance;
private static String TAG = HydratemateApplication.class.getName();
boolean status;
ScreenOffReceiver screenOffReceiver = new ScreenOffReceiver();
public static synchronized HydratemateApplication getInstance() {
return mInstance;
}
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
registerActivityLifecycleCallbacks(this);
registerReceiver(screenOffReceiver, new IntentFilter("android.intent.action.SCREEN_OFF"));
// new HM_PrefsManager(mInstance).save(Prefs_Keys.SERVICE_THREAD_STOP,"NO");
}
#Override
public void onActivityCreated(Activity activity, Bundle arg1) {
// Log.d(TAG, "onActivityCreated " + activity.getLocalClassName());
wasInBackground = false;
status = false;
stateOfLifeCycle = "Create";
}
#Override
public void onActivityStarted(Activity activity) {
// Log.d(TAG, "onActivityStarted " + activity.getLocalClassName());
stateOfLifeCycle = "Start";
}
#Override
public void onActivityResumed(Activity activity) {
Log.d(TAG, "onActivityResumed " + activity.getLocalClassName());
stateOfLifeCycle = "Resume";
try {
Intent service = new Intent(getApplicationContext(), VolumeService.class);
stopService(service);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (BatteryHealthActivity.mBluetoothLeForegroundService != null && status) {
//BatteryHealthActivity.mBluetoothLeForegroundService.indicateCharacteristic(UUID.fromString(GattAttributes.BATTERY_LEVEL_SERVICE_UUID), UUID.fromString(GattAttributes.BATTERY_LEVEL_CHARACTERSTIC_UUID), true);
status = false;
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onActivityPaused(Activity activity) {
// Log.d(TAG, "onActivityPaused " + activity.getLocalClassName());
stateOfLifeCycle = "Pause";
}
#Override
public void onActivityStopped(Activity activity) {
// Log.d(TAG, "onActivityStopped " + activity.getLocalClassName());
stateOfLifeCycle = "Stop";
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle arg1) {
//Log.d(TAG, "onActivitySaveInstanceState " + activity.getLocalClassName());
}
#Override
public void onActivityDestroyed(Activity activity) {
// Log.d(TAG, "onActivityDestroyed " + activity.getLocalClassName());
Log.d("iam", "calling");
wasInBackground = false;
stateOfLifeCycle = "Destroy";
}
#Override
public void onTrimMemory(int level) {
if (stateOfLifeCycle.equals("Stop")) {
wasInBackground = true;
}
super.onTrimMemory(level);
Log.d(TAG, "onTrimMemory " + level);
onBackground();
}
public void onBackground(){
if (!isMyServiceRunning(VolumeService.class)) {
try {
status = true;
if (BatteryHealthActivity.mBluetoothLeForegroundService != null) {
BatteryHealthActivity.mBluetoothLeForegroundService.indicateCharacteristic(UUID.fromString(GattAttributes.BATTERY_LEVEL_SERVICE_UUID), UUID.fromString(GattAttributes.BATTERY_LEVEL_CHARACTERSTIC_UUID), false);
}
new ForegroundCheckTask().execute(mInstance).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
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;
}
class ScreenOffReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
wasInBackground = true;
onBackground();
}
}}

Why my text view doesn't change?

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

Text to Speech from Service

I have a service running on device boot. It checks for some data and send out Notifications.
I came across the following.
http://mobile.tutsplus.com/tutorials/android/android-sdk-using-the-text-to-speech-engine/
and I want to send voice notification. I do not need UI part of it. How do I add it in my project?
Differnt java class (calling Activity from service)
An internal class
Create class App and an instance of TextToSpeech in it:
public class App extends Application {
private static TextToSpeech mTts;
public static TextToSpeech getmTts() {
return mTts;
}
public void onCreate() {
super.onCreate();
// creating TTS:
mTts = new TextToSpeech(this, this);
mTts.setLanguage(Locale.US);
mTts.stop();
}
}
Declare App(above) in your manifest:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:name="your.application.package.App" >
Send a broadcast by your service when you want to a BroadcastReceiver for example this:
public class TTSReceiver extends BroadcastReceiver implements OnInitListener {
private TextToSpeech mTts;
private String message;
#Override
public void onReceive(Context context, Intent intent) {
mTts = App.getmTts();
mTts.setLanguage(Locale.US);
message = "your message";
mTts.stop();
mTts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status) {
}
}
public class SpeakService extends Service implements OnInitListener {
public static TextToSpeech tts;
private String string;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
tts = new TextToSpeech(this, this);
super.onCreate();
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
string = intent.getStringExtra("string");
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d("SpeakService", "Language is not available.");
} else {
if (!TextUtils.isEmpty(string)) {
speak(string);
} else {
speak("Error");
}
}
} else {
Log.d("SpeakService", "Could not initialize TextToSpeech.");
}
}
private void speak(String string) {
tts.speak(string, TextToSpeech.QUEUE_FLUSH, null);
}

Categories

Resources