Alertdialog on outgoing call not working. CallBlocker implementation failed - java

Below is my code that I am using for displaying alert during outgoingcall. But the problem is it is not working.
Picked up from https://github.com/dharmikvyas/CallBlocker
I just need to implement it in my project
Thanks in advance for your help!
CallBarring.java
public class CallBarring extends BroadcastReceiver {
// This String will hold the incoming phone number
private String number;
CustomDialog dialog;
TelephonyManager telephonyManager;
PhoneStateListener listener;
Context context;
#Override
public void onReceive(final Context context, Intent intent) {
// If, the received action is not a type of "Phone_State", ignore it
if (!intent.getAction().equals("android.intent.action.PHONE_STATE"))
return;
// Else, try to do some action
else {
this.context = context;
if(dialog == null){
dialog = new CustomDialog(context);
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
// Fetch the number of incoming call
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
listener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
dialog.dismiss();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
dialog.dismiss();
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
dialog.show();
break;
}
Toast.makeText(context, stateString,Toast.LENGTH_LONG).show();
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
// Check, whether this is a member of "Black listed" phone numbers
// stored in the database
/*if (MainActivity.blockList.contains(new Blacklist(number))) {
// If yes, invoke the method
disconnectPhoneItelephony(context);
return;
}*/
}
}
// Method to disconnect phone automatically and programmatically
// Keep this method as it is
#SuppressWarnings({ "rawtypes", "unchecked" })
private void disconnectPhoneItelephony(Context context) {
ITelephony telephonyService;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
class CustomDialog extends Dialog implements OnClickListener {
public CustomDialog(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
Button btnEndCall = (Button) findViewById(R.id.end_call);
//btnEndCall.set
btnEndCall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
disconnectPhoneItelephony(context);
}
}
below is my Androidmanifest.xml
All the permissions seem to be ok.
<receiver android:name=".CallBarring" >
<intent-filter android:priority="100" >
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

Related

How obtain calling event from my app Android?

I want to capture incoming and outgoing calls from my App, that is, while it is running, if a phone call is made or comes in that can be captured, I have implemented the BroadcastReceiver class and the PhoneStateListener class, but it is not capturing it, or perhaps the way to invoke her. I have added the permissions in the Manifest, I also invoke the Receiver with the name of the BroadcastReceiver class called "Ena_Llamadas_Manager"
This is the class below:
#SuppressLint("SimpleDateFormat") public class Ena_Llamadas_Manager extends BroadcastReceiver {
private static Context contexto;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if(extras != null){
call(context,extras);
}
if ( extras.getString("state").equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//codigo
}
}
public static void call(Context context, Bundle extras) {
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
contexto = context;
//String phoneNumber = extras.getString("incoming_number");
}
private static class PhoneCallListener extends PhoneStateListener {
public boolean isPhoneCalling = false;
Boolean wasRinging = false;
#Override
public void onCallStateChanged(int state, String incomingNumber) {
//Bundle extras = intent.getExtras();
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
//Aquí ya detectas que el teléfono esta recibiendo una llamada entrante
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
isPhoneCalling = true;
AlertDialog.Builder builder = new AlertDialog.Builder(contexto);
builder.setMessage("Llamada saliente...")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
isPhoneCalling = false;
}
}
}
}
And this is the Manifest permisson:
<receiver android:name="etapa.webServices.inec.go.cr.Ena_Llamadas_Manager" >
<intent-filter
android:priority="1">
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
Finally this is the way tha invoke the class from the Main Activity
Ena_Llamadas_Manager.call(LoginActivity.this, getIntent().getExtras());

How to turn off the alarm?

