I'm trying to write the codes for my project that's to play a music when WiFi connection is disconnected and also whenever user clicks 'test' button it display the current connection strength. I've tried the following code:
Main activity part (for the test button and call out the class AlarmManagerBroadcastReceiver :
public class MainActivity extends FragmentActivity {
public static final String TAG = "Final Year Project";
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
private LogFragment mLogFragment;
private AlarmManagerBroadcastReceiver alarm ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(alarm, intentFilter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// When the user clicks TEST, display the connection status.
case R.id.test_action:
checkNetworkStrengh();
return true;
// Clear the log view fragment.
case R.id.clear_action:
mLogFragment.getLogView().setText("");
return true;
}
return false;
}
private void checkNetworkStrengh() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo Info = cm.getActiveNetworkInfo();
if (Info == null || !Info.isConnectedOrConnecting()) {
Log.i(TAG, "No connection");
} else {
int netType = Info.getType();
int netSubtype = Info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
Log.i(TAG, "Wifi connection");
WifiManager wifiManager = (WifiManager) getApplication().getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scanResult = wifiManager.getScanResults();
for (int i = 0; i < scanResult.size();) {
Log.d("scanResult", "Speed of wifi" + scanResult.get(i).level);//The db level of signal //
// its okay now thanks guys //
}
} else if (netType == ConnectivityManager.TYPE_MOBILE) {
Log.i(TAG, "GPRS/3G connection");
// Need to get differentiate between 3G/GPRS
}
}
}
}
AlarmManagerBroadcastReceiver part (created in order to scan the current network connectivity all the time):
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// Wifi is connected
Intent in = new Intent(context, RingService.class);
context.stopService(in);
} else {
Intent in = new Intent(context, RingService.class);
context.startService(in);
}
}
}
and the MusicService part(created in order to play a music whenever the class AlarmMAnagerBroadcastReceiver triggered the specific condition):
public class MusicService extends Service{
private MediaPlayer mp;
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
mp.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
try {
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
super.onStart(intent, startId);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
try {
mp = new MediaPlayer();
mp = MediaPlayer.create(MusicService.this, R.raw.ly);
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Manifest file
<service
android:name="com.example.android.basicnetworking.RingService"
android:exported="true"
android:process=":remote" >
</service>
<receiver android:name=".AlarmManagerBroadcastReceiver" >
<intent-filter android:priority="100" android:enabled="true"
android:label="ConnectivityActionReceiver">
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Can someone who's professional in android programming helps me in the code cause i'm new in android and java programming) to get return to checkConnectivity class in the AlarmManagerBroadcastReceiver part, and also to play a music when the wifi connection is lost.
Edit: thanks for the helps. I have figured it out. If anyone need the codes you can inbox me or I will upload the complete coding once everything is ok.
Edit: updated some code
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int numberOfLevels = 5;
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);
When you try to play the music AGAIN, then you need to prepare it again, so every time before start call prepare as well:
add this to AlarmManagerBroadcastReceiver:
void play(int musicId) {
MediaPlayer mp = MediaPlayer.create(getContext(), musicId);
mp.prepare();
mp.start();
}
and in checkConnectivity where you want to play music:
play(R.raw.ly); // or use other resource instead of ly
play sound on disconnection... try this:
public class NetworkReceiver extends BroadcastReceiver {
static boolean isConnect = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "network changed");
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d(TAG, "network type wifi"); // connected on wifi
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.d(TAG, "network type mobile"); // connected on mobile (3g/4g)
}
} else {
isConnect = false;
Log.d(TAG, "no connection"); // DISCONNECTED
playMySound(); // <- your play sound function
}
}
public void playMySound() {
MediaPlayer sound = MediaPlayer.create(context, R.raw.song);
sound.start();
}
}
Related
I build the dialogue box for my android app. Its working well, but i encountered some issues related to the dialogue box.
(1) I want when internet connection or WiFi get connected. automatically dialogue box get disappeared.
(2) In middle of the app is running if internet connection get lost. dialogue box again appears automatically.
if (!isConnected(Dashboard.this)) buildDialog(Dashboard.this).show();
else {
setContentView(R.layout.activity_dashboard);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or WiFi to access this. Press OK to Exit");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Dashboard.super.onBackPressed();
}
});
return builder;
}
Use properties builder.setCancelable(false); in your aleart dailog
Put this line out of the alert dialog code
alertDialog.setCancelable(false);
To automatically get internet connectivity events try setting up a network change listener. Here is a sample:
/**
* Broadcast receiver that detects receives notification when change in internet connection to alert when there is no Internet.
*/
public class NetworkChangeReceiver extends BroadcastReceiver {
private NetworkChangeListener mListener;
public NetworkChangeReceiver(NetworkChangeListener listener) {
mListener = listener;
}
#Override
public void onReceive(final Context context, #NonNull final Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean connected = activeNetwork != null && activeNetwork.isConnected();
mListener.onNetworkConnectedStateChanged(connected);
}
}
public interface NetworkChangeListener {
void onNetworkConnectedStateChanged(boolean connected);
}
}
You then register the listener in your Activity or Fragment
#Override
public void onStart() {
super.onStart();
if (mNetworkChangeReceiver == null) {
mNetworkChangeReceiver = new NetworkChangeReceiver(this);
getContext().registerReceiver(mNetworkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
Then show / dismiss your dialog on network connected state changed
#Override
public void onNetworkConnectedStateChanged(boolean connected) {
if (connected) {
//dismiss dialog
} else {
//show dialog
}
}
You have to setCancelable == false for stop tounching outside of dialog.
In Your case You have to put like this in your AlertDialog.Builder after setMessage
builder.setCancelable(false);
and Use this functionality for User that on Backpress button You have to setCancelable == true
for that You have to write code in onBackPressed like this :-
builder.setCancelable(true);
You need add Broadcast receiver to get connectivity status.
Then you need to keep builder global.
private AlertDialog.Builder builder;
Just create a BroadcastReceiver to track your internet connectivity
first, create a NetworkChangeReceiver class like this
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
if (isOnline(context)) {
//show dialog when internet on
dialogHome(true);
Log.e("pradeep", "Online Connect Internet ");
} else {
//hide dialog when internet off
dialogHome(false);
Log.e("pradeep", "Connectivity Failure !!");
}
} catch (NullPointerException e) {
e.printStackTrace();
Log.i(getClass().getName(), "exceptional " + e.toString());
}
}
public boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
after that just add below code in application tag which is located in AndroidMenifest.xml
<receiver android:name=".utils.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Final step
just create your BroadcastReceiver instance in your activity where you check the internet activity
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//init broadcast receiver
mNetworkReceiver = new NetworkChangeReceiver();
}
#Override
protected void onResume() {
super.onResume();
if (((NetworkChangeReceiver) mNetworkReceiver).isOnline(mContext)) {
} else {
registerNetworkBroadcastForNougat();
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
Log.i(getClass().getName(), "easdfdf" + e.toString());
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
Log.i(getClass().getName(), "easdfdfdd" + e.toString());
}
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
whenever internet connection changes BroadcastReceiver call onReceive Method.
Hope helpful for you...
In my app there is a media player which is playing streamed url.
The player starts in oncreate method when the connection to internet is available.I have a broadcast receiver which checks the connection to the internet and notify the user. I am facing a problem here that when my app shifts from Wifi to cellular network, media player should take a little pause and starts again because the network is available again. But i'am unable to find the logic that how can i achieve this?
Here is my sample code,Kindly solve the issue?
Any help will be grateful.
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<receiver android:name=".receivers.NetworkChangeReciever">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Main Activity:
private BroadcastReceiver mNetworkReceiver;
static TextView tv_check_connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_check_connection=(TextView) findViewById(R.id.tv_check_connection);
mNetworkReceiver = new NetworkChangeReciever();
registerNetworkBroadcastForNougat();
// checkNetworkStatus();
mSelectedTrackTitle = (TextView) findViewById(R.id.selected_track_title);
nowplaying = (TextView) findViewById(R.id.nowplaying);
mPlayerControl = (ImageView) findViewById(R.id.player_control);
mPlayerControl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
togglePlayPause();
}
});
mSelectedTrackTitle.setText("FM World Pakistan");
nowplaying.setText("Now Playing");
mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mMediaPlayer.setDataSource(url);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mMediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
nowplaying.setText("Offline");
Toast.makeText(MainActivity.this, "Radio Offline", Toast.LENGTH_LONG).show();
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
}
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundResource(R.color.neton);
tv_check_connection.setTextColor(Color.WHITE);
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
#Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not connect to Internet.");
tv_check_connection.setBackgroundResource(R.color.colorAccent);
tv_check_connection.setTextColor(Color.WHITE);
nowplaying.setText("Buffering...");
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
private void togglePlayPause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
nowplaying.setText("Offline");
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
} else {
mMediaPlayer.start();
nowplaying.setText("Now Playing");
mPlayerControl.setImageResource(R.drawable.ic_pause_circle_filled);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
}
Receiver Class:
public class NetworkChangeReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try
{
if (isOnline(context)) {
dialog(true);
Log.e("Hi", "Online Connect Intenet ");
} else {
dialog(false);
Log.e("Sorry","Conectivity Failure !!! ");
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
I found a solution as, if media player is declared as static; we can reinitialize it in dialog()
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundResource(R.color.neton);
tv_check_connection.setTextColor(Color.WHITE);
//recreate media player
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
#Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not connect to Internet.");
tv_check_connection.setBackgroundResource(R.color.colorAccent);
tv_check_connection.setTextColor(Color.WHITE);
nowplaying.setText("Buffering...");
mPlayerControl.setImageResource(R.drawable.ic_play_circle_filled);
//pause media player
}
}
I want to track user location continuously even after they close the app. The service continuously stores location on DB and a wakefulintent starts a timertask to upload it to server. I have used
LocationServices.FusedLocationApi.requestLocationUpdates(Utils.googleApiClient,
mlocationrequest, this);
on a service. I have declared service on manifest as
<service
android:name="com.projest.services.BackgroundService"
android:enabled="true"
android:process=":Background">
</service>
and called servicew on my main activity using
Intent service = new Intent(this, BackgroundService.class);
startService(service);
but the service is not working. I couldn't see log.
public class BackgroundService extends Service implements LocationListener{
public static final String TAG = "BackgroundService";
Context context;
LocationRequest mlocationrequest;
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
public BackgroundService(Context context){
this.context = context;
}
public BackgroundService(){
}
public void onCreate(){
try{
super.onCreate();
if(Utils.DEBUG)Log.d(TAG,"inside onCreate");
}catch(Exception e){
if(Utils.DEBUG)Log.d(TAG,"problem oncreate");
}
}
public int onStartCommand(){
if(Utils.DEBUG)Log.d(TAG,"inside onStartCommand");
if(!Utils.startGpsTracker)
{
Utils.startGpsTracker=true;
toggleGPS(true);
}
buildGoogleApiClient();
Utils.googleApiClient.connect();
if (Utils.googleApiClient.isConnected()) {
startLocationUpdates();
}
return START_STICKY;
}
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
if (Utils.latestLocation == null) {
Utils.latestLocation = LocationServices.FusedLocationApi.getLastLocation(Utils.googleApiClient);
if(Utils.DEBUG)Log.d(TAG,"inside onconnected");
try {
storeGpsinDb();
if(Utils.DEBUG)Log.d(TAG,"trouble opening storeGPS");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
startLocationUpdates();
}
private void startLocationUpdates() {
// TODO Auto-generated method stub
try {
if (Utils.googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(Utils.googleApiClient, mlocationrequest, this);
if(Utils.DEBUG)Log.d(TAG,"inside startlocationupdates");
}
} catch (SecurityException ex) {
}
}
#Override
public void onLocationChanged(Location location) {
Utils.latestLocation = location;
try {
storeGpsinDb();
if(Utils.DEBUG)Log.d(TAG,"inside onlocationchanged");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected synchronized void buildGoogleApiClient() {
if (Utils.googleApiClient == null) {
Utils.googleApiClient = new GoogleApiClient.Builder(this.context).addApi(LocationServices.API).build();
if(Utils.DEBUG)Log.d(TAG,"googleAPIclient");
}
createLocationRequest();
}
private void createLocationRequest() {
// TODO Auto-generated method stub
mlocationrequest = new LocationRequest();
mlocationrequest.setInterval(UPDATE_INTERVAL);
mlocationrequest.setFastestInterval(FATEST_INTERVAL);
mlocationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if(Utils.DEBUG)Log.d(TAG,"inside createlocationrequest");
}
public void onConnectionSuspended(int cause) {
Utils.googleApiClient.connect();
if(Utils.DEBUG)Log.d(TAG,"insise connectionsuspended");
}
#Override
public void onDestroy() {
if(Utils.DEBUG)Log.d(TAG,"inside onDestroy");
stopLocationUpdates();
Utils.googleApiClient.disconnect();
super.onDestroy();
}
protected void stopLocationUpdates() {
if (Utils.googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(Utils.googleApiClient, this);
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private void toggleGPS(boolean enable) {
String provider = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(Utils.DEBUG)System.out.println("toggleGPS:" + provider);
if (provider.contains("gps") == enable) {
if(Utils.DEBUG)System.out.println("toggleGPS:enable true");
return; // the GPS is already in the requested state
}
if(Utils.DEBUG)System.out.println("toggleGPS:enable false");
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.context.sendBroadcast(poke);
}
private void storeGpsinDb() throws IOException {
if (!(Utils.latestLocation==null)) {
}else{
}
// }
}
}
What mistake am I making
I am working two weeks on this.Please help me.
you need to define android:stopWithTask="false" in manifest.
the process(Threads) run from the service will stop working if your app is removed from the recent apps. To ensure that your processes(Threads) remains always in running condition you have to Override onTaskRemoved() method and add code to restart Tasks like below.
#Override
public void onTaskRemoved(Intent rootIntent){
Intent restartServiceTask = new Intent(getApplicationContext(),this.getClass());
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
super.onTaskRemoved(rootIntent);
}
i am currently doing a project based on network connections.I am developing an app in which network connection is checked regularly.If there is no connection, a progress dialog should spin showing "No network connection" until the user himself turn the wifi on or any other kind of internet connection .After the wifi is turned on and if the app connects with wifi then the progress dialog should close and the control should pass to another activity. I have searched this in google for many times but didn't get a satisfactory answer. Below are my codes:
public class Alert extends Activity implements Runnable{
ProgressDialog pd;
WifiManager wm,wifiManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert);
wm = (WifiManager) getSystemService(WIFI_SERVICE);
if(!wm.isWifiEnabled()) {
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
Thread t = new Thread(this);
t.start();
}
}
#Override
protected void onResume() {
super.onResume();
if(wm.isWifiEnabled()) {
pd.dismiss();
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while(wm.getWifiState() != 3) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To check network connection, use ConnectivityManager class.
Add below method to your activity and call it to check network connection, if it returns true then it means network is available otherwise not.
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Now do it in your onCreate(...) method
if(!isNetworkAvailable(Alert.this)) {
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
Thread t = new Thread(this);
t.start();
}else{
if(pd != null && pd.isShowing()){
pd.dismiss();
}
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
Hope this will help you.
Try like this using Handler, It may work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert);
wm = (WifiManager) getSystemService(WIFI_SERVICE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if(!wm.isWifiEnabled()) {
runOnUiThread(new Runnable() {
public void run() {
if(pd == null)
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
}
});
}else{
runOnUiThread(new Runnable() {
public void run() {
if(pd != null)
pd.dismiss();
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
});
}
handler.postDelayed(this, 5000); //now is every 2 minutes
}
}, 5000);
}
#Override
public void run() {
// TODO Auto-generated method stub
while(running) {
try {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
// you got a connection! tell your user!
Log.i("Post", "Connected");
running=false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
pd.dismiss();
}
});
Intent intent_service=new Intent(this, anotherActivity.class);
context.startService(intent_service);
}
}
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Put this class in your project:
public class Utility {
public static boolean isNetworkConnected(Context context){
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
connected = (cm.getActiveNetworkInfo() != null&&cm.getActiveNetworkInfo().isAvailable() && cm
.getActiveNetworkInfo().isConnected());
return connected;
}
public static void showAlert(final Activity activity, final String message,final String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message).setTitle(title).setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
activity.finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static void showAlertValidation(final Activity activity,final String message,final String title){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message).setTitle(title).setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int id){
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
This class detects if your internet connection is on or not. After that in your activity, put the following code:
if(Utility.isNetworkConnected(Alert.this))
{
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}
else if(!Utility.isNetworkConnected(Alert.this))
Utility.showAlert(Alert.this,"Internet Connection Not Present.","Network Error!");
Check and see if your problem is solved or not.
Check this link,
Depends on internet state change you can call your activity.
Hope this will solve your problem
I'm developing an application. When i exit from the application, it will be opened again (The first activity is called again and again). So i couldn't able to exit from it.
In some other activities I use EXIT button and proper code to exit. Even when I click the EXIT button on those activities, it will start login activity. (login page is opened)
In my application, I use
1) Main
2) ScreenActivity
3) Login
flow: (from main->screenActivity->login)
The start page (1st activity) is posted below
public class main extends Activity {
static ConnectivityManager conMgr;
BackgroundThread backgroundThread;
TextView myText;
boolean myTextOn = true;
Cursor cursor;
String response="";
public SQLiteAdapter mySQLiteAdapter;
private SQLiteDatabase sqLiteDatabase;
SimpleCursorAdapter cursorAdapter;
public class BackgroundThread extends Thread {
boolean running = false;
void setRunning(boolean b){
running = b;
}
#Override
public void run() {
// TODO Auto-generated method stub
//super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
handler.sendMessage(handler.obtainMessage());
}
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread);
myText = (TextView)findViewById(R.id.mytext);
}
#Override
protected void onStart() {
conMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
// TODO Auto-generated method stub
super.onStart();
if(isInternetAvailable())
{
Toast.makeText(this, "online", Toast.LENGTH_LONG).show();
startActivity(new Intent(main.this, ScreenActivity.class));
}
else{
startActivity(new Intent(main.this, splashscreen.class));
Toast.makeText(this, "offline", Toast.LENGTH_LONG).show();
}
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}
private boolean isInternetAvailable() {
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
backgroundThread.setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e)
{
}
}
}
public void onDEstroy()
{
super.onDestroy();
}
}
ScreenActivity:
public class ScreenActivity extends Activity implements AnimationListener {
private TextView animatedView3;
//ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
/* Animation animation1 = AnimationUtils.loadAnimation(this,
R.anim.anima);
animation1.setAnimationListener(this);
View animatedView1 = findViewById(R.id.aet1);
animatedView1.startAnimation(animation1);
/** set time to splash out */
final int welcomeScreenDisplay = 9000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
System.out.println("EXc=" + e);
} finally {
/**
* Called after splash times up. Do some action after splash
* times up. Here we moved to another main activity class
*/
startActivity(new Intent(ScreenActivity.this,
login.class));
}
}
};
welcomeThread.start();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
//Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
if (animatedView3.getVisibility() == View.VISIBLE) {
animatedView3.setVisibility(View.INVISIBLE);
} else {
animatedView3.setVisibility(View.VISIBLE);
}
}
public void onAnimationRepeat(Animation animation) {
// Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
}
}
Please can anyone explain about the problem and how to solve it? I didn't understand.
Place finish() in your loginActivity and for other Activities as well else stack will store the list of visited Activities.