Not getting callback from google api, android? - gps

I have connected to google api for loaction in android. but i not getting any callback from google api. not getting location.
my code is
public class SplashScreen extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
public static int SPLASH_TIME_OUT = 3000;
private final String LOG_TAG = "logTagMngr";
private TextView loactionout;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private LocationManager locationManager;
SharedPreferences sharedPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
sharedPref = getApplicationContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
loactionout = (TextView) findViewById(R.id.loactionout);
}
#Override
protected void onResume() {
super.onResume();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Turn on location?")
.setCancelable(false)
.setPositiveButton("Turn on Location", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
openWifiSettings();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else {
googleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
public void openWifiSettings() {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(500);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(LOG_TAG,"Failed");
}
#Override
public void onLocationChanged(Location location) {
Log.i("AAA",location.toString());
loactionout.setText(location.getLatitude()+"");
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("userLongitude",location.getLongitude()+"");
editor.putString("userLatitude",location.getLatitude()+"");
if(editor.commit()){
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(LOG_TAG,"Failed");
}
}
i dont know the problem. not getting connection failed on suspended callbacks also. please help me.

Related

Location returning null for longitude and latitude

I am trying to get the latitude and longitude of the current online user and store it in a firebase database but it keeps returning null. I tried to log the longitude and latitude in logcat, it's not showing anything because I applied a null check to it but if I removed the null check, it returns an error that I am referencing a double location.getLatitude in a null object reference. I don't know what I did wrong. Here is the code
public class VendorMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
private LatLng vendorLocationLatLng;
Marker customerDeliveredLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setContentView(R.layout.activity_vendor_maps);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
vendorId = mAuth.getCurrentUser().getUid();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
//update the location after one one second
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if (lastLocation !=null){
lastLocation = location;
Log.d("TAG","latitude is "+lastLocation.getLatitude());
Log.d("TAG","longitude is "+lastLocation.getLongitude());
if (getApplicationContext() !=null){
try {
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
//store the location of the current online vendor by using geofire to get the longitude and latitude of the vendor
String onlineVendorId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference vendorAvailabilityRef = FirebaseDatabase.getInstance().getReference().child("Vendors Available");
GeoFire geoFireVendorAvailable = new GeoFire(vendorAvailabilityRef);
vendorWorkingRef = FirebaseDatabase.getInstance().getReference().child("Vendors Working");
GeoFire geoFireVendorWorking = new GeoFire(vendorWorkingRef);
switch (customerId){
case "":
geoFireVendorWorking.removeLocation(onlineVendorId, new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
geoFireVendorAvailable.setLocation(vendorId, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
break;
default:
geoFireVendorAvailable.removeLocation(onlineVendorId, new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
geoFireVendorWorking.setLocation(onlineVendorId, new GeoLocation(location.getLatitude(), location.getLongitude()), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
}
});
}
}catch (Exception ignored){}
}
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (!currentVendorLogoutStatus){
disconnectTheVendor();
}
}

Signing in an account to use google play leaderboard

The following sign in code causes my game to flicker then crash after printing "bad stuff". What am I doing wrong? I tried to implement the code shown here. I attempt a silent sign in, then if that does not work I attempt an interactive sign in. I am testing an a physical Nexus 5 with the latest version of Android 8.1.0.
public class MainActivity extends Activity {
private GLSurfaceView mGLView;
private GoogleSignInAccount account;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a GLSurfaceView instance and set it
// as the ContentView for this Activity.
mGLView = new MyGLSurfaceView(this, this);
setContentView(mGLView);
hideStatusBar();
getAccount();
}
public void hideStatusBar() {
View decorView = getWindow().getDecorView();
// Hide the status bar.
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
// Remember that you should never show the action bar if the
// status bar is hidden, so hide that too if necessary.
//ActionBar actionBar = getActionBar();
//actionBar.hide();
}
private void getAccount() {
account = GoogleSignIn.getLastSignedInAccount(this);
if (account == null) {
signInSilently();
}
}
public void submitScore(int score) {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.submitScore("leaderboardID", score);
}
}
private static final int leaderboardRequestCode = 9004;
private static final int signInRequestCode = 101;
public void showLeaderboard() {
if (account == null) {
getAccount();
} else {
Games.getLeaderboardsClient(this, account)
.getLeaderboardIntent("leaderboardID")
.addOnSuccessListener(new OnSuccessListener<Intent>() {
#Override
public void onSuccess(Intent intent) {
startActivityForResult(intent, leaderboardRequestCode);
}
});
}
}
//interactive sign in
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, signInRequestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == signInRequestCode) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
account = result.getSignInAccount();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "bad stuff";
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
//silent sign in
private void signInSilently() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
signInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
account = task.getResult();
} else {
startSignInIntent();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
signInSilently();
}
}

