I'm starting with android studio and I was trying that the application check the connectivity before to start, for this I'm creating an splash screen, but I really don't find the way to calculate the time for checking the connectivity, my requirement is that the splash screen only stay visible while I'm checking the connectivity.
This is what I have in my onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int myTimer = 4000;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Splash.this, DashBoard.class);
boolean result = AppManager.CheckConnectionStatus(getApplicationContext());
if(result == true) {
startActivity(i);
}
else{
//Show a Message informing there is not internet connection
}
finish();
}
}, myTimer);
setContentView(R.layout.activity_splash);
}
As you can see I'm waiting 4000 ms but this is not the idea...
If any have any idea of how can I face this I will be grateful.
As i understand, you want to check network availability and then if available go start MainActivity. You can check network availability with this function:
public boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null){
return false;
}
else{
return true;
}
}
Then add this codes on your SplashScreen activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Intent i = new Intent(Splash.this, DashBoard.class);
if(isInternetAvailable(Splash.this)){
startActivity(i);
finish();
}
else{
Toast toast = Toast.makeText(Splash.this,
"Please check your internet options...", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
finish();
}
}
Do not forget to add this permissions to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I wish i could understand you right. Good luck.
You can use an AsyncTask in this case. Here's some simple code to get you started:
public class CheckConnectionAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Display some waiting progress bar or a splash image here
}
#Override
protected Boolean doInBackground(Void... params) {
return AppManager.CheckConnectionStatus(getApplicationContext());
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(aBoolean);
if (result) {
// start next activity
} else {
// error message that you're not connected.
}
}
}
Hope it helps!
Related
How to play android radio with screen off background playable option. My App working fine without backgournd playing option. But I want to give background playing option in my app that is when user closes the app, the radio should keep on playing, untill user stops it.
I am also disable screen off option in xml file with android:keepScreenOn="true" option but I want to remove this option and keep mobile screen off and play my app in background.
This is my code
Button BPlay;
String stream = "http://stream.zeno.fm/hmzuvfwn9k0uv";
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
BPlay = (Button) findViewById(R.id.b_play);
BPlay.setEnabled(false);
BPlay.setText("Loading.....");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
BPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started){
started = false;
mediaPlayer.pause();
BPlay.setText("PLAY");
} else {
started = true;
mediaPlayer.start();
BPlay.setText("PAUSE");
}
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings [0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
BPlay.setEnabled(true);
BPlay.setText("PLAY");
}
}
#Override
protected void onPause() {
super.onPause();
if (started){
mediaPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if (started){
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prepared){
mediaPlayer.release();
}
}
}
In order to have you media playing while the app is in the background, you'll need a MediaSession background Service running in parallel.
TLTR, here's a basic tutorial from Google on how to do that.
I tried to change the orientation of my device on recycler view but it always crashes when progress dialog shows up.
How to solve this?
Here is my code:
private class LoadOrdersListAgent extends AsyncTask {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(OrdersActivity.this);
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders_agent);
emptytv = findViewById(R.id.empty_view_orders_agent);
emptytv.setVisibility(View.GONE);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
rvor.setItemAnimator(new DefaultItemAnimator());
dialog.setMessage("Loading....");
dialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
final OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
srl.setRefreshing(false);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (ordersList.isEmpty()) {
Log.d("TESTING.....", "LIST OF ORDERS ----->" + ordersList);
rvor.setVisibility(View.GONE);
srl.setVisibility(View.GONE);
emptytv.setVisibility(View.VISIBLE);
} else {
rvor.setVisibility(View.VISIBLE);
srl.setVisibility(View.VISIBLE);
emptytv.setVisibility(View.GONE);
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
ordersList = OrdersApi.getOrders(url, key);
return null;
}
}
private void swipeOrderLayout() {
srl = findViewById(R.id.swipe);
srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
new LoadOrdersListAgent().execute();
// new LoadOrdersListAdmin().execute();
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
srl.setRefreshing(false);
}
});
}
I got this error when i was Finishing/Destroying the activity without Dismissing progress Dialogue.
Solution use dialog.dismiss(); to dismiss the progress dialogue before destroying or pausing the activity
in your case remove the if condition and just call dialog.dismiss(); in postExecute method
Declare your ProgressDialog in Global using :
Add this code above onCreate() :
private ProgressDialog dialog;
Add this code within a onCreate():
dialog = new ProgressDialog(OrdersActivity.this);
dialog.setMessage("Loading....");
dialog.show();
Add this code within as onPreExecute method ,
if (!dialog.isShowing()) {
dialog.show();
}
this is my base activity that extends class activity. I make my other activities extend this base class:
public abstract class Base extends Activity {
private BroadcastReceiver netStateReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
}
protected abstract int getLayoutResourceId();
#Override
protected void onPause() {
if (netStateReceiver != null) {
unregisterReceiver(netStateReceiver);
netStateReceiver = null;
}
super.onPause();
}
#Override
protected void onResume() {
if (netStateReceiver == null) {
netStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final Dialog offline = new Dialog(context, android.R.style.Theme_Light);
//A change occurred in connection state. Check whether user has been become online or offline:
if (!CheckNet()) {
//User became offline (show offline dialog):
offline.setContentView(R.layout.activity_offline);
offline.setTitle("offline");
offline.getWindow().setBackgroundDrawableResource(R.color.transparent);
offline.show();
final Button retry = (Button) offline.findViewById(R.id.button6);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CheckNet()) {
offline.dismiss();
}
}
});
}
else {
//User became online (dismiss offline dialog):
if (offline.isShowing()) {
offline.dismiss();
}
}
}
};
registerReceiver(netStateReceiver, new IntentFilter(Values.CONNECTIVITY_RECEIVER_ACTION));
}
super.onResume();
}
private boolean CheckNet() {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
return (activeNetwork != null && activeNetwork.isConnectedOrConnecting());
}
}
As you see in code I have registered a receiver for checking connectivity status.
I want when user becomes offline a dialog be shown to user and notify him that he is offline and should become online to continue. This part works good.
I also want when that dialog is showing and in the moment user becomes online this dialog be dismissed, but this part doesn't work and dialog stays on the display.
What's the problem, how can I dismiss the dialog?
You create a new dialog on every broadcast instead of using the dialog you already created before.
Make the dialog variable a member variable of the activity class, then it should work.
private Dialog offline;
#Override
protected void onResume() {
if (netStateReceiver == null) {
netStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
if (!CheckNet()) {
if(offline==null || !offline.isShowing()){
offline = new Dialog(context, android.R.style.Theme_Light);
}
...
} else {
//User became online (dismiss offline dialog):
if (offline!=null && offline.isShowing()) {
offline.dismiss();
}
}
Make it global access to your dialog object reference :
final Dialog offline = new Dialog(context, android.R.style.Theme_Light);
Then you will able to close your dialog.
You are creating a new dialog everytime you receive a broadcast, so the dialog you dismissed is a whole different dialog than the one used to show "you are currently offline".
Try putting your "offline" dialog in the activity instead of within the onReceive callback.
A simple example would be:
public abstract class Base extends Activity {
private BroadcastReceiver netStateReceiver;
final Dialog offline;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
// You create the dialog here instead within the onReceive callback
offline = new Dialog(this, android.R.style.Theme_Light);
offline.setContentView(R.layout.activity_offline);
offline.setTitle("offline");
offline.getWindow().setBackgroundDrawableResource(R.color.transparent);
}
#Override
protected void onResume() {
if (netStateReceiver == null) {
netStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
if (!CheckNet()) {
// Your dialog already exists, just show it immediately
offline.show();
final Button retry = (Button) offline.findViewById(R.id.button6);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CheckNet()) {
offline.dismiss();
}
}
});
}
else {
//User became online (dismiss offline dialog):
if (offline.isShowing()) {
offline.dismiss();
}
}
}
};
registerReceiver(netStateReceiver, new IntentFilter(Values.CONNECTIVITY_RECEIVER_ACTION));
}
super.onResume();
}
}
I'm using a simple activity (from this library) with ZXing to scan a barcode.
Everything works fine, but the transition between the MainActivity and the ScannerActivity doesn't work well. Halfway through it gets interrupted. When going back from the ScannerActivity to the MainActivity the transition works like desired. Only while loading the barcodescanner it doesn't look really good.
Do you have any idea how to fix this?
MainActivity:
private void invokeScanner() {
try {
Intent intent = new Intent(this, ScannerActivity.class);
stealFocus(et_loadInput);
startActivityForResult(intent,0);
this.overridePendingTransition(R.anim.detail_anim_up, R.anim.detail_anim_down);
} catch (Exception e){
Log.e(TAG, "couldn't open scanner");
e.printStackTrace();
openAlertDialog(Const.MSG_PROCESSING_ERROR);
}
}
ScannerActivity:
public class ScannerActivity extends AbstractTitleBarActivity implements ZXingScannerView.ResultHandler{
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
this.tv_backTitle.setText(getString(R.string.TITLE_SEARCH_VIEW));
this.tv_heading.setText("");
TextView titleClose = (TextView) findViewById(R.id.btn_close);
titleClose.setVisibility(View.VISIBLE);
titleClose.setOnClickListener(titleCloseListener);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
protected boolean isBackBtnVisible() {
return false;
}
#Override
protected boolean isLogoVisible() {
return false;
}
#Override
public void handleResult(Result rawResult) {
Log.v(TAG, rawResult.getText()); // Prints scan results
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
MainActivity.scanVal = rawResult.toString();
MainActivity.loadVal = MainActivity.scanVal;
finish();
overridePendingTransition(R.anim.detail_anim_back_down,R.anim.detail_anim_back_up);
}
// listener for close button
protected TextView.OnClickListener titleCloseListener = new TextView.OnClickListener() {
public void onClick(View v) {
finish();
overridePendingTransition(
R.anim.detail_anim_back_down, R.anim.detail_anim_back_up);
}
};
}
I actually solved my own problem :D with this answer.
I just put the ZXingScannerView into a fragment and added a surface view with 0px height as a sibling. Now the animation works fine and the barcode scanner loads without refreshing the complete activity.
I am developing an feedback kind of application, when I click the "submitnow" button I am getting the following error
Activity has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView#46029dd0
Following is my code, please help me out.
public class SignOut_Activity extends SherlockActivity implements
OnClickListener {
Button btnSubmitNow, btnSubmitLater;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.signout);
((TextView) findViewById(R.id.tvSubTitle))
.setText(StoresListAdapter.StoreName);
btnSubmitNow = (Button) findViewById(R.id.btnSubmitNow);
btnSubmitLater = (Button) findViewById(R.id.btnSubmitLater);
btnSubmitNow.setOnClickListener(this);
btnSubmitLater.setOnClickListener(this);
progressDialog = new ProgressDialog(SignOut_Activity.this);
progressDialog.setMessage("Uploading data, please wait...");
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; finish activity to go home
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
// Set title
getSupportActionBar().setTitle("Sign Out");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmitNow:
// Submit now
// Sample upload image
UploadImage.uploadImage("testimage");
new AsyncTask<Void, Void, Void>() {
// called before execution // main/UI thread
protected void onPreExecute() {
progressDialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Submit the store data
StoreData.postData(StoreList_Activity.storesList
.get(StoresListAdapter.Position));
return null;
}
// on store data uploaded // main/UI thread
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setSignOut();
StoreList_Activity.storesList
.get(StoresListAdapter.Position).isSubmitted = true;
SignOut_Activity.this.finish();
};
}.execute();
break;
case R.id.btnSubmitLater:
// Submit later
setSignOut();
StoreList_Activity.storesList.get(StoresListAdapter.Position).isSubmitLater = true;
VisitOps_Activity.isSubmitLater = true;
SignOut_Activity.this.finish();
break;
default:
break;
}
}
#SuppressLint("SimpleDateFormat")
private void setSignOut() {
VisitOp visitOp10 = new VisitOp();
visitOp10.setName("Sign Out");
visitOp10.setStatus("");
SampleData.visitOpsList.add(visitOp10);
if (VisitOps_Activity.VisitOps.SignOut == null)
VisitOps_Activity.VisitOps.SignOut = new SignOut();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
VisitOps_Activity.VisitOps.SignOut.SignOutTime = "Out: "
+ currentDateandTime;
}
}
Leak comes because you are keeping reference of activity after it destroyed also so use
if(progressDialog !=null)
{
progressDialog = null;
}
progressDialog = new ProgressDialog(this.getApplicationContext());
progressDialog.setMessage("Uploading data, please wait...");
OR
use this it will help
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmitNow:
// Submit now
// Sample upload image
UploadImage.uploadImage("testimage");
new AsyncTask<Void, Void, Void>() {
// called before execution // main/UI thread
protected void onPreExecute() {
progressDialog = new ProgressDialog(SignOut_Activity.this);
progressDialog.setMessage("Uploading data, please wait...");
progressDialog.show();
};
#Override
protected Void doInBackground(Void... params) {
// Submit the store data
StoreData.postData(StoreList_Activity.storesList
.get(StoresListAdapter.Position));
return null;
}
// on store data uploaded // main/UI thread
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setSignOut();
StoreList_Activity.storesList
.get(StoresListAdapter.Position).isSubmitted = true;
SignOut_Activity.this.finish();
};
}.execute();
Why this Error...?
this error happen when you keep reference of unused activity
Solution
remove reference of progress bar , dialog .....etc after use it .
by dismiss them or make them equal null
you can approach this when no longer need of it
Recommended put it in onStop
#Override
protected void onStop() {
super.onStop();
if(_dialog.isShowing()){
_dialog.dismiss();
}
if(_dialog != null){
_dialog = null;
}
}
Dismiss the dialog after its use, it won't let your application crash.
dialog.dismiss();
use that code progressDialog.dismiss();
Make sure you dismiss() the dialog, after dialog use and before any next background process to be initiated.