In my android app i am using Latest Geoloqi API to implement Geofence concept.when user entered into some region he has notify, for that purpose i am using Push Notifications.in GeoReceiver class three callback methods are calling but not onPushMessageReceived().please help me how to do it?
I am creating trigger with current location is it required to enter into region manually or since i am already in the location its not calling?
Note:I ve given required credentials in assets/geoloqi.properties file.when app is launched in logcat "Successfully registered for the C2DM service" msg also displayed.my code:
GeoloqiExampleActivity.java
public class GeoloqiExampleActivity extends Activity{
String TAG = "Geoloqi Example";
private LQService mService;
private boolean mBound;
GeoReceiver geoReceiver = new GeoReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, LQService.class);
startService(intent);
}
#Override
public void onResume() {
super.onResume();
// Bind to the tracking service so we can call public methods on it
Intent intent = new Intent(this, LQService.class);
bindService(intent, mConnection, 0);
// Wire up the sample location receiver
final IntentFilter filter = new IntentFilter();
filter.addAction(GeoReceiver.ACTION_LOCATION_CHANGED);
filter.addAction(GeoReceiver.ACTION_TRACKER_PROFILE_CHANGED);
filter.addAction(GeoReceiver.ACTION_LOCATION_UPLOADED);
filter.addAction(GeoReceiver.ACTION_PUSH_MESSAGE_RECEIVED);
registerReceiver(geoReceiver, filter);
}
#Override
public void onPause() {
super.onPause();
// Unbind from LQService
if (mBound) {
unbindService(mConnection);
mBound = false;
}
// Unregister our location receiver
unregisterReceiver(geoReceiver);
}
public void sendRequest() {
// Performing a Trigger POST request
if (mService != null) {
LQSession session = mService.getSession();
LQTracker tracker = mService.getTracker();
tracker.setSession(session);
// Build your request
JSONObject trigger = new JSONObject();
try {
trigger.put("text", "Popcornapps");
trigger.put("type", "message");
trigger.put("latitude", 17.42557068);
trigger.put("longitude", 78.42022822);
trigger.put("radius", 500);
trigger.put("place_name", "Banjara Hills");
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
}
// Send the request
session.runPostRequest("trigger/create", trigger, new OnRunApiRequestListener() {
#Override
public void onSuccess(LQSession session, HttpResponse response) {
Toast.makeText(GeoloqiExampleActivity.this, "Success", Toast.LENGTH_SHORT).show();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder s = new StringBuilder();
String sResponse;
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
String result = s.toString().trim();
Log.d("On success Result", result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(LQSession session, LQException e) {
Log.e(TAG, e.getMessage());
Toast.makeText(GeoloqiExampleActivity.this, "Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(LQSession session, HttpResponse response, StatusLine status) {
Toast.makeText(GeoloqiExampleActivity.this, "Complete", Toast.LENGTH_LONG).show();
}
});
} else{
Toast.makeText(this, "service null", Toast.LENGTH_LONG).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
// We've bound to LocalService, cast the IBinder and get LocalService instance.
LQBinder binder = (LQBinder) service;
mService = binder.getService();
mBound = true;
sendRequest();//Sending API Request
} catch (ClassCastException e) {
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
}
GeoReceiver.java
public class GeoReceiver extends LQBroadcastReceiver {
#Override
public void onLocationChanged(Context arg0, Location arg1) {
Toast.makeText(arg0, "Loc Changed ", Toast.LENGTH_SHORT).show();
}
#Override
public void onPushMessageReceived(Context context, Bundle data) {
Toast.makeText(context, "Push Msg Received ", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationUploaded(Context arg0, int arg1) {
Toast.makeText(arg0, "Location Uploaded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onTrackerProfileChanged(Context arg0, LQTrackerProfile oldp,
LQTrackerProfile newp) {
Toast.makeText(arg0, "onTrackerProfileChanged ",Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pop.geoloqi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<permission
android:name="com.pop.geoloqi.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.pop.geoloqi.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".GeoloqiExampleActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.geoloqi.android.sdk.service.LQService"
android:exported="false" />
<receiver
android:name=".GeoReceiver"
android:enabled="false"
android:exported="false" >
<intent-filter>
<action android:name="com.geoloqi.android.sdk.action.LOCATION_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="com.geoloqi.android.sdk.receiver.LQDeviceMessagingReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.pop.geoloqi" />
</intent-filter>
</receiver>
</application>
</manifest>
There was a bug in earlier versions of the Geoloqi Android SDK. If you update to the latest version this problem should be resolved.
Related
I develop a VoIP app using this guide.
I faced the problem with a self-manged connection service on Samsung devices.
I'm placing a call using TelecomManager.
I expect that ConnectionService::onCreateOutgoingConnection or ConnectionService::onCreateOutgoingConnectionFailed will be invoked, but it doesn't happen on some Samsung devices.
After placing a call the dialog window appears. On samsung galaxy s10 an android toast appears with the text "Call not sent". Methods of connection service are not invoked.
On phones with the vanilla Android it works as expected.
Does anybody know how to solve this issue?
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tcom">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS"/>
<application
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"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<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="com.example.tcom.ConnectionService"
android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
<intent-filter>
<action android:name="android.telecom.ConnectionService" />
</intent-filter>
</service>
</application>
</manifest>
ConnectionService:
public class ConnectionService extends android.telecom.ConnectionService {
private static final String TAG = "ConnectionService";
#Override
public android.telecom.Connection onCreateIncomingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateIncomingConnection");
Connection connection = new Connection();
MainActivity.setConnection(connection);
return connection;
}
#Override
public void onCreateIncomingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateIncomingConnectionFailed");
super.onCreateIncomingConnectionFailed(connectionManagerPhoneAccount, request);
}
#Override
public android.telecom.Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateOutgoingConnection");
Connection connection = new Connection();
MainActivity.setConnection(connection);
return connection;
}
#Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
Log.i(TAG, "onCreateOutgoingConnectionFailed");
super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
}
Connection:
public class Connection extends android.telecom.Connection {
private static final String TAG = "Connection";
public Connection() {
super();
setConnectionProperties(android.telecom.Connection.PROPERTY_SELF_MANAGED);
}
#Override
public void onStateChanged(int state) {
super.onStateChanged(state);
Log.i(TAG, "onStateChanged state=" + android.telecom.Connection.stateToString(state));
}
}
PhoneAccount creating:
void createAccount() {
tm = (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
if (tm == null) {
throw new RuntimeException("cannot obtain telecom system service");
}
ComponentName connectionServiceName = new ComponentName(getApplicationContext(), ConnectionService.class);
PhoneAccountHandle accountHandle = new PhoneAccountHandle(connectionServiceName, PHONE_ACCOUNT_LABEL);
try {
PhoneAccount phoneAccount = tm.getPhoneAccount(accountHandle);
if (phoneAccount == null) {
PhoneAccount.Builder builder = PhoneAccount.builder(accountHandle, PHONE_ACCOUNT_LABEL);
builder.setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED);
phoneAccount = builder.build();
tm.registerPhoneAccount(phoneAccount);
}
this.accountHandle = phoneAccount.getAccountHandle();
if (tm.getPhoneAccount(accountHandle) == null) {
throw new RuntimeException("cannot create account");
}
} catch (SecurityException e) {
throw new RuntimeException("cannot create account", e);
}
}
Call creating:
void createCall() {
try {
Bundle extras = new Bundle();
extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, accountHandle);
Uri uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, "test_call", null);
tm.placeCall(uri, extras);
}
catch (SecurityException e) {
throw new RuntimeException("cannot place call", e);
}
}
After some firmware update the code above started working correctly.
So, the problem was in the phone itself.
Anybody else having this problem, just make sure of two things:
Remove PhoneAccount.CAPABILITY_CALL_PROVIDER from your phone account's capabilities.
You have implemented an InCallService.
I am trying to develop a setup of 2 applications (service app + client app) using AIDL. I have currently a setup of 3 modules:
android-agent-framework (android library module holding only the AIDL file)
android-agent (the service)
android-example-client (the client)
android-agent and android-agent-framework have a dependency to the first one to get access to the interface.
Whenever the client calls bindService() it gets false as return and in the ServiceConnection the onServiceConnected() is not called. Also in the service implementation the onBind() is not called. There is no error in the logs.
Here is the code:
android-agent activity:
public class MyCompanyStartActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(MyCompanyStartActivity.class.toString(), "Create MyCompanyStartActivity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ComponentName service = startService(new Intent(this, MyCompanyRequestService.class));
Log.i("tag", service.getClassName() + "::" + service.getPackageName());
}
}
android-agent service:
public class MyCompanyRequestService extends Service {
#Override
public IBinder onBind(Intent intent) {
Log.i(MyCompanyRequestService.class.toString(), "Starting SmartRest Service");
return mBinder;
}
private final IMyCompanyRequestService.Stub mBinder = new IMyCompanyRequestService.Stub() {
#Override
public void sendData(String xid, String authentication, String data) throws RemoteException{
Log.i(MyCompanyRequestService.class.toString(), "sending data: " + data);
}
};
}
android-agent manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.android.agent" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MyCompanyStartActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Services -->
<service
android:name="com.mycompany.android.agent.framework.MyCompanyRequestService"
android:process=":remote"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="MyCompanyRequestService"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
<!-- Permissions -->
</application>
</manifest>
android-example-client activity:
public class ClientStarter extends Activity {
protected IMyCompanyRequestService mycompanyRequestService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("tag","create client");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
if (mycompanyRequestService == null) {
printServices();
Intent it = new Intent("MyCompanyRequestService");
it.setPackage("com.mycompany.android.agent.framework");
Log.i("tag","before binding service: " + it.getAction() + "::" + it.getPackage());
boolean serviceBinding = getApplicationContext().bindService(it, connection, Context.BIND_AUTO_CREATE);
Log.i("tag", "service is bound: " + serviceBinding);
}
Handler handler = new Handler();
handler.postDelayed(new Runner(), 10000);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
private ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("service", "Service connected");
mycompanyRequestService = IMyCompanyRequestService.Stub.asInterface(service);
Toast.makeText(getApplicationContext(), "Service Connected", Toast.LENGTH_SHORT).show();
Log.i("service", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i("service", "Service disconnected");
mycompanyRequestService = null;
Toast.makeText(getApplicationContext(), "Service Disconnected", Toast.LENGTH_SHORT).show();
Log.i("service", "Service disconnected");
}
};
private void printServices() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
Log.d("service", service.service.getClassName());
}
}
private class Runner implements Runnable {
#Override
public void run() {
Log.i("tag","starting");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Log.e(ClientStarter.class.toString(), "Error", e);
} while(true) {
try {
if (mycompanyRequestService != null) {
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i(ClientStarter.class.toString(), loc.getLatitude() + " - " + loc.getLongitude() + " - " + loc.getAltitude());
mycompanyRequestService.sendData("test", "auth", String.valueOf(loc.getLatitude()) + "," + String.valueOf(loc.getLongitude()) + "," + String.valueOf(loc.getAltitude()));
} else {
Log.i(ClientStarter.class.toString(), "service not yet available");
}
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(ClientStarter.class.toString(), "Error", e);
} catch (RemoteException e) {
Log.e(ClientStarter.class.toString(), "Error", e);
}
}
}
}
}
The printServices() call before trying to bind the service actually lists the service so it is running.
The log does not contain any errors and the client is in the end running in the loop but the service is still null.
Maybe someone encountered a similar issue before.
After going another round through all files I found my mistake.
I needed to change:
Intent it = new Intent("MyCompanyRequestService");
it.setPackage("com.mycompany.android.agent.framework");
to:
Intent it = new Intent("MyCompanyRequestService");
it.setPackage("com.mycompany.android.agent");
The package of the Intent needs to match the package of the app and not the package of the service.
Another reason why you could face this issue (at least I did) is that – from API level 30 – you are also required to declare the apps that you communicate to in the manifest, for example:
<queries>
<package android:name="com.your.app" />
</queries>
I created application that if the button is click it will send SMS to the number that came from webservice. Then I use Alarm Manager to send SMS repeatedly in the number that i get from the web service. It is working fine but when I change the number that I want to send an SMS it will not work. I don't know what is wrong with my code. Here is my code.
This is my code that send an SMS.
public class EmergencyAssistance extends ActionBarActivity {
ArrayList<Objects> objectsList = new ArrayList<>();
String url = "http://192.168.254.108:8080/taxisafe3/webService/listcontact";
String urls = "http://192.168.254.108:8080/taxisafe3/webService/plate";
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String message;
String message1;
Button send;
LocationService locationService;
double lat;
double lng;
StringBuilder address;
StringBuffer smsBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_assistance);
send = (Button) findViewById(R.id.emergency);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setData();
new Task().execute(urls);
new Tasks().execute(url);
}
});
}
public class Task extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setCon1(jsonobject.getString("con1"));
objects.setCon2(jsonobject.getString("con2"));
objects.setCon3(jsonobject.getString("con3"));
objects.setCon4(jsonobject.getString("con4"));
objects.setCon5(jsonobject.getString("con5"));
objectsList.add(objects);
contact1 = objects.getCon1();
contact2 = objects.getCon2();
contact3 = objects.getCon3();
contact4 = objects.getCon4();
contact5 = objects.getCon5();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Tasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = HttpULRConnect.getData(urls);
return content;
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray ary = new JSONArray(s);
for (int i = 0; i < ary.length(); i++) {
JSONObject jsonobject = ary.getJSONObject(i);
Objects objects = new Objects();
objects.setTaxi_plate_no(jsonobject.getString("taxi_plate_no"));
objects.setDriver_operator(jsonobject.getString("driver_operator"));
objectsList.add(objects);
message = objects.getTaxi_plate_no();
message1 = objects.getDriver_operator();
emergency();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void emergency() {
smsBody = new StringBuffer();
smsBody.append("https://maps.google.com/maps?q=");
smsBody.append(lat);
smsBody.append(",");
smsBody.append(lng);
String msgs = "[EMERGENCY!] \nTaxi plate #: " + message + "\nTaxi operator: " + message1 + "\n" + address + smsBody.toString();
try {
if (PatternChecker.isNotNull(contact1)) {
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent(EmergencyAssistance.this, AlarmReceiver.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num1", contact1);
bundle.putCharSequence("msg1", msgs);
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(EmergencyAssistance.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 1000 * 60 * 1, pendingIntent);
Toast.makeText(getApplicationContext(), "SMS Sent", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "No Number", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
public void setData() {
locationService = new LocationService(getApplication());
if(locationService.canGetLocation()){
lat = locationService.getLatitude();
lng = locationService.getLongitude();
}else{
locationService.showSettingsAlert();
}
getMyLocationAddress();
}
public void getMyLocationAddress() {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
address = new StringBuilder();
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
address.append(fetchedAddress.getAddressLine(i)).append("\n");
}
} else
Toast.makeText(getApplicationContext(),"No Address", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
This is my Alarm Receiver.
public class AlarmReceiver extends BroadcastReceiver
{
String msg;
String num;
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
num = bundle.getString("num1");
msg = bundle.getString("msg1");
//Toast.makeText(context, num + msg, Toast.LENGTH_SHORT).show();
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(num, null, msg, null, null);
}
}
This is my manifest to allow sending SMS and to register the alarm receiver.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.group.taxisafe" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<permission
android:name="com.mapv2.demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mapv2.demo.permission.MAPS_RECEIVE" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/taxisafe"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Login"
android:label="TaxiSafe" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Register"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Home"
android:label="#string/title_activity_home" >
</activity>
<activity
android:name=".DriverDetails"
android:label="#string/title_activity_driver_details" >
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
<activity
android:name=".Contacts"
android:label="#string/title_activity_contacts" >
</activity>
<activity
android:name=".ReportActivity"
android:label="#string/title_activity_report" >
</activity>
<activity
android:name=".DriversList"
android:label="#string/title_activity_drivers_list" >
</activity>
<activity
android:name=".DriverAdapter"
android:label="#string/title_activity_driver_adapter" >
</activity>
<activity
android:name=".EmergencyAssistance"
android:label="#string/title_activity_emergency_assistance" >
</activity>
<activity
android:name=".DisplayContact"
android:label="#string/title_activity_display_contact" >
</activity>
<activity
android:name=".ContactAdapter"
android:label="#string/title_activity_contact_adapter" >
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
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
I try to write to share a post on twitter but this code works on Galaxy S2 but it doesn't work in Galaxy s3...I don't know why.
At this link there is the log error:
http://it.tinypic.com/r/2wqyd1w/5
This is the code of Twitter:
public class TwitterActivity extends Activity {
private Twitter twitter;
public final String PREFS = "MyPrefsFile";
final public String CALLBACK_URL = "app://casa";
private SharedPreferences shared;
private static RequestToken requestToken=null;
private LinkedList<RequestToken> lista=new LinkedList<RequestToken>();
private int it = 0;
private String frase = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
it = getIntent().getExtras().getInt("punteggio");
frase = getIntent().getExtras().getString("frase");
shared = this.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new updateTwitterStatus().execute();
}
});
}
#Override
public void onNewIntent(Intent data) {
super.onNewIntent(data);
dealWithTwitterResponse(data);
}
class updateTwitterStatus extends AsyncTask<Void, Void, String> {
private Intent i = null;
#Override
protected String doInBackground(Void... params) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("********")
.setOAuthConsumerSecret(
"**********");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = new TwitterFactory().getInstance();
twitter = tf.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("Stringa",requestToken.toString());
Log.i("bauu", "miao");
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(requestToken.getAuthenticationURL())));
return authUrl;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void onResume() {
Log.i("reume","re");
super.onResume();
}
private void dealWithTwitterResponse(final Intent intent) {
Log.i("Sonod entro", "vau");
final Uri uri = intent.getData();
if (uri == null) {
Log.i("è null", "null");
}
Log.i("callback funziona", "ciao");
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
final String verifier = uri.getQueryParameter("oauth_verifier");
final String oauthToken = uri.getQueryParameter("oauth_token");
new Thread(new Runnable() {
public void run() {
try {
//
// if(requestToken==null){
// Log.i("Il TOKEN è NULL","uihuh");
// }else{
// Log.i("IL TOKEN NON E NULL","huèh ");
// }
// if(verifier==null){
// Log.i("Verifier nullo","sdg");
// }else{
// Log.i("Verifier non null","asdfg");
// }
Log.i("SOno dentro il run", "asd");
//the next line throws exception
AccessToken at = twitter.getOAuthAccessToken(
requestToken,verifier);
twitter.setOAuthAccessToken(at);
twitter.updateStatus("CHI VUOLE ESSERE SCIENZIATO?? Punteggio: "
+ it
+ " "
+ frase
+ " "
+ "www.scienze-naturali.com");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.punteggio, menu);
return true;
}
}
and this is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicazionescienza"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.applicazionescienza.MenuPrincipale"
android:label="#string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.Informazioni"
android:label="#string/title_activity_informazioni" >
</activity>
<activity
android:name="com.example.applicazionescienza.Regolamento"
android:label="#string/title_activity_regolamento" >
</activity>
<activity
android:name="com.example.applicazionescienza.Gioca"
android:label="#string/title_activity_gioca" >
</activity>
<activity
android:name="com.example.applicazionescienza.Livello"
android:label="#string/title_activity_livello" >
</activity>
<activity
android:name="com.example.applicazionescienza.Punteggio"
android:label="#string/title_activity_punteggio" >
</activity>
<activity
android:name="com.example.applicazionescienza.TwitterActivity"
android:label="#string/title_activity_twitter"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="casa"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.FacebookActivity"
android:label="#string/title_activity_facebook" >
</activity>
</application>
</manifest>
I try this code in other real device. In one device works great but in my device the same code doesn't work. Anyone can help me to understand why?
It looks like twitter is null here
AccessToken at = twitter.getOAuthAccessToken(
requestToken,verifier);
because this method is called before you run your AsyncTask which initializes your twitter variable.
Try calling this method in onPostExecute() of your AsyncTask since this method will be called when doInBackground() is finished.