Restore scroll position

I have a simple fragment which retrieve data from Firebase database.
I use firebase recycler view to display retrieving data. And after scrolling or screen rotation I can't force recycler view (or linear layout manager) restore scroll position.
I found here some answers but they don't work.
My code is:
public class NewsListFragment extends ParentNewsFragment {
static int color_naval, color_black;
private boolean mProcessLikes = false;
private DatabaseReference mDatabaseLikes;
private DatabaseReference mDatabaseViews;
private FirebaseAuth mAuth;
private int position = 0;
public static NewsListFragment getInstance() {
return new NewsListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDatabaseReference = FirebaseDatabase.getInstance().getReference()
.child("App_news");
mDatabaseLikes = FirebaseDatabase.getInstance().getReference().child("news_likes");
mDatabaseViews = FirebaseDatabase.getInstance().getReference().child("news_views");
mAuth = FirebaseAuth.getInstance();
mQuery = mDatabaseReference.orderByChild("pos").startAt("100");
color_naval = getResources().getColor(R.color.colorPrimary);
color_black = getResources().getColor(R.color.colorBlack);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.rv_choose, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv_choose);
lm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(lm);
rv.setHasFixedSize(true);
return rootView;
}
#Override
public void onPause() {
super.onPause();
position = lm.findFirstVisibleItemPosition();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null) {
position = savedInstanceState.getInt("position");
}
}
#Override
public void onResume() {
super.onResume();
if (position != 0) {
lm.scrollToPosition(position);
showToast(position+"");
}
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<NewsList, NewsListViewHolder> adapter =
new FirebaseRecyclerAdapter<NewsList, NewsListViewHolder>(
NewsList.class,
R.layout.frag_newslist_card_view,
NewsListViewHolder.class,
mQuery
) {
#Override
protected void populateViewHolder(NewsListViewHolder viewHolder, final NewsList model, int position) {
final String post_key = getRef(position).getKey();
viewHolder.setDate(model.getDate()+",");
viewHolder.setTime(model.getTime());
viewHolder.setTitle(model.getTitle());
viewHolder.setImage(getContext(), model.getImage());
viewHolder.setEye(model.getCode());
viewHolder.setThumb(post_key);
viewHolder.thumb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessLikes = true;
mDatabaseLikes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLikes){
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.removeValue();
mProcessLikes = false;
}
else {
mDatabaseLikes.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("like");
mProcessLikes = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseViews.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseViews.child(post_key).child(mAuth.getCurrentUser().getUid())
.setValue("view");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mChooserListener.chooseNews(model.getCode());
}
});
}
};
rv.setAdapter(adapter);
}
public static class NewsListViewHolder extends RecyclerView.ViewHolder {
//some text here
}
}
method showToast in the end shows real number of position but recyclerview starts from the beginning.
any ideas?
Make sure you are not reloading data from the server or wherever you are retrieving data.
Add is not null check in your fragment's onCreateView or activity's onCreate like:
if(savedInstanceState != null){
...
}else{
loadData();
}
Replace your linear layout manager with something similar to the following. I have used this implementation many times when using RecyclerView in fragments. Let me know how it goes
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
yourItem.setLayoutManager(mLayoutManager);

Android-how to send continuous latitude and longitude to the server?

I continuously get the current location, now I want to send this continuous location to the sever every 1 to 5 sec. How do I do this?
Android code:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
TextView txtOutputLat, txtOutputLon;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String lat, lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOutputLat = (TextView) findViewById(R.id.textView);
txtOutputLon = (TextView) findViewById(R.id.textView2);
buildGoogleApiClient();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = String.valueOf(mLastLocation.getLatitude());
lon = String.valueOf(mLastLocation.getLongitude());
}
updateUI();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
updateUI();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
buildGoogleApiClient();
}
synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
void updateUI() {
txtOutputLat.setText(lat);
txtOutputLon.setText(lon);
}
}

Estimote : Show notification when the app is closed