My App goes like this:
When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.
When you tap the Start button, the "service" is started.
Now if you remove the AC charger you will hear an alarm sound.
Connecting the AC with the device again should stop the alarm but it does NOT.
Now removing the AC again starts another alarm. The alarms overlap.
Can you help me find the bug?
Thanks
My work so far:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yousef.mustafa.antitheft">
<application
android:allowBackup="true"
android:icon="#mipmap/antitheft"
android:label="#string/app_name"
android:roundIcon="#mipmap/antitheft"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PowerConnectionReceiver">
</receiver>
</application>
</manifest>
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button startServiceButton;
PowerConnectionReceiver powerConnectionReceiver;
BroadcastReceiver powerDisconnectedBroadcastReceiver;
BroadcastReceiver powerConnectedBroadcastReceiver;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
powerConnectionReceiver = new PowerConnectionReceiver(true);
startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (startServiceButton.isActivated()) {
unregisterReceiver(powerDisconnectedBroadcastReceiver);
unregisterReceiver(powerConnectedBroadcastReceiver);
Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
startServiceButton.setActivated(false);
} else {
monitorBatteryChanges();
}
}
});
}
private void monitorBatteryChanges() {
IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);
IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);
Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
startServiceButton.setActivated(true);
}
}
PowerConnectionReceiver.java
public class PowerConnectionReceiver extends BroadcastReceiver {
MediaPlayer mediaPlayer = new MediaPlayer();
// Determine whether the AC is disconnected or not
private boolean POWER_DISCONNECTED = true;
PowerConnectionReceiver(boolean disconnected) {
this.POWER_DISCONNECTED = disconnected;
}
#Override
public void onReceive(Context context, Intent intent) {
if (POWER_DISCONNECTED) {
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
mediaPlayer.setLooping(true);
//POWER_DISCONNECTED = false;
} else {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The bug is in your complex code.
You register two different instances of PowerConnectionReceiver one for "connected" and another for "disconnected" events. So MediaPlayer is started in "connected" receiver, and you try to stop MediaPlayer in "disconected", but it doesn't play.
You should remove POWER_DISCONNECTED field, and handle event in a single instance of receiver. You can register a single receiver for multiple events and use intent.getAction() to check how to handle it.
UPD
Also you can make your receiver singleton, to prevent multiple registrations, and playing of multiple MediaPlayers
I was finally able to find a solution.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button startServiceButton;
BroadcastReceiver powerConnectionBroadcastReceiver;
IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
powerConnectionBroadcastReceiver = new PowerConnectionBroadcastReceiver();
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (startServiceButton.isActivated()) {
unregisterReceiver(powerConnectionBroadcastReceiver);
startServiceButton.setActivated(false);
Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
} else {
monitorBatteryChanges();
}
}
});
}
private void monitorBatteryChanges() {
registerReceiver(powerConnectionBroadcastReceiver, powerDisconnectedIntentFilter);
registerReceiver(powerConnectionBroadcastReceiver, powerConnectedIntentFilter);
startServiceButton.setActivated(true);
Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
}
}
PowerConnectionBroadcastReceiver.java
public class PowerConnectionBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_1);
mediaPlayer.start();
mediaPlayer.setLooping(true);
Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
} else {
try {
if (mediaPlayer != null)
mediaPlayer.release();
Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
It may not be the best solution but it works :)
Thanks for the help.

How to update a service running in a separate process when the Android app is updated?

When I update the app to a new version, the service that was installed with the previous app version is still running. When I update the app the second time, the updated service is running properly.
However, after first update, whenever i close the app or restart the phone the service from the previous version is running.
How can i force the new service to run as soon as the app is updated.
Here is my code
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.djuro.updateservicewithappupdate">
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:process=":myService" />
<receiver android:name=".PackageReplacedReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REMOVED" />
<data android:scheme="package" android:path="com.djuro.updateservicewithappupdate"/>
</intent-filter>
</receiver>
</application>
</manifest>
App.java
public class App extends Application {
private static final String TAG = App.class.getName();
private static App mInstance;
private Messenger myServiceMessenger;
private boolean isBound;
private Messenger replyMessenger = new Messenger(new IncomingHandler());
#Override
public void onCreate() {
super.onCreate();
if (mInstance == null) {
mInstance = this;
startMyService();
}
isBound = false;
// start the chore service (if it is not running) and bind to it
}
public void startMyService() {
startService(new Intent(mInstance, MyService.class));
doBindService();
}
public void stopMyService() {
doUnBindService(true);
stopService(new Intent(mInstance, MyService.class));
}
public static App getInstance() {
return mInstance;
}
public static Context getContext() {
return mInstance.getApplicationContext();
}
public static Messenger getChoreMessenger() {return mInstance.myServiceMessenger;}
#Override
public void onTerminate() {
doUnBindService(false);
super.onTerminate();
}
private void doBindService() {
if (!isBound) {
Log.d(TAG, "Binding ChoreService.");
bindService(new Intent(this, MyService.class), myServiceConnection, Context.BIND_AUTO_CREATE);
isBound = true;
}
}
private void doUnBindService(boolean restartService) {
if (isBound) {
Log.d(TAG, "Unbinding ChoreService.");
if (myServiceMessenger != null) {
try {
Message msg = Message.obtain(null, MyService.UNREGISTER_CLIENT);
msg.replyTo = replyMessenger;
replyMessenger.send(msg);
}
catch (RemoteException e) {
// There is nothing special we need to do if the service has crashed.
}
}
if (restartService) {
try {
Message msg = Message.obtain(null, MyService.STOP_SERVICE_ON_UNBIND);
msg.replyTo = replyMessenger;
replyMessenger.send(msg);
}
catch (RemoteException e) {
// There is nothing special we need to do if the service has crashed.
}
}
unbindService(myServiceConnection);
isBound = false;
} else if (restartService) {
stopService(new Intent(mInstance, MyService.class));
}
}
private ServiceConnection myServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
myServiceMessenger = new Messenger(service);
Log.d(TAG, "connected to service");
try {
Message msg = Message.obtain(null, MyService.REGISTER_CLIENT);
msg.replyTo = replyMessenger;
myServiceMessenger.send(msg);
}
catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
public void onServiceDisconnected(ComponentName className) {
myServiceMessenger = null;
Log.d(TAG, "disconnected from ChoreService");
}
};
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
}
}
}
MyService.java
public class MyService extends Service {
private static final String TAG = MyService.class.getName();
public static final int UNREGISTER_CLIENT = 1;
public static final int REGISTER_CLIENT = 2;
public static final int STOP_SERVICE_ON_UNBIND = 3;
final Messenger messenger = new Messenger(new IncomingHandler());
private String appVersion;
private boolean stopOnUnbind;
private int boundCount = 0;
// called when the intent starts the Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
Log.d(TAG, "onStartCommand()");
getVersion();
return START_STICKY;
}
// called once at creation (before onStartCommand)
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
// used to bind intent to service
#Nullable
#Override
public IBinder onBind(Intent intent) {
//doStopForeground();
boundCount ++;
Log.d(TAG, "bound count: " + boundCount);
return messenger.getBinder();
}
#Override
public boolean onUnbind(Intent intent) {
boundCount --;
Log.d(TAG, "bound count: " + boundCount);
boolean result = super.onUnbind(intent);
if (stopOnUnbind) {
Log.d(TAG, "stopSelf()");
stopSelf();
}
return result;
}
// called when the service is destroyed
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy()");
super.onDestroy();
}
public void getVersion() {
try {
PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
appVersion = pInfo.versionName;
Log.d(TAG, "appVersion: " + appVersion);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Log.d(TAG, "IncomingHandler handling message. msg.what= " + msg.what);
switch (msg.what) {
case STOP_SERVICE_ON_UNBIND:
stopOnUnbind = true;
break;
default:
super.handleMessage(msg);
break;
}
}
}
}
PackageReplacedReceiver.java
public class PackageReplacedReceiver extends BroadcastReceiver {
private static final String TAG = PackageReplacedReceiver.class.getName();
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "package updated");
App.getInstance().stopMyService();
}
}
Use android.intent.action.MY_PACKAGE_REPLACED action in your intent filer and stop your service from broadcast receiver.
<receiver android:name=".PackageReplacedReceiver" android:enabled="#bool/is_at_least_api_12" > <intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>

