I've been working with Android Studio for a short time and this is my first project. I don't know a lot of points, and I apologize for my complex code. There are only 1 consumable product in my app and gives the user 20 lives. I succeeded in adding in-app purchase to my application as a result of long efforts. In my application I was able to make purchases with google test cards with my own product ID. I did not have any problems up to here. Since I don't have a server, I have to do the purchase verification on the device. I wrote all purchase and verification codes in an activity. I think it might sound a bit silly, but I don't know where to make the confirmation of the purchase. My application accepts verification even if it is an incorrect signature. What is the point I missed in my codes?
public class MagazaActivity extends AppCompatActivity {
Button baslik, buy_button;
Can hak;
int can;
private BillingClient mBillingClient;
private final List<Purchase> mPurchases = new ArrayList<>();
private static final String BASE_64_ENCODED_PUBLIC_KEY = "XXXXX";
private static final String TAG = "IABUtil/Security";
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
String canfiyat;
mBillingClient =BillingClient.newBuilder(MagazaActivity.this).
setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated ( int responseCode,
#Nullable List<Purchase> purchases){
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (final Purchase purchase : purchases) {
ConsumeResponseListener listener = new
ConsumeResponseListener() {
#Override
public void
onConsumeResponse(#BillingClient.BillingResponse int responseCode, String
outToken) {
if (responseCode ==
BillingClient.BillingResponse.OK) {
handlePurchase(purchase);
}
}
};
mBillingClient.consumeAsync(purchase.getPurchaseToken(), listener);
}
} else if (responseCode ==
BillingClient.BillingResponse.USER_CANCELED) {
billingCanceled();
}
else {
AlertDialog.Builder builder2 = new
AlertDialog.Builder(MagazaActivity.this, R.style.AlertDialogCustom);
builder2.setMessage("Billing System İs İnvalid");
builder2.setCancelable(true);
LayoutInflater factory =
LayoutInflater.from(MagazaActivity.this);
final View view = factory.inflate(R.layout.sample4,
null);
builder2.setView(view);
builder2.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder2.create();
alert11.show();
}
}
}).
build();
buy_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener()
{
#Override
public void
onBillingSetupFinished(#BillingClient.BillingResponse int
billingResponseCode) {
if (billingResponseCode ==
BillingClient.BillingResponse.OK) {
final List<String> skuList = new ArrayList<>();
skuList.add("XXX");
SkuDetailsParams skuDetailsParams =
SkuDetailsParams.newBuilder()
.setSkusList(skuList).setType(BillingClient.SkuType.INAPP).build();
mBillingClient.querySkuDetailsAsync(skuDetailsParams,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int
responseCode,
List<SkuDetails> skuDetailsList) {
BillingFlowParams flowParams =
BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(0))
.build();
int billingResponseCode =
mBillingClient.launchBillingFlow(MagazaActivity.this, flowParams);
if (billingResponseCode ==
BillingClient.BillingResponse.OK) {
for (SkuDetails skuDetails :
skuDetailsList) {
String sku =
skuDetails.getSku();
String price =
skuDetails.getPrice();
if ("XXX".equals(sku)) {
canfiyat = price;
}
}
}
}
});
}
}
#Override
public void onBillingServiceDisconnected() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MagazaActivity.this);
builder.setMessage("Connection Error")
.setCancelable(false)
.setPositiveButton("Retry", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
#Override
public void onBackPressed() {
Intent intentLayout8 = new Intent(MagazaActivity.this,
MainActivity.class);
startActivity(intentLayout8);
MagazaActivity.this.finish();
}
private void billingCanceled() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MagazaActivity.this);
builder.setMessage("Purchase Canceled")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey,
Base64.DEFAULT);
KeyFactory keyFactory =
KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new
X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
}
}
public static boolean verifyPurchase(String base64PublicKey, String
signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey)
||
TextUtils.isEmpty(signature)) {
Log.e("HATA", "Purchase verification failed");
return false;
}
PublicKey key = MagazaActivity.generatePublicKey(base64PublicKey);
return MagazaActivity.verify(key, signedData, signature);
}
public static boolean verify(PublicKey publicKey, String signedData, String
signature) {
byte[] signatureBytes;
try {
signatureBytes = Base64.decode(signature, Base64.DEFAULT);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Base64 decoding failed.");
return false;
}
try {
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(signatureBytes)) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key specification.");
} catch (SignatureException e) {
Log.e(TAG, "Signature exception.");
}
return false;
}
private boolean verifyValidSignature(String signedData, String signature) {
try {
return MagazaActivity.verifyPurchase(BASE_64_ENCODED_PUBLIC_KEY,
signedData, signature);
} catch (Exception e) {
Log.e(TAG, "Got an exception trying to validate a purchase: " + e);
return false;
}
}
public void handlePurchase(Purchase purchase) {
if (!verifyValidSignature(purchase.getOriginalJson(),
purchase.getSignature())) {
Log.i("Warning", "Purchase: " + purchase + "; signature
failure...");
return;
}
Log.d("MESAJ", "Got a verified purchase: " + purchase);
hak.cancan = hak.cancan + 20;
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putInt("kalp", hak.cancan);
editor.apply();
mPurchases.add(purchase);
}
public void onResume() {
super.onResume();
}
}
Related
i am tried to stream video from uvc camera with agora video call api. but it doesn't work . but the uvc camera preview show proferly on '''''' .
public class VideoChatViewActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback{
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
// Permission WRITE_EXTERNAL_STORAGE is not mandatory
// for Agora RTC SDK, just in case if you wanna save
// logs to external sdcard.
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private VideoCanvas mLocalVideo;
private VideoCanvas mRemoteVideo;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
private LoggerRecyclerView mLogView;
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onUserJoined(final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft(uid);
}
});
}
};
private void setupRemoteVideo(int uid) {
ViewGroup parent = mRemoteContainer;
if (parent.indexOfChild(mLocalVideo.view) > -1) {
parent = mLocalContainer;
}
if (mRemoteVideo != null) {
return;
}
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(parent == mLocalContainer);
parent.addView(view);
mRemoteVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid);
// Initializes the video view of a remote user.
mRtcEngine.setupRemoteVideo(mRemoteVideo);
}
private void onRemoteUserLeft(int uid) {
if (mRemoteVideo != null && mRemoteVideo.uid == uid) {
removeFromParent(mRemoteVideo);
// Destroys remote view
mRemoteVideo = null;
}
}
//usb
private static final int DEFAULT_CAPTURE_WIDTH = 1280;
private static final int DEFAULT_CAPTURE_HEIGHT = 720;
#BindView(R.id.camer_view)
public View mTextureView;
private static final String TAG1 = "Debug";
private UVCCameraHelper mCameraHelper;
private CameraViewInterface mUVCCameraView;
private AlertDialog mDialog;
private boolean isRequest;
private boolean isPreview;
private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
#Override
public void onAttachDev(UsbDevice device) {
// request open permission
if (!isRequest) {
isRequest = true;
if (mCameraHelper != null) {
mCameraHelper.requestPermission(0);
}
}
}
#Override
public void onDettachDev(UsbDevice device) {
// close camera
if (isRequest) {
isRequest = false;
mCameraHelper.closeCamera();
showShortMsg(device.getDeviceName() + " is out");
}
}
#Override
public void onConnectDev(UsbDevice device, boolean isConnected) {
if (!isConnected) {
showShortMsg("fail to connect,please check resolution params");
isPreview = false;
} else {
isPreview = true;
showShortMsg("connecting");
// initialize seekbar
// need to wait UVCCamera initialize over
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.prepare();
if(mCameraHelper != null && mCameraHelper.isCameraOpened()) {
}
Looper.loop();
}
}).start();
}
}
#Override
public void onDisConnectDev(UsbDevice device) {
showShortMsg("disconnecting");
}
};
//usb
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
ButterKnife.bind(this);//uvc
initUI();
mUVCCameraView = (CameraViewInterface) mTextureView;
mUVCCameraView.setCallback(this);
//mLocalContainer.setCallback(this);
mCameraHelper = UVCCameraHelper.getInstance();
mCameraHelper.setDefaultPreviewSize(1280,720);
mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);
mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
#Override
public void onPreviewResult(byte[] bytes) {
try {
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = bytes;
frame.format = AgoraVideoFrame.FORMAT_NV21;
frame.stride = DEFAULT_CAPTURE_WIDTH;
frame.height = DEFAULT_CAPTURE_HEIGHT;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}catch (Exception e){
e.printStackTrace();
}
}
});
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
mLogView = findViewById(R.id.log_recycler_view);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
mLogView.logI("Welcome to Agora 1v1 video call");
mLogView.logW("You will see custom logs here");
mLogView.logE("You can also use this to show errors");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
mRtcEngine.enableVideo();
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
.
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(true);
mLocalContainer.addView(view);
mLocalVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, 0);
mRtcEngine.setupLocalVideo(mLocalVideo);
}
private void joinChannel() {
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token) || TextUtils.equals(token, "#YOUR ACCESS TOKEN#")) {
token = null; // default, no token
}
mRtcEngine.joinChannel(token, "streaming", "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeFromParent(mLocalVideo);
mLocalVideo = null;
removeFromParent(mRemoteVideo);
mRemoteVideo = null;
leaveChannel();
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View. SurfaceView view .GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
private ViewGroup removeFromParent(VideoCanvas canvas) {
if (canvas != null) {
ViewParent parent = canvas.view.getParent();
if (parent != null) {
ViewGroup group = (ViewGroup) parent;
group.removeView(canvas.view);
return group;
}
}
return null;
}
private void switchView(VideoCanvas canvas) {
ViewGroup parent = removeFromParent(canvas);
if (parent == mLocalContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(false);
}
mRemoteContainer.addView(canvas.view);
} else if (parent == mRemoteContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(true);
}
mLocalContainer.addView(canvas.view);
}
}
public void onLocalContainerClick(View view) {
switchView(mLocalVideo);
switchView(mRemoteVideo);
}
///uvc
#Override
protected void onStart() {
super.onStart();
// step.2 register USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.registerUSB();
}
}
#Override
protected void onStop() {
super.onStop();
// step.3 unregister USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.unregisterUSB();
}
}
private void showShortMsg(String msg) {
//
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public USBMonitor getUSBMonitor(){ return mCameraHelper.getUSBMonitor();
}
#Override
public void onDialogResult(boolean canceled) {
if (canceled) {
showShortMsg("cancel");
}
}
#Override
public void onSurfaceCreated(CameraViewInterface cameraViewInterface, Surface surface) {
if (!isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.startPreview(mUVCCameraView);
isPreview = true;
}
}
#Override
public void onSurfaceChanged(CameraViewInterface cameraViewInterface, Surface surface, int i, int i1) {
}
#Override
public void onSurfaceDestroy(CameraViewInterface cameraViewInterface, Surface surface) {
if (isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.stopPreview();
isPreview = false;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
//xiaobing add
final View view = findViewById(R.id.camera_view);
mUVCCameraView = (CameraViewInterface)view;
mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
mUVCCameraView.setAspectRatio(previewWidth / (float)previewHeight);
mCameraHandler = UVCCameraHandler.createHandler(this,
mUVCCameraView, previewWidth,
previewHeight, BANDWIDTH_FACTORS[0],
firstDataCallBack);
}
//xiaobing add
private void startPreview() {
final SurfaceTexture st = mUVCCameraView.getSurfaceTexture();
mCameraHandler.startPreview(new Surface(st));
}
//xiaobing add
UvcCameraDataCallBack firstDataCallBack = new UvcCameraDataCallBack() {
#Override
public void getData(byte[] data) {
if (DEBUG) {
Log.v(TAG, "data callback:" + data.length);
}
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = data;
frame.format = AgoraVideoFrame.FORMAT_NV12;
frame.stride = previewWidth;
frame.height = previewHeight;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}
};
//xiaobing add
#Override
protected void onStart() {
super.onStart();
if (DEBUG) Log.v(TAG, "onStart:");
mUSBMonitor.register();
if (mUVCCameraView != null)
mUVCCameraView.onResume();
if (!mCameraHandler.isOpened()) {
UsbManager um = (UsbManager) (getSystemService(Context.USB_SERVICE));
HashMap<String, UsbDevice> map = um.getDeviceList();
ArrayList<String> names = new ArrayList<>();
final ArrayList<UsbDevice> devices = new ArrayList<>();
for(Map.Entry<String, UsbDevice> item : map.entrySet()) {
String name = item.getValue().getProductName();
String vid = Integer.toHexString(item.getValue().getVendorId());
String pid = Integer.toHexString(item.getValue().getProductId());
String all = "" + name + " VID:" + vid
+ " PID:" + pid;
Log.v("xiaobing", "all:" + all);
names.add(all);
devices.add(item.getValue());
if(item.getValue().getProductId()==1383 && (item.getValue().getVendorId() == 3034)){
mDev = item.getValue();
mUSBMonitor.requestPermission(mDev);
//为了同时支持手机和眼镜,只有获得了眼镜的设备才选择本地视频
mRtcEngine.setExternalVideoSource(true, true, true);
mLogView.logI("使用USB摄像头!");
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I managed to establish a bluetooth connection from my main activity but i want to print from another activity.
How can I do this?
Main Activity Where I Start A connection to a bluetooth printer
protected static final String TAG = "TAG";
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private ProgressDialog BluetoothConnectProgressDialog;
Button button_connect_to_bluetooth_printer;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private BluetoothDevice bluetoothDevice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_connect_to_bluetooth_printer = findViewById(R.id.btn_connect_bluetooth);
button_connect_to_bluetooth_printer.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this, BluetoothDeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
});
}
private void ListPairedDevices()
{
Set<BluetoothDevice> PairedDevices = bluetoothAdapter.getBondedDevices();
if (PairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : PairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + mDevice.getAddress());
}
}
}
public void onActivityResult(int RequestCode, int ResultCode, Intent DataIntent)
{
super.onActivityResult(RequestCode, ResultCode, DataIntent);
switch (RequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (ResultCode == Activity.RESULT_OK)
{
Bundle mExtra = DataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
bluetoothDevice = bluetoothAdapter
.getRemoteDevice(mDeviceAddress);
BluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress(), true, true);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (ResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
BluetoothDeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(MainActivity.this, "Message", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void run()
{
try
{
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
bluetoothAdapter.cancelDiscovery();
bluetoothSocket.connect();
handler.sendEmptyMessage(0);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(bluetoothSocket);
return;
}
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg)
{
BluetoothConnectProgressDialog.dismiss();
}
};
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
this is my device list activity
protected static final String TAG = "TAG";
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> paired_devices_list;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_bluetooth_device_list);
setResult(Activity.RESULT_CANCELED);
paired_devices_list = new ArrayAdapter<>(this, R.layout.bluetooth_device_name);
ListView PairedListDevices = findViewById(R.id.paired_devices);
PairedListDevices.setAdapter(paired_devices_list);
PairedListDevices.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
try
{
bluetoothAdapter.cancelDiscovery();
String mdeviceInfo = ((TextView) view).getText().toString();
String deviceAddress = mdeviceInfo.substring(mdeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + deviceAddress);
Bundle bundle = new Bundle();
bundle.putString("DeviceAddress", deviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(bundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> PairedDevices = bluetoothAdapter.getBondedDevices();
if (PairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : PairedDevices)
{
paired_devices_list.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String NoDevices = "None Paired";
paired_devices_list.add(NoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (bluetoothAdapter != null)
{
bluetoothAdapter.cancelDiscovery();
}
}
And this my print activity
public void print()
{
Thread t = new Thread()
{
public void run()
{
try
{
OutputStream os = bluetoothSocket.getOutputStream();
String account_no;
account_no_value = ""+ Account_No.getText().toString()+"\n";
os.write(account_no.getBytes());
}
catch (Exception e)
{
Log.e("PrintActivity", "Exe ", e);
}
}
};
t.start();
}
E/PrintActivity: Exe
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream android.bluetooth.BluetoothSocket.getOutputStream()' on a null object reference
at com.vicjames.qiimeterreader.PrintBill$6.run(PrintBill.java:1635)
how can I fix this?? The app is not crashing but it wont print either.
I am getting the following Error: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
this the Logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.shibli.luxuryrider.Home.requestPickupHere(Home.java:338)
at com.example.shibli.luxuryrider.Home.access$000(Home.java:96)
at com.example.shibli.luxuryrider.Home$2.onClick(Home.java:217)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20300)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5682)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)
and this the code .. any help please
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mService = Common.getFCMService();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//init storage
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navigationHeaderView = navigationView.getHeaderView(0);
txtRiderName = navigationHeaderView.findViewById(R.id.txtRiderName);
txtRiderName.setText(String.format("%s", Common.currentUser.getName()));
txtStars = navigationHeaderView.findViewById(R.id.txtStars);
txtStars.setText(String.format("%s", Common.currentUser.getRates()));
imageAvatar = navigationHeaderView.findViewById(R.id.imageAvatar);
//Load avatar
if (Common.currentUser.getAvatarUrl() != null && !TextUtils.isEmpty(Common.currentUser.getAvatarUrl())) {
Picasso.with(this)
.load(Common.currentUser.getAvatarUrl())
.into(imageAvatar);
}
//Maps
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Geo Fire
ref = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire(ref);
//init View
imgExpandable = (ImageView)findViewById(R.id.imgExpandable);
mBottomSheet = BottomSheetRiderFragment.newInstance("Rider bottom sheet");
imgExpandable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheet.show(getSupportFragmentManager(),mBottomSheet.getTag());
}
});
btnPickupRequest = (Button) findViewById(R.id.btnPickupRequest);
btnPickupRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!Common.isDriverFound)
requestPickupHere(FirebaseAuth.getInstance().getCurrentUser().getUid());
else
sendRequestToDriver(Common.driverId);
}
});
place_destination = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_destination);
place_location = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_location);
typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.setTypeFilter(3)
.build();
//Event
place_location.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mPlaceLocation = place.getAddress().toString();
//Remove Old Marker
mMap.clear();
//Add Marker at New Location
mUserMarker = mMap.addMarker(new MarkerOptions().position(place.getLatLng())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.title("Pickup Here"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));
}
#Override
public void onError(Status status) {
}
});
place_destination.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mPlaceDestination = place.getAddress().toString();
//Add New destination Marker
mMap.addMarker(new MarkerOptions()
.position(place.getLatLng())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 15.0f));
// Show information in bottom
BottomSheetRiderFragment mBottomsheet = BottomSheetRiderFragment.newInstance(mPlaceLocation);
mBottomsheet.show(getSupportFragmentManager(), mBottomsheet.getTag());
}
#Override
public void onError(Status status) {
}
});
setUpLocation();
updateFirebaseToken();
}
private void updateFirebaseToken() {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tb1);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(token);
}
private void sendRequestToDriver(String driverId) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tb1);
tokens.orderByKey().equalTo(driverId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot : dataSnapshot.getChildren()) {
Token token = postSnapShot.getValue(Token.class);
//Make raw payload
String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
String riderToken = FirebaseInstanceId.getInstance().getToken();
Notification data = new Notification(riderToken, json_lat_lng);
Sender content = new Sender(token.getToken(), data);
mService.sendMessage(content)
.enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if (response.body().success == 1)
Toast.makeText(Home.this, "Request sent", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e("ERROR", t.getMessage());
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void requestPickupHere(String uid) {
DatabaseReference dbRequest = FirebaseDatabase.getInstance().getReference(Common.pickup_request_tb1);
GeoFire mGeoFire = new GeoFire(dbRequest);
mGeoFire.setLocation(uid, new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
if (mUserMarker.isVisible())
mUserMarker.remove();
//Add new Marker
mUserMarker = mMap.addMarker(new MarkerOptions()
.title("Pickup Here")
.snippet("")
.position(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mUserMarker.showInfoWindow();
btnPickupRequest.setText("Getting your Driver...");
findDriver();
}
private void findDriver() {
final DatabaseReference drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
GeoFire gfDrivers = new GeoFire(drivers);
final GeoQuery geoQuery = gfDrivers.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()), radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
// if found
if (!Common.isDriverFound) {
Common.isDriverFound = true;
Common.driverId = key;
btnPickupRequest.setText("CALL DRIVER");
Toast.makeText(Home.this, ""+key, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onKeyExited(String key) {
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
}
#Override
public void onGeoQueryReady() {
//if still not found driver , increase distance
if (!Common.isDriverFound && radius < LIMIT) {
radius++;
findDriver();
} else {
if (!Common.isDriverFound) {
Toast.makeText(Home.this, "No available any driver near you", Toast.LENGTH_SHORT).show();
btnPickupRequest.setText("REQUEST PICKUP");
geoQuery.removeAllListeners();
}
}
}
#Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setUpLocation();
}
break;
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
} else {
buildLocationCallBack();
createLocationRequest();
displayLocation();
}
}
private void buildLocationCallBack() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Common.mLastLocation = locationResult.getLocations().get(locationResult.getLocations().size() - 1);
displayLocation();
}
};
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null) {
LatLng center = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());
LatLng northSide = SphericalUtil.computeOffset(center, 100000, 0);
LatLng southSide = SphericalUtil.computeOffset(center, 100000, 180);
LatLngBounds bounds = LatLngBounds.builder()
.include(northSide)
.include(southSide)
.build();
place_location.setBoundsBias(bounds);
place_location.setFilter(typeFilter);
place_destination.setBoundsBias(bounds);
place_location.setFilter(typeFilter);
driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
driversAvailable.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
LoadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude()));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
LoadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude()));
Log.d("EDMTDEV", String.format("Your location was changed: %f / %f", latitude, longitude));
} else {
Log.d("ERROR", "Cannot get your location");
}
}
});
}
private void LoadAllAvailableDriver(final LatLng location) {
//Add Marker
mMap.clear();
mUserMarker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
.position(location)
.title("You'r Location"));
//Move Camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 15.0f));
//Load all available Driver in distance 3km
DatabaseReference driverLocation = FirebaseDatabase.getInstance().getReference(Common.driver_tb1);
GeoFire gf = new GeoFire(driverLocation);
GeoQuery geoQuery = gf.queryAtLocation(new GeoLocation(location.latitude, location.longitude), distance);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, final GeoLocation location) {
FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1)
.child(key)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Rider rider = dataSnapshot.getValue(Rider.class);
//Add Driver to map
mMap.addMarker(new MarkerOptions()
.position(new LatLng(location.latitude, location.longitude))
.flat(true)
.title(rider.getName())
.snippet("Phone : "+rider.getPhone())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onKeyExited(String key) {
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
}
#Override
public void onGeoQueryReady() {
if (distance <= LIMIT) // distance just find for 3 km
{
distance++;
LoadAllAvailableDriver(location);
}
}
#Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_signOut) {
signout();
} else if (id == R.id.nav_updateInformation) {
showUpdateInformationDialog();
}
return true;
}
private void showUpdateInformationDialog() {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(Home.this);
alertdialog.setTitle("Update Information");
alertdialog.setMessage("Please Enter Your New data");
LayoutInflater inflater = this.getLayoutInflater();
View update_info_layout = inflater.inflate(R.layout.layout_update_information, null);
final MaterialEditText edtName = update_info_layout.findViewById(R.id.edtName);
final MaterialEditText edtPhone = update_info_layout.findViewById(R.id.edtPhone);
final ImageView imgAvatar = update_info_layout.findViewById(R.id.imgAvatar);
alertdialog.setView(update_info_layout);
imgAvatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImageAndUpload();
}
});
alertdialog.setView(update_info_layout);
//set Button
alertdialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog(Home.this);
waitingDialog.show();
String name = edtName.getText().toString();
String phone = edtPhone.getText().toString();
Map<String, Object> update = new HashMap<>();
if (!TextUtils.isEmpty(name))
update.put("name", name);
if (!TextUtils.isEmpty(phone))
update.put("phone", phone);
//update
DatabaseReference riderInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tb1);
riderInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
if (task.isSuccessful())
Toast.makeText(Home.this, "Information Updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Information Not Update", Toast.LENGTH_SHORT).show();
}
});
}
});
alertdialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
//show Dialog
alertdialog.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_RECUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
progressDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map<String, Object> update = new HashMap<>();
update.put("avatarUrl", uri.toString());
DatabaseReference riderInformation = FirebaseDatabase.getInstance().getReference(Common.user_rider_tb1);
riderInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(Home.this, "Avatar Was Upoload", Toast.LENGTH_SHORT).show();
else
Toast.makeText(Home.this, "Avatar Not Update", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Home.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded" + progress + "%");
}
});
}
}
}
private void chooseImageAndUpload() {
//start intent to chose image
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_RECUEST);
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
boolean isSuccess = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(this, R.raw.uber_style_map)
);
if (!isSuccess)
Log.e("ERROR", "Map Style Load Failed !!!");
} catch (Resources.NotFoundException ex) {
ex.printStackTrace();
}
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.setInfoWindowAdapter(new CustomInfoWindow(this));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (markerDestination != null)
markerDestination.remove();
markerDestination = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
.position(latLng)
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
BottomSheetRiderFragment mBottomsheet = BottomSheetRiderFragment.newInstance(String.format("%f,%f", mLastLocation.getLatitude(), mLastLocation.getLongitude())
);
mBottomsheet.show(getSupportFragmentManager(), mBottomsheet.getTag());
}
});
if (ActivityCompat.checkSelfPermission(Home.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(Home.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
THE SOLUTION IS THIS:
IN sendRequestToDriver(String driverId)
change:
this:Token token = postSnapShot.getValue(Token.class);
into this: Token token = new Token(postSnapShot.getValue(String.class));
This is the gps class for mainactivity to call track user location
public class TrackGPS extends Service implements LocationListener{
private final Context mContext;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
public double latitude;
public double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public TrackGPS(Context mContext) {
this.mContext = mContext;
getLocation();
}
This is the get the location code for longitude and latitude
private Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
This is to check whether network and gps is turn on ?
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
catch(SecurityException e){
Toast.makeText(TrackGPS.this, "please turn on gps", Toast.LENGTH_SHORT).show();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}
public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
}
return latitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
// if (locationManager != null) {
//
// locationManager.removeUpdates(TrackGPS.this);
// }
try {
locationManager.removeUpdates(TrackGPS.this);
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION","PERMISSION_NOT_GRANTED");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
how to get the location updated longitude and latitude from mainactivity when every time is change ?
#Override
public void onLocationChanged(Location location) {
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
}
this is call in main activity to get the location
public void getLocation() {
gps = new TrackGPS(econtacts.this);
if (gps.canGetLocation()) {
longitude = gps.getLongitude();
latitude = gps.getLatitude();
// Toast.makeText(getApplicationContext(), "Longitude:" + Double.toString(longitude) + "\nLatitude:" + Double.toString(latitude), Toast.LENGTH_SHORT).show();
} else {
gps.showSettingsAlert();
}
}
How to Create Geo fence(Creating and Monitoring Geo fences) on current latitude,longitude.
I am trying multiple example but not create.
Using this code:
public Geofence geofence(float radius, double latitude, double longitude) {
String id = UUID.randomUUID().toString();
return new Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.setCircularRegion(latitude, longitude, radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
}
There's this tutorial from Google, that's very easy to follow:
http://io2015codelabs.appspot.com/codelabs/geofences
There's also a course at Udacity that teaches location services, including geofences:
https://www.udacity.com/course/google-location-services-on-android--ud876-1
Add Google Play Services to Gradle File:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.3.0'
}
Add to Manifest File:
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Add to Activity's XML Layout file:
<Button
android:id="#+id/add_geofences_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:onClick="addGeofencesButtonHandler"
android:text="Add GeoFences" />
Add to Activity's Java File:
public class MainActivity extends Activity
implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ResultCallback<Status>{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
// Empty list for storing geofences.
mGeofenceList = new ArrayList<Geofence>();
// Get the geofences used. Geofence data is hard coded in this sample.
populateGeofenceList();
// Kick off the request to build GoogleApiClient.
buildGoogleApiClient();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void populateGeofenceList() {
for (Map.Entry<String, LatLng> entry : Constants.LANDMARKS.entrySet()) {
mGeofenceList.add(new Geofence.Builder()
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
}
}
#Override
protected void onStart() {
super.onStart();
if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do something with result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
mGoogleApiClient.connect();
}
public void addGeofencesButtonHandler(View view) {
if (!mGoogleApiClient.isConnected()) {
Toast.makeText(this, "Google API Client not connected!", Toast.LENGTH_SHORT).show();
return;
}
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this); // Result processed in onResult().
} catch (SecurityException securityException) {
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
}
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling addgeoFences()
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void onResult(Status status) {
if (status.isSuccess()) {
Toast.makeText(
this,
"Geofences Added",
Toast.LENGTH_SHORT
).show();
} else {
// Get the status code for the error and log it using a user-friendly message.
String errorMessage = GeofenceErrorMessages.getErrorString(this,
status.getStatusCode());
}
}
Create a java file called Constans:
public class Constants {
public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 12 * 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 20;
public static final HashMap<String, LatLng> LANDMARKS = new HashMap<String, LatLng>();
static {
// San Francisco International Airport.
LANDMARKS.put("Moscone South", new LatLng(37.783888,-122.4009012));
// Googleplex.
LANDMARKS.put("Japantown", new LatLng(37.785281,-122.4296384));
// Test
LANDMARKS.put("SFO", new LatLng(37.621313,-122.378955));
}
}
Create a java file called GeofenceTransitionsIntentService:
public class GeofenceTransitionsIntentService extends IntentService {
protected static final String TAG = "GeofenceTransitionsIS";
public GeofenceTransitionsIntentService() {
super(TAG); // use TAG to name the IntentService worker thread
}
#Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent event = GeofencingEvent.fromIntent(intent);
if (event.hasError()) {
Log.e(TAG, "GeofencingEvent Error: " + event.getErrorCode());
return;
}
}
String description = getGeofenceTransitionDetails(event);
sendNotification(description);
}
private static String getGeofenceTransitionDetails(GeofencingEvent event) {
String transitionString =
GeofenceStatusCodes.getStatusCodeString(event.getGeofenceTransition());
List triggeringIDs = new ArrayList();
for (Geofence geofence : event.getTriggeringGeofences()) {
triggeringIDs.add(geofence.getRequestId());
}
return String.format("%s: %s", transitionString, TextUtils.join(", ", triggeringIDs));
}
private void sendNotification(String notificationDetails) {
// Create an explicit content Intent that starts MainActivity.
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Get a PendingIntent containing the entire back stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class).addNextIntent(notificationIntent);
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText("Click notification to return to App")
.setContentIntent(notificationPendingIntent)
.setAutoCancel(true);
// Fire and notify the built Notification.
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
You should probably stick to their tutorial instead of copying and pasting the code to your project :D
Source
I am doing it in a Service
GeolocationService
public class GeolocationService extends Service implements LocationListener,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
// private Location mLastLocation;
private PendingIntent mGeofencePendingIntent;
private String mLastUpdateTime;
public static boolean isGeoFenceAdded = false;
private boolean mUpdateGeoFence = false;
private boolean mRemoveAllGeoFence = false;
private static final long TIME_OUT = 100;
#Override
public void onCreate() {
super.onCreate();
mContext = GeolocationService.this;
buildGoogleApiClient();
createLocationRequest();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
/// FIXME: 2/15/2017 connect should be handled through onStart and onStop of Activity
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);//set the interval in which you want to get locations
mLocationRequest.setFastestInterval(2500);//if a location is available sooner you can get it (i.e. another app is using the location services)
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
if (intent.getAction() != null) {
if (intent.getAction().equals(Constants.ACTION_UPDATE_GEOFENCE)) {
//// FIXME: 3/21/2017 you can also receive triggered location here..
mUpdateGeoFence = true;
isGeoFenceAdded = false;
mRemoveAllGeoFence = false;
} else if (intent.getAction().equals(Constants.ACTION_ADD_GEOFENCE)) {
mUpdateGeoFence = false;
isGeoFenceAdded = false;
mRemoveAllGeoFence = false;
} else if (intent.getAction().equals(Constants.ACTION_REMOVE_ALL_GEOFENCE)) {
mRemoveAllGeoFence = true;
isGeoFenceAdded = true;
mUpdateGeoFence = false;
}
}
}
//try this for null as http://stackoverflow.com/a/25096022/3496570
///return START_REDELIVER_INTENT;
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
startLocationUpdates(mContext);
}
#Override
public void onConnectionSuspended(int i) {
switch (i) {
case CAUSE_SERVICE_DISCONNECTED:
/*if (onLocationUpdateListener != null)
onLocationUpdateListener.onError(
Constants.ErrorType.SERVICE_DISCONNECTED);*/
break;
case CAUSE_NETWORK_LOST:
/*if (onLocationUpdateListener != null)
onLocationUpdateListener.onError(
Constants.ErrorType.NETWORK_LOST);*/
break;
}
//// FIXME: 3/2/2017 check is it right to check for re Connecting..
//--- http://stackoverflow.com/a/27350444/3496570
///mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
/*if (onLocationUpdateListener != null)
onLocationUpdateListener.onError(
Constants.ErrorType.CONNECTION_FAIL);*/
//// FIXME: 3/3/2017 call a transparent activity and call startResolutionForresult from their and return result to service using action
if (connectionResult.hasResolution()) {
/*try {
// !!!
connectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}*/
} else {
/*GoogleApiAvailability.getInstance().getErrorDialog(mContext, connectionResult.getErrorCode(), 0).show();
return;*/
}
}
#Override
public void onLocationChanged(final Location currentLocation) {
setupGeoFencePoints(currentLocation);
/*if (onLocationUpdateListener != null && mLocation != null) {
onLocationUpdateListener.onLocationChange(mLocation);
}*/
}
private void setupGeoFencePoints(final Location currentLocation) {
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
// mLastLocation = currentLocation;
if (currentLocation != null && isGeoFenceAdded == false)
{
if (mUpdateGeoFence) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient
, getGeofencePendingIntent()).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
//if old geoFence's remove successfully then add new ones.
addGeoFences(currentLocation);
}
}
});
}
} else {
addGeoFences(currentLocation);
}
}
else if(isGeoFenceAdded && mRemoveAllGeoFence ){
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
{
LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient
, mGeofencePendingIntent).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
mRemoveAllGeoFence = false;
isGeoFenceAdded = false;
//if old geoFence's remove successfully then do nothing.
stopLocationUpdate();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
}
});
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdate();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
private void startLocationUpdates(final Context mContext) {
if (ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// mLastLocation = FusedLocationApi.getLastLocation(mGoogleApiClient);
PendingResult<Status> pendingResult = FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
pendingResult.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
//update it's code too.
if (status.isSuccess()) {
Toast.makeText(mContext, "location Update Started",
Toast.LENGTH_SHORT).show();
} else if (status.hasResolution()) {
Toast.makeText(mContext, "Open intent to resolve",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void stopLocationUpdate() {
//three types of constructor ..
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
public void addGeoFences(Location currentLocation) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
try {
if (getGeofencingRequest(currentLocation) != null) {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
// The GeofenceRequest object.
getGeofencingRequest(currentLocation),
// A pending intent that that is reused when calling removeGeofences(). This
// pending intent is used to generate an intent when a matched geofence
// transition is observed.
getGeofencePendingIntent()
//).await(TimeOut,TimeUnit.Miilisecponds);
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Toast.makeText(mContext, "Geo Fence Added", Toast.LENGTH_SHORT).show();
isGeoFenceAdded = true;
mRemoveAllGeoFence = false;
mUpdateGeoFence = false;
/// FIXME: 3/2/2017 I didn't have to draw it.
///broadcastDrawGeoFenceOnMap();
} else {
String errorMessage = getErrorString(mContext, status.getStatusCode());
Toast.makeText(mContext, "Status Failed", Toast.LENGTH_SHORT).show();
}
}
}); // Result processed in onResult().
}
} catch (SecurityException securityException) {
securityException.printStackTrace();
// Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
//logSecurityException(securityException);
}
}
}
private PendingIntent getGeofencePendingIntent() {
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
// Reuse the PendingIntent if we already have it.
/// FIXME: 2/9/2017 Update the below class with a receiever..
Intent intent = new Intent(mContext, GeofenceReceiver.class);///GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
// addGeofences() and removeGeofences().
/// FIXME: 3/1/2017 It must be reciever not IntentService
mGeofencePendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
private GeofencingRequest getGeofencingRequest(Location mCurrentLocation) {
/// FIXME: 2/13/2017 mLastLocation can be null because it will take time for the first time.
/// this request should be called after first mLastLocation has been fetched..
GeofencingRequest geofencingRequest = null;
if (mCurrentLocation != null) {
List<SimpleGeofence> simpleFenceList = SimpleGeofenceStore
.getInstance().getLatestGeoFences(mCurrentLocation);
simpleFenceList.add(new SimpleGeofence("currentLocation",
mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(),
100f, GEOFENCE_EXPIRATION_IN_MILLISECONDS,
Geofence.GEOFENCE_TRANSITION_EXIT));
ListSharedPref.saveAnyTypeOfList(ListSharedPref.GEO_FENCE_LIST_KEY, simpleFenceList);
GeofencingRequest.Builder geofencingRequestBuilder = new GeofencingRequest.Builder();
geofencingRequestBuilder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
for (SimpleGeofence simpleGeofence : simpleFenceList)
geofencingRequestBuilder.addGeofence(simpleGeofence.toGeofence());
geofencingRequest = geofencingRequestBuilder.build();
}
// Return a GeofencingRequest.
return geofencingRequest;
}
}
GeofenceReceiver
public class GeofenceReceiver extends IntentService {
public static final int NOTIFICATION_ID = 1;
public GeofenceReceiver() {
super("GeofenceReceiver");
}
#Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);
Location triggredLocation = geoEvent.getTriggeringLocation();
if (geoEvent.hasError()) {
Log.d(HomeActivity.TAG, "Error GeofenceReceiver.onHandleIntent");
} else {
Log.d(HomeActivity.TAG, "GeofenceReceiver : Transition -> "
+ geoEvent.getGeofenceTransition());
int transitionType = geoEvent.getGeofenceTransition();
if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER
|| transitionType == Geofence.GEOFENCE_TRANSITION_DWELL
|| transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
List<Geofence> triggerList = geoEvent.getTriggeringGeofences();
//if(triggerList.g)
Type listType = new TypeToken<ArrayList<SimpleGeofence>>(){}.getType();
List<SimpleGeofence> geoFenceList = GenericPref.readAnyTypeOfList(GenericPref.GEO_FENCE_LIST_KEY,listType);
for (Geofence geofence : triggerList)
{
/*SimpleGeofence sg = SimpleGeofenceStore.getInstance()
.getSimpleGeofences().get(geofence.getRequestId());*/
SimpleGeofence sg = null;
for(SimpleGeofence simpleGeofence : geoFenceList){
if(simpleGeofence.getId().equalsIgnoreCase(geofence.getRequestId())){
sg = simpleGeofence;
break;
}
}
String transitionName = "";
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_DWELL:
transitionName = "dwell";
break;
case Geofence.GEOFENCE_TRANSITION_ENTER:
transitionName = "enter";
String date = DateFormat.format("yyyy-MM-dd hh:mm:ss",
new Date()).toString();
EventDataSource eds = new EventDataSource(
getApplicationContext());
eds.create(transitionName, date, geofence.getRequestId());
eds.close();
GeofenceNotification geofenceNotification = new GeofenceNotification(
this);
if(sg != null){
geofenceNotification
.displayNotification(sg, transitionType);
}
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
transitionName = "exit";
broadcastUpdateGeoFences();
//update your List
// Unregister all geoFences and reRegister it again
break;
}
}
}
}
}
public void broadcastUpdateGeoFences() {
//// FIXME: 3/2/2017 what if app is closed
HomeActivity.geofencesAlreadyRegistered = false;
MainActivity.isGeoFenceAdded = false;
Intent intent = new Intent(Constants.RECEIVER_GEOFENCE);
intent.putExtra("done", 1);
sendBroadcast(intent);
}
}