How to show notification when the app is closed with estimote api.As it is having default BeaconService we need to implement it in the application level to show the notification when the app is closed.So for that i'm trying with the following code.
Activity:-
public class Dashboard extends Activity {
private static final String TAG = Dashboard.class.getSimpleName();
ConnectionDetector cDetector;
private static final int NOTIFICATION_ID = 123;
private NotificationManager notificationManager;
JSONParser jParser = new JSONParser();
AlertDialogManager alert;
private static final String URL_NOTIFICATIONS = "";
ArrayList<NameValuePair> pairs;
private static final int REQUEST_ENABLE_BT = 1234;
private ProgressDialog pDialog;
private BeaconManager bManager;
// private Beacon beacon;
private Region region = new Region("regionID", null, null, null);
List<Beacon> beaconList;
BroadcastReceiver receiver;
Intent serviceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_demo);
getActionBar().setDisplayHomeAsUpEnabled(true);
cDetector = new ConnectionDetector(getApplicationContext());
// check Internet connection
if (!cDetector.isConnectingToInternet()) {
alert.showAlertDialog(this, "Internet Connection Error",
"Please connect to working internet connection", false);
return;
}
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region region,
final List<Beacon> beacons) {
// Note that results are not delivered on UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// Note that beacons reported here are already sorted by
// estimated distance between device and beacon.
getActionBar().setSubtitle(
"Found beacons: " + beacons.size());
}
});
}
});
Log.i("BeaconsList", "beaconslist" + beaconList);
// region = new Region("regionId", ((Beacon)
// beaconList).getProximityUUID(),
// ((Beacon) beaconList).getMajor(),
// ((Beacon) beaconList).getMinor());
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
// new GetNotificationData().execute();
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
#Override
protected void onStart() {
super.onStart();
// Check if device supports Bluetooth Low Energy.
if (!bManager.hasBluetooth()) {
Toast.makeText(this, "Device does not have Bluetooth Low Energy",
Toast.LENGTH_LONG).show();
return;
}
// If Bluetooth is not enabled, let user enable it.
if (!bManager.isBluetoothEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
connectToService();
}
}
#Override
protected void onStop() {
try {
bManager.stopRanging(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while stopping ranging", e);
}
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
connectToService();
} else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG)
.show();
getActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService() {
getActionBar().setSubtitle("Scanning...");
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startRanging(region);
} catch (RemoteException e) {
Toast.makeText(
Dashboard.this,
"Cannot start ranging, something terrible happened",
Toast.LENGTH_LONG).show();
Log.e(TAG, "Cannot start ranging", e);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
notificationManager.cancel(NOTIFICATION_ID);
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d(TAG, "Error while starting monitoring");
}
}
});
}
#Override
protected void onDestroy() {
notificationManager.cancel(NOTIFICATION_ID);
bManager.disconnect();
super.onDestroy();
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(Dashboard.this, Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
Dashboard.this, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(Dashboard.this)
.setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
TextView statusTextView = (TextView) findViewById(R.id.status);
statusTextView.setText(msg);
}
}
Application Class:-
public class MyApplication extends Application {
BeaconManager bManager;
NotificationManager notificationManager;
private Region region = new Region("regionID", null, null, null);
private static final int NOTIFICATION_ID = 123;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
bManager = new BeaconManager(getApplicationContext());
bManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region regions, List<Beacon> beacons) {
// TODO Auto-generated method stub
Log.i("Beacons", "" + beacons.size());
}
});
bManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
bManager.startMonitoring(region);
} catch (RemoteException e) {
Log.d("BEACON", "Error while starting monitoring");
}
}
});
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.In order for this demo to be more responsive and immediate we
// lower down those values.
bManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
bManager.setMonitoringListener(new MonitoringListener() {
#Override
public void onEnteredRegion(Region arg0, List<Beacon> arg1) {
// TODO Auto-generated method stub
postNotification("Welcome to Walmart !Today there is 10% off on all Goods.");
}
#Override
public void onExitedRegion(Region arg0) {
// TODO Auto-generated method stub
postNotification("Exit region");
}
});
}
private void postNotification(String msg) {
Intent notifyIntent = new Intent(getApplicationContext(),
Dashboard.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
getApplicationContext(), 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(
getApplicationContext()).setSmallIcon(R.drawable.beacon_gray)
.setContentTitle("Notify Demo").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
and i have mentioned the beaconservice in manifest also as follows..
Can any one help what is going wrong here and how can show the notification when the app is closed.