How to start my application process when a android device is rebooted?

I am making app which tracks user location continuously, so far I have been able to make a successful receiving of its ordinate on location change, but if he is restarting the phone than I am not able to start my service without user again opening the app.
This is my Servicesstart.java code
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("service started", "start");
userFunctions = new UserFunctions();
final LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(userFunctions.isUserLoggedIn(getApplicationContext())){
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei=telephonyManager.getDeviceId();
Toast.makeText(getApplicationContext(), imei, 5000).show();
if(Broadcast.check==false)
{
final UserFunctions userFunction = new UserFunctions();
LocationListener locatioListner = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
get();
}
public void onLocationChanged(Location location) {
Log.i("location", "loc");
String latitude=String.valueOf(location.getLatitude());
String longtitude=String.valueOf(location.getLongitude());
//location updated starts here
boolean check_update=userFunction.locationUpdater(UserFunctions.email, latitude, longtitude,imei);
if(check_update==true){
Log.i("updated", "update");
}
else
{
Log.i("notupdated","not");
}
}
};
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locatioListner);
}
}
}
this is my Broadcast.java code
public class Broadcast extends BroadcastReceiver {
public static boolean check=true;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
check=false;
Intent i = new Intent(context,Servicestart.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(i);
}
}
}
This my manifest.xml code
<service android:name=".Servicestart">
</service>
<receiver android:name=".Broadcast"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Add this permission in manifest and add this broadcast receiver class in your application.
I have added my service ServiceStarter to start first, replace this with yours
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("Reciver Started..........................................");
Intent activate = new Intent();
activate.setClass(context, **ServiceStarter.class**);
// activate.putExtra("Auto", true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, activate,
Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 20000, pendingIntent);
}
}

show toast when connectivity changes

I built an app that streams audio using a webview. Now I added a check if there's connectivity (or not). Using toast I show a message with "true" or "false", but I'd like show a toast only when the connectivity changes. What should I do?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
update();
private void update() {
new Thread() {
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
isOnline();
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Toast.makeText(getApplicationContext(), "true",Toast.LENGTH_LONG).show();
return true;
}
Toast.makeText(getApplicationContext(), "false",Toast.LENGTH_LONG).show();
return false;
Try this :
public class BroadCastSampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
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()){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}
Add this permission in your Manifest :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The ConnectivityManager broadcasts the CONNECTIVITY_ACTION ("android.net.conn.CONNECTIVITY_CHANGE") action whenever the connectivity details have changed. You can register a broadcast receiver in your manifest to listen for these changes and resume (or suspend) your background updates accordingly.
That comes from the android developer information.
You can read more here: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
That should have everything you need to show the toast notifications.
You should register for android.net.conn.CONNECTIVITY_CHANGE. And show a dialog only on receiving the intent.
You can create an inner class that extends a BroadcastReceiver and shows a toast in it's onReceive method.
That should work :)

Categories

Resources