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>
Related
In my android project i have a sync adapter that will sync data from android device to the server and its working fine, but recently i noticed that the onPerfomSync is not calling in my moto g3 android phone, I don't know whether there is the same problem in any other phones,I have tested it in some other Samsung phones with different android api level,but didn't find any problem there.I have configured the sync when a successful user login found.What will be the reason for this behaviour.Correct me if i am doing anything wrong.
Below is my codes.
private void finishLogin(Intent intent) {
String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
if (getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)) {
String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
String authtokenType = authTokenType;
String refreshToken = intent.getStringExtra(KEY_REFRESH_TOKEN);
Bundle userData = new Bundle();
userData.putString(KEY_REFRESH_TOKEN, refreshToken);
accountManager.addAccountExplicitly(account, accountPassword, userData);
accountManager.setAuthToken(account, authtokenType, authtoken);
accountManager.setUserData(account,KEY_REFRESH_TOKEN,refreshToken);
ContentResolver.setMasterSyncAutomatically(true);
ContentResolver.setSyncAutomatically(account, "com.myexample.mysampleproject", true);
configurePeriodicSync(account, SYNC_INTERVAL, SYNC_FLEXTIME);
try {
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("condition else getIntent().getBooleanExtra(ARG_IS_ADDING_ACCOUNT, false)");
accountManager.setPassword(account, accountPassword);
}
setAccountAuthenticatorResult(intent.getExtras());
setResult(RESULT_OK, intent);
finish();
}
public void configurePeriodicSync(Account account, int syncInterval, int flexTime) {
Log.d(TAG, "PERIODC SYNC CONFIGURED");
Bundle mySyncExtras = new Bundle();
mySyncExtras.putBoolean("MY_SYNC", true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
System.out.println("if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
SyncRequest request = new SyncRequest.Builder().
syncPeriodic(syncInterval, flexTime).
setSyncAdapter(account, "com.myexample.mysampleproject").setExtras(mySyncExtras).build();
ContentResolver.requestSync(request);
} else {
System.out.println("else (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)");
ContentResolver.addPeriodicSync(account, "com.myexample.mysampleproject", mySyncExtras, syncInterval);
}
}
SyncService.java :
public class SyncService extends Service {
private static SyncAdapter syncAdapter = null;
private static final Object syncAdapterLock = new Object();
#Override
public void onCreate() {
synchronized (syncAdapterLock) {
if (syncAdapter == null) {
syncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}
#Override
public IBinder onBind(Intent intent) {
return syncAdapter.getSyncAdapterBinder();
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myexample.mysampleproject" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:largeHeap="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".view.MainActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme"
android:label="#string/app_name" >
</activity>
<activity android:name=".view.LoginActivity"
android:configChanges="orientation|screenSize"
android:theme="#style/AppTheme"
android:label="#string/login_label"/>
........
........
<provider
android:name=".db.MyContentProvider"
android:authorities="com.myexample.mysampleproject"
android:exported="false"
android:syncable="true" />
<service
android:name=".sync.SyncService"
android:exported="true">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/sync_adapter" />
</service>
</application>
</manifest>
sync_adapter.xml :
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter
xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="com.myexample.mysampleproject"
android:accountType="com.myexample.mysampleproject"
android:userVisible="true"
android:supportsUploading="true"
android:allowParallelSyncs="true"
android:isAlwaysSyncable="true" />
SyncAdapter.java :
public class SyncAdapter extends AbstractThreadedSyncAdapter {
ContentResolver contentResolver;
Context context;
String authToken;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
this.context = context;
contentResolver = context.getContentResolver();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
contentResolver = context.getContentResolver();
}
#Override
public void onPerformSync(Account account, final Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
try {
System.out.println("start sync ");
AccountManager manager = AccountManager.get(context);
authToken = manager.peekAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
try {
if(authToken != null) {
if (isOnline()) {
// perform sync....
} else {
Log.d("ATTEMPT SYNC ERROR", "NO NETWORK CONNECTION");
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using Google Map v2 in Tabs.
Here is layout file of activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white" >
<RelativeLayout
android:id="#+id/registrationLayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#333333" >
<ImageView
android:id="#+id/activity_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:contentDescription="#string/content_description"
android:src="#drawable/logo" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/registrationLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/registrationLayout" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I get this error when I transfer my project to another PC. I have imported GooglePlayService for GoogleMap V2 and Facebook SDK 3.5.2 in my work space.
Here is the java code
public class NearMe extends FragmentActivity {
GpsProvider gpsProvider;
private GoogleMap googleMap;
double lat;
double lng;
JsonParser jparser;
String latString, longString, titleString, dis, distanceString,
stationIdString, colorNameString;
ArrayList<HashMap<String, String>> dockitstationsArrayList,
stationidArrayList;
BitmapDescriptor bitmapMarker;
NetworkHelper nh;
AlertDialogManager alertDialogManager = new AlertDialogManager();
// flag for Internet connection status
Boolean isInternetPresent = false;
HashMap<String, String> markershashmap = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Setting View for Screen
setContentView(R.layout.near_me);
dockitstationsArrayList = new ArrayList<HashMap<String, String>>();
markershashmap = new HashMap<String, String>();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
try {
String distance[] = marker.getSnippet().split(" - ");
String distanceString = distance[0];
String idString = marker.getId();
String stationid = markershashmap.get(idString);
Message mesg = new Message();
Bundle b = new Bundle();
b.putString("stationId", stationid);
b.putString("distance", distanceString);
mesg.setData(b);
handler.sendMessage(mesg);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Bundle b1 = new Bundle();
b1.putString("stationId", b.getString("stationId"));
b1.putString("distance", b.getString("distance"));
Intent dockitdetailsIntent = new Intent(getParent(),
DockItStationDetails.class);
dockitdetailsIntent.putExtras(b1);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("Dock It Details",
dockitdetailsIntent);
}
};
#Override
protected void onResume() {
super.onResume();
initilizeMap();
nh = new NetworkHelper(getApplicationContext());
isInternetPresent = nh.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alertDialogManager.showInfoAlertDialog(NearMe.this.getParent(),
"Please connect to working internet connection");
// stop executing code by return
return;
}
gpsProvider = new GpsProvider(this.getParent());
// check if GPS enabled
if (gpsProvider.canGetLocation()) {
double latitude = gpsProvider.getLatitude();
double longitude = gpsProvider.getLongitude();
// \n is for new line
/*
* Toast.makeText( getApplicationContext(),
* "Your Location is - \nLat: " + latitude + "\nLong: " + longitude,
* Toast.LENGTH_LONG).show();
*/
new LoadNearByDockITStations().execute(String.valueOf(latitude),
String.valueOf(longitude));
} else {
// can't get location
// GPS is not enabled
// Ask user to enable GPS in settings
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
this.getParent());
// Setting Dialog Message
alertDialog
.setMessage("Your GPS seems to be disabled, do you want to enable it?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
// Setting Gravity to Center
AlertDialog dialog = alertDialog.show();
dialog.setCanceledOnTouchOutside(false);
TextView messageText = (TextView) dialog
.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
// Showing Alert Message
dialog.show();
}
}
private class LoadNearByDockITStations extends
AsyncTask<String, String, String> {
String res, status;
JSONArray resultJsonArray;
HashMap<String, String> map;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String lat = arg0[0];
String lng = arg0[1];
jparser = new JsonParser();
JSONObject jsonObject = jparser
.makeHttpRequest(Utility.GETDOCKITLIST + "?latitude=" + lat
+ "&longitude=" + lng + "&klm=20");
try {
// /Getting array of Events.......
if (jsonObject.getJSONArray(Utility.STATIONS) != null) {
res = jsonObject.getString(Utility.SUCCESS);
if (Integer.parseInt(res) == 1) {
resultJsonArray = jsonObject
.getJSONArray(Utility.STATIONS);
// looping through All Contacts
for (int i = 0; i < resultJsonArray.length(); i++) {
JSONObject c = resultJsonArray.getJSONObject(i);
// Storing each json item in variable
latString = c.getString(Utility.LAT);
longString = c.getString(Utility.LONG);
titleString = c.getString(Utility.TITLE);
distanceString = c.getString(Utility.DISTANCE);
stationIdString = c.getString(Utility.STATION_ID);
colorNameString = c.getString(Utility.COLOR_NAME);
// creating new HashMap
map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(Utility.LAT, latString);
map.put(Utility.LONG, longString);
map.put(Utility.TITLE, titleString);
map.put(Utility.DISTANCE, distanceString);
// map.put(Utility.DISTANCE, distanceString);
map.put(Utility.STATION_ID, stationIdString);
map.put(Utility.COLOR_NAME, colorNameString);
dockitstationsArrayList.add(map);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dockitstationsArrayList.size() == 0) {
Toast.makeText(getApplicationContext(),
"No Dock It Stations Found", Toast.LENGTH_LONG).show();
} else {
/*
* Toast.makeText(getApplicationContext(),
* "Dock It Stations Found", Toast.LENGTH_LONG).show();
*/
googleMap.clear();
addMarkersToMap();
}
}
}
private void addMarkersToMap() {
ArrayList<Marker> mMarkers = new ArrayList<Marker>();
LatLng ll = null;
String distance;
for (int i = 0; i < dockitstationsArrayList.size(); i++) {
ll = new LatLng(Double.parseDouble(dockitstationsArrayList.get(i)
.get(Utility.LAT)),
Double.parseDouble(dockitstationsArrayList.get(i).get(
Utility.LONG)));
distance = dockitstationsArrayList.get(i).get(Utility.DISTANCE);
stationIdString = dockitstationsArrayList.get(i).get(
Utility.STATION_ID);
colorNameString = dockitstationsArrayList.get(i).get(
Utility.COLOR_NAME);
if (colorNameString.equals("Cyan"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.cyan_marker);
else if (colorNameString.equals("Red"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.red_marker);
else if (colorNameString.equals("Yellow"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.yellow_marker);
else if (colorNameString.equals("Blue"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.blue_marker);
else if (colorNameString.equals("Green"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.green_marker);
else if (colorNameString.equals("Purple"))
bitmapMarker = BitmapDescriptorFactory
.fromResource(R.drawable.purple_marker);
MarkerOptions mOption = new MarkerOptions();
mOption.position(ll);
mOption.title(dockitstationsArrayList.get(i).get(Utility.TITLE));
mOption.anchor(0.0f, 1.0f);
mOption.snippet(Utility.convertDistance(distance) + "m - Here");
mOption.icon(bitmapMarker);
Marker marker = googleMap.addMarker(mOption);
mMarkers.add(marker);
String markerkey = marker.getId();
markershashmap.put(markerkey,
dockitstationsArrayList.get(i).get(Utility.STATION_ID));
}
// stationidArrayList.add(markers);
final LatLngBounds.Builder bld = new LatLngBounds.Builder();
for (int i = 0; i < dockitstationsArrayList.size(); i++) {
LatLng ll2 = new LatLng(Double.parseDouble(dockitstationsArrayList
.get(i).get(Utility.LAT)),
Double.parseDouble(dockitstationsArrayList.get(i).get(
Utility.LONG)));
bld.include(ll2);
}
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(
bld.build(), 30));
// googleMap.animateCamera(CameraUpdateFactory.zoomIn());
googleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// Move camera.
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(
bld.build(), 50));
// Remove listener to prevent position reset on camera move.
googleMap.setOnCameraChangeListener(null);
}
});
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
}
Here is manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dockit"
android:versionCode="2"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<permission
android:name="com.dockit.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.dockit.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<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_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- Access Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/app_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
<activity
android:name="com.dockit.SplashScreen"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.dockit.AboutUs"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.ListViewDockItStations"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.More"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden|stateHidden" >
<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="twitter"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.dockit.NearByDockItTabs"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.NearMeold"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.Registration"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroupActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroup1"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.NearMe"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroup2"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.tabcontroller.TabGroup3"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<activity
android:name="com.dockit.DockItStationDetails"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAlvDShdumWacdKdHldu3TCAUPyUXId30k" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.dockit.RateApplication"
android:label="#string/title_activity_rate_application" >
</activity>
</application>
</manifest>
I capitalize fragment but I got this warning "Invalid tag Fragment should be fragment"
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.
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.
I have written the android application and I want the application to send the call information whenever there is an incoming call and it ends. This way I would be sending all calls to the server irrespective of size of the call log.
Here is the code
public class PhoneInfo extends BroadcastReceiver {
private int incoming_call = 0;
private Cursor c;
Context context;
public void onReceive(Context con, Intent intent) {
c = con.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC");
context = con;
IncomingCallListener phoneListener = new IncomingCallListener();
TelephonyManager telephony = (TelephonyManager) con
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
public class IncomingCallListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (incoming_call == 1) {
CollectSendCallInfo();
incoming_call = 0;
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_RINGING:
incoming_call = 1;
break;
}
}
private void CollectSendCallInfo() {
int numberColumn = c
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE);
int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE);
int durationColumn = c
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
ArrayList<String> callList = new ArrayList<String>();
try {
boolean moveToFirst = c.moveToFirst();
}
catch (Exception e) {
; // could not move to the first row.
return;
}
int row_count = c.getCount();
int loop_index = 0;
int is_latest_call_read = 0;
String callerPhonenumber = c.getString(numberColumn);
int callDate = c.getInt(dateColumn);
int callType = c.getInt(typeColumn);
int duration = c.getInt(durationColumn);
while ((loop_index < row_count) && (is_latest_call_read != 1)) {
switch (callType) {
case android.provider.CallLog.Calls.INCOMING_TYPE:
is_latest_call_read = 1;
break;
case android.provider.CallLog.Calls.MISSED_TYPE:
break;
case android.provider.CallLog.Calls.OUTGOING_TYPE:
break;
}
loop_index++;
c.moveToNext();
}
SendCallInfo(callerPhonenumber, Integer.toString(duration),
Integer.toString(callDate));
}
private void SendCallInfo(String callerPhonenumber, String callDuration,
String callDate) {
JSONObject j = new JSONObject();
try {
j.put("Caller", callerPhonenumber);
j.put("Duration", callDuration);
j.put("CallDate", callDate);
} catch (JSONException e) {
Toast.makeText(context, "Json object failure!", Toast.LENGTH_LONG)
.show();
}
String url = "http://xxxxxx.xxx.xx/xxxx/xxx.php";
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("phonecall", j.toString());
HttpResponse re;
try {
re = doPost(url, kvPairs);
String temp;
try {
temp = EntityUtils.toString(re.getEntity());
if (temp.compareTo("SUCCESS") == 0) {
;
}
else
;
} catch (ParseException e1) {
Toast.makeText(context, "Parse Exception in response!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(context, "Io exception in response!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
} catch (ClientProtocolException e1) {
Toast.makeText(context, "Client Protocol Exception!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(context, "Client Protocol Io exception!",
Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
}
}
and here is the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Friend" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"></uses-permission>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Friend" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".LoginInfo" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.DEFAULT" />
</intent-filter>
</activity>
<service android:exported="true" android:enabled="true"
android:name=".GeoUpdateService">
</service>
<receiver android:name=".SmsInfo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<receiver android:name=".PhoneInfo">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
</application>
</manifest>
The application just crashes when there is an incoming call. I have been able to log the information about incoming SMS, but this call info logging is failing.
In my opinion you use BroadcastReciver in wrong way. You perform sync-query which can last more time than you have for handling broadcast. Next issue - you register listener object which will be probably collected by GC just after the end of onReceive method. Your BroadR should start service for handling those events.