Hi guys I'm creating simple interactive android application. Server runs Java.
It turns out, that I can not receive files from server.
Android code is following
public class MainActivity extends Activity {
public DataReceiving dataReceiving;
public DataTransfer dataTransfer;
private EditText inputData;
private Button sendParameters;
private Button startComputation;
public TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputData= (EditText) findViewById(R.id.editText1);
sendParameters=(Button) findViewById(R.id.button1);
startComputation=(Button) findViewById(R.id.button2);
displayText=(TextView) findViewById(R.id.textView1);
startComputation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String numberOfGates=inputData.getText().toString();
ArrayList send=new ArrayList();
send.add(numberOfGates);
dataTransfer=new DataTransfer();
dataTransfer.execute(send);
}
});
sendParameters.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dataReceiving=new DataReceiving();
dataReceiving.execute();
}
});
}
public class DataReceiving extends AsyncTask<Void, Void, ArrayList>
{
#Override
protected ArrayList doInBackground(Void... params) {
ArrayList receivedData=new ArrayList();
Log.i("DataReceiving", "doInbackgroung works");
try {
receivedData=receive();
} catch (ClassNotFoundException e) {
Log.e("DataReceiving", "Problems with receive method. Issue with class");
e.printStackTrace();
} catch (IOException e) {
Log.e("DataReceiving", "Problems with receive method. Issue with IO");
e.printStackTrace();
}
return receivedData;
}
#Override
protected void onPostExecute(ArrayList result) {
super.onPostExecute(result);
displayText.setText(result.toString());
}
}
public ArrayList receive () throws IOException, ClassNotFoundException
{
Log.i("receive method", "works");
ServerSocket s= new ServerSocket(8888);
Log.i("receive method", "ServerSocket(8888)");
Socket incoming =s.accept();
Log.i("receive method", "accept()");
ObjectInputStream ios = new ObjectInputStream(incoming.getInputStream());
Log.i("receive method", "ios");
ArrayList b=new ArrayList();
b = (ArrayList) ios.readObject();
Log.i("receive method", "data were received");
ios.close();
incoming.close();
s.close();
return b;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Here is the Log
06-18 18:08:51.709: D/dalvikvm(2160): GC_CONCURRENT freed 69K, 7% free 2760K/2952K, paused 78ms+85ms, total 261ms
06-18 18:08:52.079: D/gralloc_goldfish(2160): Emulator without GPU emulation detected.
06-18 18:09:05.090: I/DataReceiving(2160): doInbackgroung works
06-18 18:09:05.099: I/receive method(2160): works
06-18 18:09:05.099: I/receive method(2160): ServerSocket(8888)
It seems like Socket incoming =s.accept(); doesn't work and I have no idea why
Here is Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Server side is very simple
Socket s=new Socket("192.168.1.110", 8888);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ArrayLIst b = new ArrayList();
b.add("It Works");
oos.writeObject(b);
oos.close();
s.close();
I will be very appreciated for any Ideas, how to fix this problem. Thank you
I think the client part is working right, it stops at the accept method. So the problem is in the server which never gets to connect.
The server part should be like this:
try {
Socket s = new Socket();
InetAddress addr = InetAddress.getByName("192.168.1.110");
SocketAddress sockaddr = new InetSocketAddress(addr, 8888);
s.connect(sockaddr, 20000); // 20 seconds time out
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
ArrayLIst b = new ArrayList();
b.add("It Works");
oos.writeObject(b);
oos.close();
s.close();
}
catch (Exception e)
{
.....
}
Related
I am working on an Android app that will receive multicast packets from a network that already outputs reliable multicast data on 239.255.x.x . I have verified that my device can receive multicast with another application. I'm new to Java and Android but I did confirm that my original code to gather the Multicast info worked in a java application and have been struggling to get everything working in the Android side of things. I have permissions set in the manifest,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
the networking portion of code runs in an Asynctask as to not crash the app but my Multicast.receive() calls all result in a time out.Is there something else I am missing or something that prevents multicast sockets from working in the asynctask class?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new getACN.execute();
}
});
}
public class getACN extends AsyncTask<Void, Void, String> {
#Override
public String doInBackground(Void... Void) {
byte[] buf = new byte[1000];
try {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifiManager.createMulticastLock("sACN");
multicastLock.acquire();
InetAddress group = InetAddress.getByName("239.255.0.3");
DatagramPacket recv = new DatagramPacket(buf,buf.length);
MulticastSocket sock = new MulticastSocket(5568);
sock.joinGroup(group);
sock.setSoTimeout(1000);
sock.receive(recv);
sock.leaveGroup(group);
} catch (IOException e) {
return e.getMessage();
} catch (SecurityException e) {
return e.getMessage();
}
return Arrays.toString(buf);
}
#Override
protected void onPostExecute(String result){
TextView textView = (TextView) findViewById(R.id.text01);
textView.setText(result);
}
}
}
I'm trying to show a progresbar while my MainActivity is loading,
tried this:
public class MainActivity extends Activity {
private ProgressBar spinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
spinner.setVisibility(View.VISIBLE);
...do stuff...
}
public void onStart() {
super.onStart();
openBT();
spinner.setVisibility(View.GONE);
...do stuff...
}
}
Problem: MainActivity is for about 5 seconds blank, and then the MainActivity is loaded. But it's not displaying the progressbar. How do i get ths fixed? And what is my mistake? Thanks!
.xml looks like this:
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true" />
Whole OnCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
spinner.setVisibility(View.VISIBLE);
function1btn = (Button) findViewById(R.id.function1btn);
...
btDataList = new ArrayList<>();
mWaveLoadingView = (WaveLoadingView) findViewById(R.id.waveLoadingView);
mWaveLoadingView.setShapeType(WaveLoadingView.ShapeType.CIRCLE);
mWaveLoadingView.setCenterTitleColor(Color.DKGRAY);
mWaveLoadingView.setCenterTitleStrokeColor(Color.LTGRAY);
mWaveLoadingView.setCenterTitleStrokeWidth(2);
mWaveLoadingView.setProgressValue(100);
mWaveLoadingView.setBorderWidth(10);
mWaveLoadingView.setAmplitudeRatio(20);
mWaveLoadingView.setWaveColor(Color.argb(255,50,205,50)); // green -> 100%
mWaveLoadingView.setBorderColor(Color.DKGRAY);
mWaveLoadingView.setCenterTitle("No BT-Device connected");
mWaveLoadingView.setAnimDuration(3000);
mWaveLoadingView.pauseAnimation();
mWaveLoadingView.resumeAnimation();
mWaveLoadingView.cancelAnimation();
mWaveLoadingView.startAnimation();
final SharedPreferences mPrefsMaxCap = getSharedPreferences("label", 0);
String mString = mPrefsMaxCap.getString("MaxCap", "0");
maxEnergy = Integer.parseInt(mString);
if (maxEnergy != 0){
maxEnergyView.setText(mString);
}
function1btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
function2btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
function3btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
openBT() method:
private void openBT(){
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
Log.d(TAG, "...onStart - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e1) {
errorExit("Fatal Error", "In onStart() and socket create failed: " + e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onStart() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onStart() and output stream creation failed:" + e.getMessage() + ".");
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
call View.GONE in your onResume() method like this..
#Override
protected void onResume() {
super.onResume();
spinner.setVisibility(View.GONE);
}
If you facing a problem when you open the application then set this theme to your launcher activity.
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen"
See the below snippet.
<application
your application name,icon,label etc.>
<activity
android:name="Your main launcher activity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Translucent.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I'm trying to work with a socket output stream. I want to launch it from inside a broad cast receiver.... I believe the socket is working since the client is always receiving a null value.... But the broadcast listener seems to not be working. I seem it's not even registering as even a simple Toast inside it is not working.
I tried to use a broadcast receiver class and registered it via the Manifest. I worked but I don't want that since :
broadcast registered via manifest stay alive even after shuting down the application
I need to use some Main UI class variable/methods/inner class (here for now, that class is ServerReplyThread). Therefore a separate class for the broadcast receiver isn't going to help me much...
Below is my code ; can you help me fix that ?
public class MainActivity extends AppCompatActivity {
public ServerSocket serverSocket;
public ServerSocket getServerSocket() {
return serverSocket;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDemarrer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
});
}
#Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
MainActivity.this.registerReceiver(smsReceived, filter);
sendBroadcast(new Intent("android.provider.Telephony.SMS_RECEIVED"));
}
#Override
public void onPause() {
MainActivity.this.unregisterReceiver(smsReceived);
super.onPause();
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 7777;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
Socket socket = serverSocket.accept();
SocketServerReceiveThread socketServerReplyThread
= new SocketServerReceiveThread(socket);
socketServerReplyThread.run();
}
} catch (IOException e) {
e.printStackTrace();
}}}
private class SocketServerReceiveThread extends Thread {
private Socket hostThreadSocket;
SocketServerReceiveThread(Socket socket) {
hostThreadSocket = socket;
}
#Override
public void run() {
try{
InputStream is = hostThreadSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
//Launch USSD query
}catch(Exception e){
e.printStackTrace();
}}}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
private String sms;
SocketServerReplyThread(Socket socket, String sms) {
hostThreadSocket = socket;
this.sms = sms;
}
#Override
public void run() {
try{
OutputStream os = hostThreadSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
MyClass myclass = new MyClass();
myclass.setSms(sms);
oos.writeObject(dt2);
hostThreadSocket.close();
}catch(Exception e){
e.printStackTrace();
}}}
BroadcastReceiver smsReceived = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().
equals("android.provider.Telephony.SMS_RECEIVED")) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])
bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage smsMessage =
SmsMessage.createFromPdu
((byte[]) pdu);
sb.append("body - " + smsMessage.
getDisplayMessageBody());
}
Toast.makeText(context,sb.toString(),Toast.LENGTH_LONG); //This is not popping up
try {
Socket socket = getServerSocket().accept();
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket,sb.toString());
socketServerReplyThread.run();
} catch (IOException e) {
e.printStackTrace();
}}}}};
}
Below are the permissions of my Manifest
<!-- TELEPHONY SETTINGS-->
<uses-feature
android:name="android.hardware.telephony"
android:required="true" />
<!-- Permission needed to read TelephoneManager data -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- END -->
<!-- Permissions to dial -->
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<!-- END -->
<!-- SMS permissions -->
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<!-- END -->
<!-- END OF TELEPHONY SETTINGS-->
When the SMS came your app is in foreground/visible to user ? If not in foreground/visible you want receive it as you are unregistering receiver in onPause(). If you like to receive it always define receiver in the AndroidMainfes.xml file.
You can register/unregister in onStart() and onStop() of activity life cycle
I want to store an integer to a button. Upon clicking the button, the application sends the integer value to the server.
For the storing of integers I thought of using
nameValuePairs.add(new BasicNameValuePair("gender",Integer.toString(1)));
and making use of HttpPost to send to localhost. However, I have no idea how to invoke this function on to a button.
Main.java
Main.xml
public class Main extends Activity implements OnClickListener{
private Button cnfrm;
private Button absnt;
private Button ntfy;
private ProgressBar pb_cnfrm;
private ProgressBar pb_absnt;
private ProgressBar pb_ntfy;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cnfrm =(Button)findViewById(R.id.button1);
absnt =(Button)findViewById(R.id.button2);
ntfy =(Button)findViewById(R.id.button3);
pb_cnfrm=(ProgressBar)findViewById(R.id.progressBar1);
pb_absnt=(ProgressBar)findViewById(R.id.progressBar2);
pb_ntfy=(ProgressBar)findViewById(R.id.progressBar3);
pb_cnfrm.setVisibility(View.GONE);
cnfrm.setOnClickListener(this);
pb_absnt.setVisibility(View.GONE);
absnt.setOnClickListener(this);
pb_ntfy.setVisibility(View.GONE);
ntfy.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
pb_cnfrm.setVisibility(View.VISIBLE);
pb_absnt.setVisibility(View.VISIBLE);
pb_ntfy.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(toString());
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb_cnfrm.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
pb_absnt.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
pb_ntfy.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb_cnfrm.setProgress(progress[0]);
pb_absnt.setProgress(progress[1]);
pb_ntfy.setProgress(progress[2]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.56.1/http.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("confirm",Integer.toString(1)));
nameValuePairs.add(new BasicNameValuePair("absent",Integer.toString(2)));
nameValuePairs.add(new BasicNameValuePair("notify",Integer.toString(3)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_post_request"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
If you have a button you can use OnClickLister and OnClick. You can try something like this
private callServer(){..}
Button myButton = new Button(getApplicationContext());
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
callServer();
}
});
Also keep in mind that you should NOT be doing a call to the server in the UI thread, you will need to make the call using a different thread.
I have an app in which starting page needs internet,
Rest want to work without internet (ie, only one activity need the internet permission).
But when I turn off the Internet, the app shows a message like turn internet connection on and then only I can proceed to further (Here i want to work with out internet).
Is there any solution for that?
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exampleMock.ibps_test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:screenOrientation="landscape" >
<activity
android:name="com.exampleMock.ibps_test.MainActivity"
android:label="#string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.exampleMock.ibps_test.testClass"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.startTest"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.resultActivity"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.showDialog"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
<activity
android:name="com.exampleMock.ibps_test.showSolution"
android:label="#string/app_name"
android:screenOrientation="landscape" />
<activity
android:name="com.exampleMock.ibps_test.InfoGift"
android:label="#string/app_name"
android:screenOrientation="landscape"/>
</application>
Main Activity:
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Void>, AsyncHttpRequestDelegate
{
static EditText n;
static EditText p;
ProgressBar pb;
static String mail="";
private DatabaseHelper helper;
private SQLiteDatabase db;
private static WeakReference<MainActivity> mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new DatabaseHelper(this);
helper.initializeDataBase();
db=helper.getWritableDatabase();
String stat=check();
if(stat.equals("true"))
{
gotoNextPage();
}
else
{
n=(EditText)findViewById(R.id.name);
p=(EditText)findViewById(R.id.phone);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
mail=fetchEmail();
/*
if(mail==null)
{
EditText m=(EditText)findViewById(R.id.mail);
m.setVisibility(1);
mail=m.getText().toString();
} */
Button b=(Button)findViewById(R.id.regBtn);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(n.getText().toString().length()<1)
{
n.requestFocus();
Toast.makeText(MainActivity.this, "Enter your Name", Toast.LENGTH_SHORT).show();
}
else if(p.getText().toString().length()<10)
{
p.requestFocus();
Toast.makeText(MainActivity.this, "Enter a valid phone number", Toast.LENGTH_SHORT).show();
}
else
{
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
pb.setVisibility(View.VISIBLE);
//call asyncTask
startWork();
} else {
Toast.makeText(MainActivity.this, "No Network connection available...",Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
public String fetchEmail()
{
String e="";
Pattern email= Patterns.EMAIL_ADDRESS;
Account[] accounts= AccountManager.get(this).getAccounts();
for(Account account:accounts)
{
if(email.matcher(account.name).matches())
{
e=account.name;
return e;
}
}
return null;
}
public String check()
{
String flag="";
String sql="select * from reg_status";
Cursor c=db.rawQuery(sql, null);
if(c!=null)
{
c.moveToFirst();
flag=c.getString(0);
}
return flag;
}
public void updateStatus()
{
String sql="update reg_status set status = 'true'";
db.execSQL(sql);
gotoNextPage();
}
public void gotoNextPage()
{
Intent intent=new Intent(this,startTest.class);
startActivity(intent);
}
void startWork() {
getSupportLoaderManager().initLoader(0, (Bundle) null, this);
}
static class AsyncTaskMaker extends AsyncTaskLoader<Void> {
int progress = 0;
int percentProgress = 0;
int fileLength = 0;
AsyncTaskMaker(MainActivity activity) {
super(activity);
mActivity = new WeakReference<MainActivity>(activity);
}
#Override
public Void loadInBackground() {
System.out.println("inside loadInBackground");
processWebRequest();
return null;
}
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Void> arg0,
Void arg1) {
pb.setVisibility(View.GONE);
updateStatus();
//Toast.makeText(MainActivity.this, "Load finished", Toast.LENGTH_SHORT).show();
gotoNextPage();
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Void> arg0) {
//Toast.makeText(MainActivity.this, "Load reset", Toast.LENGTH_SHORT).show();
}
#Override
public android.support.v4.content.Loader<Void> onCreateLoader(int arg0, Bundle arg1) {
AsyncTaskMaker asyncTaskLoader = new AsyncTaskMaker(this);
asyncTaskLoader.forceLoad();
return asyncTaskLoader;
}
private static void processWebRequest(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://beta.wisdom24x7.com/gapps.php/");
//System.out.println("inside processWebRequest");
try
{
List<NameValuePair> pair=new ArrayList<NameValuePair>(4);
pair.add(new BasicNameValuePair("name",n.getText().toString()));
pair.add(new BasicNameValuePair("email",mail));
pair.add(new BasicNameValuePair("phone",p.getText().toString()));
pair.add(new BasicNameValuePair("exam","AIEEE"));
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse= httpclient.execute(httpPost);
Log.d("Http Response:", httpResponse.toString());
}catch(ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void didComplete(HttpRequest request, String responseString) {
pb.setVisibility(View.GONE);
//Toast.makeText(MainActivity.this, "data sent", Toast.LENGTH_SHORT).show();
}
#Override
public void didFail(HttpRequest request) {
}
#Override
public void publishProgress(final int progress) {
if (mActivity.get() != null) {
mActivity.get().runOnUiThread(new Runnable() {
#Override
public void run() {
mActivity.get().pb.setProgress(progress);
}
});
}
}
}
Another activity, which does not require internet:
public class showDialog extends ActionBarActivity
{
CheckBox b1,b2,b3,b4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_sub);
b1=(CheckBox)findViewById(R.id.checkBox1);
b2=(CheckBox)findViewById(R.id.checkBox2);
b3=(CheckBox)findViewById(R.id.checkBox3);
b4=(CheckBox)findViewById(R.id.checkBox4);
final List<String> subs=new ArrayList<String>();
ImageButton bn=(ImageButton)findViewById(R.id.imageButton1);
bn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(b1.isChecked())
subs.add(b1.getText().toString());
if(b2.isChecked())
subs.add(b2.getText().toString());
if(b3.isChecked())
subs.add(b3.getText().toString());
if(b4.isChecked())
subs.add(b4.getText().toString());
System.out.print("subjects "+subs);
Intent intent = new Intent(showDialog.this,testClass.class);
intent.putStringArrayListExtra("subject", (ArrayList<String>) subs);
startActivity(intent);
}
});
}
}
It seems you didn't write this Android application by yourself (or else you would understand what the message means). This message that "asks for internet connection" is something that is done through your app and not by the Android framework. Please understand your application first, then ask questions about it.
Hint: Search for the String inside your app (by search functionality of your IDE) that is shown in your "asks for internet connection" message and look up why it is displayed. You will see, that you can disable it.
in your AndroidManifest.xml put :
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
and inonCreate method of each activity you don't want to use the internet_connection in:
WifiManager wifiManager = (WifiManager)this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
You can only set permission for the complete app, not on single activity.
Why is it so important that the user doesn't have an internet connection in the rest of the app? When you don't code anything that connects to the internet in those "internet-free" activities, then you won't use up the (possible) date