class NotificationManagerCompat is missing classes - java

I clicked on the class NotificationManagerCompat and I cannot find the public methods
areNotificationsEnabled()
getImportance()
They are also both the only methods that return variables. I need to use the method areNotificationsEnabled() does anyone have any ideas how this could be possible?
Currently my import line is as follows
import android.support.v4.app.NotificationManagerCompat;
Not sure if it helps for me to post the entire class but here it is
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings;
import android.util.Log;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Compatibility library for NotificationManager with fallbacks for older platforms.
*
* <p>To use this class, call the static function {#link #from} to get a
* {#link NotificationManagerCompat} object, and then call one of its
* methods to post or cancel notifications.
*/
public class NotificationManagerCompat {
private static final String TAG = "NotifManCompat";
/**
* Notification extras key: if set to true, the posted notification should use
* the side channel for delivery instead of using notification manager.
*/
public static final String EXTRA_USE_SIDE_CHANNEL =
NotificationCompatJellybean.EXTRA_USE_SIDE_CHANNEL;
/**
* Intent action to register for on a service to receive side channel
* notifications. The listening service must be in the same package as an enabled
* {#link android.service.notification.NotificationListenerService}.
*/
public static final String ACTION_BIND_SIDE_CHANNEL =
"android.support.BIND_NOTIFICATION_SIDE_CHANNEL";
/**
* Maximum sdk build version which needs support for side channeled notifications.
* Currently the only needed use is for side channeling group children before KITKAT_WATCH.
*/
static final int MAX_SIDE_CHANNEL_SDK_VERSION = 19;
/** Base time delay for a side channel listener queue retry. */
private static final int SIDE_CHANNEL_RETRY_BASE_INTERVAL_MS = 1000;
/** Maximum retries for a side channel listener before dropping tasks. */
private static final int SIDE_CHANNEL_RETRY_MAX_COUNT = 6;
/** Hidden field Settings.Secure.ENABLED_NOTIFICATION_LISTENERS */
private static final String SETTING_ENABLED_NOTIFICATION_LISTENERS =
"enabled_notification_listeners";
private static final int SIDE_CHANNEL_BIND_FLAGS;
/** Cache of enabled notification listener components */
private static final Object sEnabledNotificationListenersLock = new Object();
/** Guarded by {#link #sEnabledNotificationListenersLock} */
private static String sEnabledNotificationListeners;
/** Guarded by {#link #sEnabledNotificationListenersLock} */
private static Set<String> sEnabledNotificationListenerPackages = new HashSet<String>();
private final Context mContext;
private final NotificationManager mNotificationManager;
/** Lock for mutable static fields */
private static final Object sLock = new Object();
/** Guarded by {#link #sLock} */
private static SideChannelManager sSideChannelManager;
/** Get a {#link NotificationManagerCompat} instance for a provided context. */
public static NotificationManagerCompat from(Context context) {
return new NotificationManagerCompat(context);
}
private NotificationManagerCompat(Context context) {
mContext = context;
mNotificationManager = (NotificationManager) mContext.getSystemService(
Context.NOTIFICATION_SERVICE);
}
private static final Impl IMPL;
interface Impl {
void cancelNotification(NotificationManager notificationManager, String tag, int id);
void postNotification(NotificationManager notificationManager, String tag, int id,
Notification notification);
int getSideChannelBindFlags();
}
static class ImplBase implements Impl {
#Override
public void cancelNotification(NotificationManager notificationManager, String tag,
int id) {
notificationManager.cancel(id);
}
#Override
public void postNotification(NotificationManager notificationManager, String tag, int id,
Notification notification) {
notificationManager.notify(id, notification);
}
#Override
public int getSideChannelBindFlags() {
return Service.BIND_AUTO_CREATE;
}
}
static class ImplEclair extends ImplBase {
#Override
public void cancelNotification(NotificationManager notificationManager, String tag,
int id) {
NotificationManagerCompatEclair.cancelNotification(notificationManager, tag, id);
}
#Override
public void postNotification(NotificationManager notificationManager, String tag, int id,
Notification notification) {
NotificationManagerCompatEclair.postNotification(notificationManager, tag, id,
notification);
}
}
static class ImplIceCreamSandwich extends ImplEclair {
#Override
public int getSideChannelBindFlags() {
return NotificationManagerCompatIceCreamSandwich.SIDE_CHANNEL_BIND_FLAGS;
}
}
static {
if (Build.VERSION.SDK_INT >= 14) {
IMPL = new ImplIceCreamSandwich();
} else if (Build.VERSION.SDK_INT >= 5) {
IMPL = new ImplEclair();
} else {
IMPL = new ImplBase();
}
SIDE_CHANNEL_BIND_FLAGS = IMPL.getSideChannelBindFlags();
}
/**
* Cancel a previously shown notification.
* #param id the ID of the notification
*/
public void cancel(int id) {
cancel(null, id);
}
/**
* Cancel a previously shown notification.
* #param tag the string identifier of the notification.
* #param id the ID of the notification
*/
public void cancel(String tag, int id) {
IMPL.cancelNotification(mNotificationManager, tag, id);
if (Build.VERSION.SDK_INT <= MAX_SIDE_CHANNEL_SDK_VERSION) {
pushSideChannelQueue(new CancelTask(mContext.getPackageName(), id, tag));
}
}
/** Cancel all previously shown notifications. */
public void cancelAll() {
mNotificationManager.cancelAll();
if (Build.VERSION.SDK_INT <= MAX_SIDE_CHANNEL_SDK_VERSION) {
pushSideChannelQueue(new CancelTask(mContext.getPackageName()));
}
}
/**
* Post a notification to be shown in the status bar, stream, etc.
* #param id the ID of the notification
* #param notification the notification to post to the system
*/
public void notify(int id, Notification notification) {
notify(null, id, notification);
}
/**
* Post a notification to be shown in the status bar, stream, etc.
* #param tag the string identifier for a notification. Can be {#code null}.
* #param id the ID of the notification. The pair (tag, id) must be unique within your app.
* #param notification the notification to post to the system
*/
public void notify(String tag, int id, Notification notification) {
if (useSideChannelForNotification(notification)) {
pushSideChannelQueue(new NotifyTask(mContext.getPackageName(), id, tag, notification));
// Cancel this notification in notification manager if it just transitioned to being
// side channelled.
IMPL.cancelNotification(mNotificationManager, tag, id);
} else {
IMPL.postNotification(mNotificationManager, tag, id, notification);
}
}
/**
* Get the set of packages that have an enabled notification listener component within them.
*/
public static Set<String> getEnabledListenerPackages(Context context) {
final String enabledNotificationListeners = Settings.Secure.getString(
context.getContentResolver(),
SETTING_ENABLED_NOTIFICATION_LISTENERS);
// Parse the string again if it is different from the last time this method was called.
if (enabledNotificationListeners != null
&& !enabledNotificationListeners.equals(sEnabledNotificationListeners)) {
final String[] components = enabledNotificationListeners.split(":");
Set<String> packageNames = new HashSet<String>(components.length);
for (String component : components) {
ComponentName componentName = ComponentName.unflattenFromString(component);
if (componentName != null) {
packageNames.add(componentName.getPackageName());
}
}
synchronized (sEnabledNotificationListenersLock) {
sEnabledNotificationListenerPackages = packageNames;
sEnabledNotificationListeners = enabledNotificationListeners;
}
}
return sEnabledNotificationListenerPackages;
}
/**
* Returns true if this notification should use the side channel for delivery.
*/
private static boolean useSideChannelForNotification(Notification notification) {
Bundle extras = NotificationCompat.getExtras(notification);
return extras != null && extras.getBoolean(EXTRA_USE_SIDE_CHANNEL);
}
/**
* Push a notification task for distribution to notification side channels.
*/
private void pushSideChannelQueue(Task task) {
synchronized (sLock) {
if (sSideChannelManager == null) {
sSideChannelManager = new SideChannelManager(mContext.getApplicationContext());
}
}
sSideChannelManager.queueTask(task);
}
/**
* Helper class to manage a queue of pending tasks to send to notification side channel
* listeners.
*/
private static class SideChannelManager implements Handler.Callback, ServiceConnection {
private static final int MSG_QUEUE_TASK = 0;
private static final int MSG_SERVICE_CONNECTED = 1;
private static final int MSG_SERVICE_DISCONNECTED = 2;
private static final int MSG_RETRY_LISTENER_QUEUE = 3;
private static final String KEY_BINDER = "binder";
private final Context mContext;
private final HandlerThread mHandlerThread;
private final Handler mHandler;
private final Map<ComponentName, ListenerRecord> mRecordMap =
new HashMap<ComponentName, ListenerRecord>();
private Set<String> mCachedEnabledPackages = new HashSet<String>();
public SideChannelManager(Context context) {
mContext = context;
mHandlerThread = new HandlerThread("NotificationManagerCompat");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper(), this);
}
/**
* Queue a new task to be sent to all listeners. This function can be called
* from any thread.
*/
public void queueTask(Task task) {
mHandler.obtainMessage(MSG_QUEUE_TASK, task).sendToTarget();
}
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_QUEUE_TASK:
handleQueueTask((Task) msg.obj);
return true;
case MSG_SERVICE_CONNECTED:
ServiceConnectedEvent event = (ServiceConnectedEvent) msg.obj;
handleServiceConnected(event.componentName, event.iBinder);
return true;
case MSG_SERVICE_DISCONNECTED:
handleServiceDisconnected((ComponentName) msg.obj);
return true;
case MSG_RETRY_LISTENER_QUEUE:
handleRetryListenerQueue((ComponentName) msg.obj);
return true;
}
return false;
}
private void handleQueueTask(Task task) {
updateListenerMap();
for (ListenerRecord record : mRecordMap.values()) {
record.taskQueue.add(task);
processListenerQueue(record);
}
}
private void handleServiceConnected(ComponentName componentName, IBinder iBinder) {
ListenerRecord record = mRecordMap.get(componentName);
if (record != null) {
record.service = INotificationSideChannel.Stub.asInterface(iBinder);
record.retryCount = 0;
processListenerQueue(record);
}
}
private void handleServiceDisconnected(ComponentName componentName) {
ListenerRecord record = mRecordMap.get(componentName);
if (record != null) {
ensureServiceUnbound(record);
}
}
private void handleRetryListenerQueue(ComponentName componentName) {
ListenerRecord record = mRecordMap.get(componentName);
if (record != null) {
processListenerQueue(record);
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Connected to service " + componentName);
}
mHandler.obtainMessage(MSG_SERVICE_CONNECTED,
new ServiceConnectedEvent(componentName, iBinder))
.sendToTarget();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Disconnected from service " + componentName);
}
mHandler.obtainMessage(MSG_SERVICE_DISCONNECTED, componentName).sendToTarget();
}
/**
* Check the current list of enabled listener packages and update the records map
* accordingly.
*/
private void updateListenerMap() {
Set<String> enabledPackages = getEnabledListenerPackages(mContext);
if (enabledPackages.equals(mCachedEnabledPackages)) {
// Short-circuit when the list of enabled packages has not changed.
return;
}
mCachedEnabledPackages = enabledPackages;
List<ResolveInfo> resolveInfos = mContext.getPackageManager().queryIntentServices(
new Intent().setAction(ACTION_BIND_SIDE_CHANNEL), PackageManager.GET_SERVICES);
Set<ComponentName> enabledComponents = new HashSet<ComponentName>();
for (ResolveInfo resolveInfo : resolveInfos) {
if (!enabledPackages.contains(resolveInfo.serviceInfo.packageName)) {
continue;
}
ComponentName componentName = new ComponentName(
resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
if (resolveInfo.serviceInfo.permission != null) {
Log.w(TAG, "Permission present on component " + componentName
+ ", not adding listener record.");
continue;
}
enabledComponents.add(componentName);
}
// Ensure all enabled components have a record in the listener map.
for (ComponentName componentName : enabledComponents) {
if (!mRecordMap.containsKey(componentName)) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Adding listener record for " + componentName);
}
mRecordMap.put(componentName, new ListenerRecord(componentName));
}
}
// Remove listener records that are no longer for enabled components.
Iterator<Map.Entry<ComponentName, ListenerRecord>> it =
mRecordMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<ComponentName, ListenerRecord> entry = it.next();
if (!enabledComponents.contains(entry.getKey())) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Removing listener record for " + entry.getKey());
}
ensureServiceUnbound(entry.getValue());
it.remove();
}
}
}
/**
* Ensure we are already attempting to bind to a service, or start a new binding if not.
* #return Whether the service bind attempt was successful.
*/
private boolean ensureServiceBound(ListenerRecord record) {
if (record.bound) {
return true;
}
Intent intent = new Intent(ACTION_BIND_SIDE_CHANNEL).setComponent(record.componentName);
record.bound = mContext.bindService(intent, this, SIDE_CHANNEL_BIND_FLAGS);
if (record.bound) {
record.retryCount = 0;
} else {
Log.w(TAG, "Unable to bind to listener " + record.componentName);
mContext.unbindService(this);
}
return record.bound;
}
/**
* Ensure we have unbound from a service.
*/
private void ensureServiceUnbound(ListenerRecord record) {
if (record.bound) {
mContext.unbindService(this);
record.bound = false;
}
record.service = null;
}
/**
* Schedule a delayed retry to communicate with a listener service.
* After a maximum number of attempts (with exponential back-off), start
* dropping pending tasks for this listener.
*/
private void scheduleListenerRetry(ListenerRecord record) {
if (mHandler.hasMessages(MSG_RETRY_LISTENER_QUEUE, record.componentName)) {
return;
}
record.retryCount++;
if (record.retryCount > SIDE_CHANNEL_RETRY_MAX_COUNT) {
Log.w(TAG, "Giving up on delivering " + record.taskQueue.size() + " tasks to "
+ record.componentName + " after " + record.retryCount + " retries");
record.taskQueue.clear();
return;
}
int delayMs = SIDE_CHANNEL_RETRY_BASE_INTERVAL_MS * (1 << (record.retryCount - 1));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Scheduling retry for " + delayMs + " ms");
}
Message msg = mHandler.obtainMessage(MSG_RETRY_LISTENER_QUEUE, record.componentName);
mHandler.sendMessageDelayed(msg, delayMs);
}
/**
* Perform a processing step for a listener. First check the bind state, then attempt
* to flush the task queue, and if an error is encountered, schedule a retry.
*/
private void processListenerQueue(ListenerRecord record) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Processing component " + record.componentName + ", "
+ record.taskQueue.size() + " queued tasks");
}
if (record.taskQueue.isEmpty()) {
return;
}
if (!ensureServiceBound(record) || record.service == null) {
// Ensure bind has started and that a service interface is ready to use.
scheduleListenerRetry(record);
return;
}
// Attempt to flush all items in the task queue.
while (true) {
Task task = record.taskQueue.peek();
if (task == null) {
break;
}
try {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Sending task " + task);
}
task.send(record.service);
record.taskQueue.remove();
} catch (DeadObjectException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Remote service has died: " + record.componentName);
}
break;
} catch (RemoteException e) {
Log.w(TAG, "RemoteException communicating with " + record.componentName, e);
break;
}
}
if (!record.taskQueue.isEmpty()) {
// Some tasks were not sent, meaning an error was encountered, schedule a retry.
scheduleListenerRetry(record);
}
}
/** A per-side-channel-service listener state record */
private static class ListenerRecord {
public final ComponentName componentName;
/** Whether the service is currently bound to. */
public boolean bound = false;
/** The service stub provided by onServiceConnected */
public INotificationSideChannel service;
/** Queue of pending tasks to send to this listener service */
public LinkedList<Task> taskQueue = new LinkedList<Task>();
/** Number of retries attempted while connecting to this listener service */
public int retryCount = 0;
public ListenerRecord(ComponentName componentName) {
this.componentName = componentName;
}
}
}
private static class ServiceConnectedEvent {
final ComponentName componentName;
final IBinder iBinder;
public ServiceConnectedEvent(ComponentName componentName,
final IBinder iBinder) {
this.componentName = componentName;
this.iBinder = iBinder;
}
}
private interface Task {
public void send(INotificationSideChannel service) throws RemoteException;
}
private static class NotifyTask implements Task {
final String packageName;
final int id;
final String tag;
final Notification notif;
public NotifyTask(String packageName, int id, String tag, Notification notif) {
this.packageName = packageName;
this.id = id;
this.tag = tag;
this.notif = notif;
}
#Override
public void send(INotificationSideChannel service) throws RemoteException {
service.notify(packageName, id, tag, notif);
}
public String toString() {
StringBuilder sb = new StringBuilder("NotifyTask[");
sb.append("packageName:").append(packageName);
sb.append(", id:").append(id);
sb.append(", tag:").append(tag);
sb.append("]");
return sb.toString();
}
}
private static class CancelTask implements Task {
final String packageName;
final int id;
final String tag;
final boolean all;
public CancelTask(String packageName) {
this.packageName = packageName;
this.id = 0;
this.tag = null;
this.all = true;
}
public CancelTask(String packageName, int id, String tag) {
this.packageName = packageName;
this.id = id;
this.tag = tag;
this.all = false;
}
#Override
public void send(INotificationSideChannel service) throws RemoteException {
if (all) {
service.cancelAll(packageName);
} else {
service.cancel(packageName, id, tag);
}
}
public String toString() {
StringBuilder sb = new StringBuilder("CancelTask[");
sb.append("packageName:").append(packageName);
sb.append(", id:").append(id);
sb.append(", tag:").append(tag);
sb.append(", all:").append(all);
sb.append("]");
return sb.toString();
}
}
}

Related

Agora.io in Native Android (Java)

I know that this questions was asked before but it doesn't solved by queries mentioned below after the code .
package io.agora.tutorials1v1vcall;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import io.agora.uikit.logger.LoggerRecyclerView;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
public class VideoChatViewActivity extends AppCompatActivity {
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,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mRemoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
private LoggerRecyclerView mLogView;
/**
* Event handler registered into RTC engine for RTC callbacks.
* Note that UI operations needs to be in UI thread because RTC
* engine deals with the events in a separate thread.
*/
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 onFirstRemoteVideoDecoded(final int uid, int width, int height, 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();
}
});
}
};
private void setupRemoteVideo(int uid) {
// Only one remote video view is available for this
// tutorial. Here we check if there exists a surface
// view tagged as this uid.
int count = mRemoteContainer.getChildCount();
View view = null;
for (int i = 0; i < count; i++) {
View v = mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int) v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mRemoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mRemoteView);
mRtcEngine.setupRemoteVideo(new VideoCanvas(mRemoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mRemoteView.setTag(uid);
}
private void onRemoteUserLeft() {
removeRemoteVideo();
}
private void removeRemoteVideo() {
if (mRemoteView != null) {
mRemoteContainer.removeView(mRemoteView);
}
mRemoteView = null;
}
#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) &&
checkSelfPermission(REQUESTED_PERMISSIONS[2], 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 + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
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() {
// This is our usual steps for joining
// a channel and starting a call.
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() {
// In simple use cases, we only need to enable video capturing
// and rendering once at the initialization step.
// Note: audio recording and playing is enabled by default.
mRtcEngine.enableVideo();
// Please go to this page for detailed explanation
// https://docs.agora.io/en/Video/API%20Reference/java/classio_1_1agora_1_1rtc_1_1_rtc_engine.html#af5f4de754e2c1f493096641c5c5c1d8f
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() {
// This is used to set a local preview.
// The steps setting local and remote view are very similar.
// But note that if the local user do not have a uid or do
// not care what the uid is, he can set his uid as ZERO.
// Our server will assign one and return the uid via the event
// handler callback function (onJoinChannelSuccess) after
// joining the channel successfully.
mLocalView = RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
mRtcEngine.setupLocalVideo(new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
}
private void joinChannel() {
// 1. Users can only see each other after they join the
// same channel successfully using the same app id.
// 2. One token is only valid for the channel name that
// you use to generate this token.
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, "demoChannel1", "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() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
}
I am integrating the agora.io for one-to-one video calling functionality. I got the above code from the agora.io documentation but i am getting the black remote screen . Also i would ask that how would i connect two users dynamically. What modifications i have to do in the above code for one-to-one video call functionality. Please help.Thanks in advance.
It showing black screen because of token issue. kindly check token generation code in backend. Most probably the reason for black screen is the token expiration time.

Unable to fix when mocking location on Android

I'm trying to mock the GPS location in my app but as soon as I set mocked location, any app using the google play services is unable to get the location of the device, whether it's the real one or the mocked one.
For instance, if I open Google Map and try to go to my location, i'll get the message
waiting for the location
and nothing will happen. That's the same in my app, the location is never found
my code is the following:
public class MockLocationService {
protected Context context;
// Define a LocationClient object
public LocationClient mLocationClient;
// provider of fake locations
private static final String PROVIDER = "flp";
// TAG for the logs
protected static final String TAG = "MockLocationService";
// intens for states
public static final String MOCK_LOCATION_SERVICE_CONNECTED = "CONNECTED";
public static final String MOCK_LOCATION_SERVICE_DECONNECTED = "DECONNECTED";
public static final String MOCK_LOCATION_SERVICE_FAILED = "FAILED";
public static final String MOCK_LOCATION_SERVICE_SETTING_NOT_ENABLED = "SETTING_NOT_ENABLED";
// current mockLocation
protected static Location currentMockLocation;
public MockLocationService(Context context) {
this.context = context;
// connect to the Google play services
mLocationClient = new LocationClient(context, connectionCallbacks,
onConnectionFailedListener);
}
/**
* Connect to the API to enable mocking the location
*/
public void connect() {
// Connect to Location Services
// ONLY WHEN CALLBACK IS CALLED, ACT
mLocationClient.connect();
}
/**
* Disconnect from the API, stops mocking the location
*/
public void disconnect() {
// terminate aTask
aTask.cancel(true);
currentMockLocation=null;
// disconnect
mLocationClient.disconnect();
}
/**
* Sets the location from a LocationMessage object as the device current
* location
*
* #param location
*/
public void setLocation(LocationMessage location) {
if (location.getLat() == null || location.getLng() == null
|| location.getAccuracy() == null)
return;
Location newLocation = new Location(PROVIDER);
newLocation.setLatitude(location.getLat());
newLocation.setLongitude(location.getLng());
newLocation.setAccuracy(1);
newLocation.setTime(System.currentTimeMillis());
newLocation.setBearing(0F);
newLocation.setAltitude(0F);
// set it as a mocked location
this.setMockLocation(newLocation);
// Create a new Location
Log.d(TAG,
"New mocked location: lat: " + location.getLat() + " - lng: "
+ location.getLng() + " - accuracy: "
+ location.getAccuracy());
}
/**
* Sets a Location object as the location for the device
*
* #param mockLocation
* the mocked Location object
*/
protected void setMockLocation(Location mockLocation) {
if (!mLocationClient.isConnected())
return;
currentMockLocation = mockLocation;
if (currentMockLocation==null) {
aTask.execute((Void) null);
}
}
// asynchronously send the mock location every second (for GPS)
final RestAsyncTask<Boolean[]> aTask = new RestAsyncTask<Boolean[]>() {
// executes on background thread
#Override
protected Boolean[] doInBackground(Void... lists) {
// set mock location
do {
mLocationClient.setMockLocation(currentMockLocation);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
#Override
protected void onPostExecute(Boolean[] result) {
return;
}
};
/**
* When connect/unconnect from the location client
*/
protected ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks() {
#Override
public void onDisconnected() {
sendIntent(MOCK_LOCATION_SERVICE_DECONNECTED);
}
#Override
public void onConnected(Bundle arg0) {
sendIntent(MOCK_LOCATION_SERVICE_CONNECTED);
// When the location client is connected, set mock mode
try {
mLocationClient.setMockMode(true);
} catch (Exception e) {
sendIntent(MOCK_LOCATION_SERVICE_SETTING_NOT_ENABLED);
}
}
};
/**
* When connection failed to the location client
*/
protected OnConnectionFailedListener onConnectionFailedListener = new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult arg0) {
sendIntent(MOCK_LOCATION_SERVICE_FAILED);
}
};
/**
* Send an intent with the correct type
*
* #param action
* : the action parameter of the intent
*/
protected static void sendIntent(String action) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(action);
LocalBroadcastManager.getInstance(PEApplication.getInstance())
.sendBroadcast(broadcastIntent);
}
}
am I missing something?
thanks!

Getting current value with Android Bluetooth LE Sample App

This is probably really straightforward, but I am new to Android and Bluetooth, and this has me lost.
I'm using the sample BluetoothLEGatt app as a starting point
http://developer.android.com/samples/BluetoothLeGatt/index.html
This allows you to select various characteristics from the connected Bluetooth LE device from an expandable list. Upon selecting the characteristic, the value is displayed in mDataField. I would like to just automatically display the heart rate measurement in the mDataField, without first having to select anything in the menu, but I can't figure out how the servicesListClickListner piece works.
Below is the DeviceControlActivity.java, which is the main screen
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.bluetooth.le;
import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* For a given BLE device, this Activity provides the user interface to connect, display data,
* and display GATT services and characteristics supported by the device. The Activity
* communicates with {#code BluetoothLeService}, which in turn interacts with the
* Bluetooth LE API.
*/
public class DeviceControlActivity extends Activity {
private final static String TAG = DeviceControlActivity.class.getSimpleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
// If a given GATT characteristic is selected, check for supported features. This sample
// demonstrates 'Read' and 'Notify' features. See
// http://d.android.com/reference/android/bluetooth/BluetoothGatt.html for the complete
// list of supported characteristic features.
private final ExpandableListView.OnChildClickListener servicesListClickListner =
new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
if (mGattCharacteristics != null) {
final BluetoothGattCharacteristic characteristic =
mGattCharacteristics.get(groupPosition).get(childPosition);
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
// If there is an active notification on a characteristic, clear
// it first so it doesn't update the data field on the user interface.
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mNotifyCharacteristic = characteristic;
mBluetoothLeService.setCharacteristicNotification(
characteristic, true);
}
return true;
}
return false;
}
};
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gatt_services_characteristics);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
// Sets up UI references.
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
mGattServicesList = (ExpandableListView) findViewById(R.id.gatt_services_list);
mGattServicesList.setOnChildClickListener(servicesListClickListner);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mDataField = (TextView) findViewById(R.id.data_value);
getActionBar().setTitle(mDeviceName);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_services, menu);
if (mConnected) {
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_connect:
mBluetoothLeService.connect(mDeviceAddress);
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
// Demonstrates how to iterate through the supported GATT Services/Characteristics.
// In this sample, we populate the data structure that is bound to the ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
= new ArrayList<ArrayList<HashMap<String, String>>>();
mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<String, String>();
uuid = gattService.getUuid().toString();
currentServiceData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas =
new ArrayList<BluetoothGattCharacteristic>();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<String, String>();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
this,
gattServiceData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 },
gattCharacteristicData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 }
);
mGattServicesList.setAdapter(gattServiceAdapter);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
}
And below is BluetoothLeService
package com.example.bluetooth.le;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.UUID;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
public final static UUID UUID_HEART_RATE_MEASUREMENT =
UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG, "Heart rate format UINT8.");
}
final int heartRate = characteristic.getIntValue(format, 1);
Log.d(TAG, String.format("Received heart rate: %d", heartRate));
intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
} else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
}
}
sendBroadcast(intent);
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* #return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* #param address The device address of the destination device.
*
* #return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {#code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {#code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {#code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* #param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
/**
* Enables or disables notification on a give characteristic.
*
* #param characteristic Characteristic to act on.
* #param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// This is specific to Heart Rate Measurement.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {#code BluetoothGatt#discoverServices()} completes successfully.
*
* #return A {#code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
}
The displayGattServices method populates your ExpandableListView with possible services. So you could just select the service that you want in this for loop:
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
if (uuid.equals("THE NAME OF THE SERVICE THAT I WANT") {
// and then call
mBluetoothLeService.setCharacteristicNotification(characteristic, true);
}
}
And then modify the displayData method if you need to.
The line:
int flag = characteristic.getProperties();
in the sample code is expected to return the bit mask for the supported characteristic fields. It doesn't. It returns the characteristic properties, like PROPERTY_NOTIFY.
To get the bit mask for the supported characteristic fields, in the case of the example's Heart Rate Measurement characteristic, the first value of the characteristic needs to be read and used.
Thus replacing the line
int flag = characteristic.getProperties();
with something like
byte[] charValue = characteristic.getValue();
byte flag = charValue[0];
will work correctly.

Alternative to zxing QR reader library for Java/Android? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Is there any other library other than Zxing that can be used to create a QR code reader EVEN IF IT'S NOT FREE.
of-course a free one will be great. but I'm also willing to pay to get a library that's easy in customization and to save time.
thank you.
I've found the answer for my question here http://sourceforge.net/news/?group_id=189236
it's much faster than zxing and much easier to implement.
Thank you.
For iOS:
for iOS (zbar.sourceforge.net/iphone) and the documentation (zbar.sourceforge.net/iphone/sdkdoc/install.html)
there are no need to install zxing for implementing qr reader, Just create a class IntentIntegrator.java and IntentResult.java file and call from your activity.
Here is the source code for this....
Checkout full source code here
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;
public final class IntentIntegrator {
public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits
private static final String TAG = IntentIntegrator.class.getSimpleName();
public static final String DEFAULT_TITLE = "Install Barcode Scanner?";
public static final String DEFAULT_MESSAGE =
"This application requires Barcode Scanner. Would you like to install it?";
public static final String DEFAULT_YES = "Yes";
public static final String DEFAULT_NO = "No";
private static final String BS_PACKAGE = "com.google.zxing.client.android";
// supported barcode formats
public static final Collection<String> PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14");
public static final Collection<String> ONE_D_CODE_TYPES =
list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128",
"ITF", "RSS_14", "RSS_EXPANDED");
public static final Collection<String> QR_CODE_TYPES = Collections.singleton("QR_CODE");
public static final Collection<String> DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX");
public static final Collection<String> ALL_CODE_TYPES = null;
public static final Collection<String> TARGET_BARCODE_SCANNER_ONLY = Collections.singleton(BS_PACKAGE);
public static final Collection<String> TARGET_ALL_KNOWN = list(
BS_PACKAGE, // Barcode Scanner
"com.srowen.bs.android", // Barcode Scanner+
"com.srowen.bs.android.simple" // Barcode Scanner+ Simple
// TODO add more -- what else supports this intent?
);
private final Activity activity;
private String title;
private String message;
private String buttonYes;
private String buttonNo;
private Collection<String> targetApplications;
public IntentIntegrator(Activity activity) {
this.activity = activity;
title = DEFAULT_TITLE;
message = DEFAULT_MESSAGE;
buttonYes = DEFAULT_YES;
buttonNo = DEFAULT_NO;
targetApplications = TARGET_ALL_KNOWN;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitleByID(int titleID) {
title = activity.getString(titleID);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessageByID(int messageID) {
message = activity.getString(messageID);
}
public String getButtonYes() {
return buttonYes;
}
public void setButtonYes(String buttonYes) {
this.buttonYes = buttonYes;
}
public void setButtonYesByID(int buttonYesID) {
buttonYes = activity.getString(buttonYesID);
}
public String getButtonNo() {
return buttonNo;
}
public void setButtonNo(String buttonNo) {
this.buttonNo = buttonNo;
}
public void setButtonNoByID(int buttonNoID) {
buttonNo = activity.getString(buttonNoID);
}
public Collection<String> getTargetApplications() {
return targetApplications;
}
public void setTargetApplications(Collection<String> targetApplications) {
this.targetApplications = targetApplications;
}
public void setSingleTargetApplication(String targetApplication) {
this.targetApplications = Collections.singleton(targetApplication);
}
/**
* Initiates a scan for all known barcode types.
*/
public AlertDialog initiateScan() {
return initiateScan(ALL_CODE_TYPES);
}
/**
* Initiates a scan only for a certain set of barcode types, given as strings corresponding
* to their names in ZXing's {#code BarcodeFormat} class like "UPC_A". You can supply constants
* like {#link #PRODUCT_CODE_TYPES} for example.
*/
public AlertDialog initiateScan(Collection<String> desiredBarcodeFormats) {
Intent intentScan = new Intent(BS_PACKAGE + ".SCAN");
intentScan.addCategory(Intent.CATEGORY_DEFAULT);
// check which types of codes to scan for
if (desiredBarcodeFormats != null) {
// set the desired barcode types
StringBuilder joinedByComma = new StringBuilder();
for (String format : desiredBarcodeFormats) {
if (joinedByComma.length() > 0) {
joinedByComma.append(',');
}
joinedByComma.append(format);
}
intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString());
}
String targetAppPackage = findTargetAppPackage(intentScan);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intentScan.setPackage(targetAppPackage);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivityForResult(intentScan, REQUEST_CODE);
return null;
}
private String findTargetAppPackage(Intent intent) {
PackageManager pm = activity.getPackageManager();
List<ResolveInfo> availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (availableApps != null) {
for (ResolveInfo availableApp : availableApps) {
String packageName = availableApp.activityInfo.packageName;
if (targetApplications.contains(packageName)) {
return packageName;
}
}
}
return null;
}
private AlertDialog showDownloadDialog() {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://details?id=" + BS_PACKAGE);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
// Hmm, market is not installed
Log.w(TAG, "Android Market is not installed; cannot install Barcode Scanner");
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {}
});
return downloadDialog.show();
}
/**
* <p>Call this from your {#link Activity}'s
* {#link Activity#onActivityResult(int, int, Intent)} method.</p>
*
* #return null if the event handled here was not related to this class, or
* else an {#link IntentResult} containing the result of the scan. If the user cancelled scanning,
* the fields will be null.
*/
public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT");
byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES");
int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE);
Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation;
String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL");
return new IntentResult(contents,
formatName,
rawBytes,
orientation,
errorCorrectionLevel);
}
return new IntentResult();
}
return null;
}
/**
* Shares the given text by encoding it as a barcode, such that another user can
* scan the text off the screen of the device.
*
* #param text the text string to encode as a barcode
*/
public void shareText(CharSequence text) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
showDownloadDialog();
} else {
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
}
private static Collection<String> list(String... values) {
return Collections.unmodifiableCollection(Arrays.asList(values));
}
}
And IntentResult.java for cantaining the info of the selected bar code or qr code.
/**
*
*/
public final class IntentResult {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResult() {
this(null, null, null, null, null);
}
IntentResult(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
/**
* #return raw content of barcode
*/
public String getContents() {
return contents;
}
/**
* #return name of format, like "QR_CODE", "UPC_A". See {#code BarcodeFormat} for more format names.
*/
public String getFormatName() {
return formatName;
}
/**
* #return raw bytes of the barcode content, if applicable, or null otherwise
*/
public byte[] getRawBytes() {
return rawBytes;
}
/**
* #return rotation of the image, in degrees, which resulted in a successful scan. May be null.
*/
public Integer getOrientation() {
return orientation;
}
/**
* #return name of the error correction level used in the barcode, if applicable
*/
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
#Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
now how to call these classes from your Activity
btnScanBarCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
IntentIntegrator integrator = new IntentIntegrator(BarCodeReaderActivity.this);
integrator.initiateScan();
}
});
And in onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
// handle scan result
contantsString = scanResult.getContents()==null?"0":scanResult.getContents();
if (contantsString.equalsIgnoreCase("0")) {
Toast.makeText(this, "Problem to get the contant Number", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this, contantsString, Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(this, "Problem to secan the barcode.", Toast.LENGTH_LONG).show();
}
}
I have the same issue. I downloaded the ZXing library and integrated it into my project. The integration is very hard and junky and I spend a lot of time to clean the project and to used only the QRCode part. Now it works but there is a known issue with some Motorola devices Atrix and DroidX (Android 2.3)where CaptureActivity shows a white screen instead of camera. This is an issue with the library but the guys from ZXing wont fix it. It seems that this issue is also present on Htc Nexus One. This is a post: https://groups.google.com/forum/#!topic/zxing/BofniyFVZaQ.
#Sean
I know you are the founder of ZXing. The Barcode scanner app is great but using it as a library into the application is not. I suggest to decouple the app and the library and to write a good documentation to it. Also I don't understand why you dropeed the support for iOS.

Util Class in Java

I want to know about the util Class used in Java. I am currently working on one Application in Android where I need to used a class from one file to another different file. I was told to import it like import com.android.utli.(ClassName) here the "com.android.util" is a package name.
Can I use that class in my another file simply by importing the package along with the class name?
Yes. After you import the class at the top of your java file like:
import android.util.Log;
You can then use it in your code.
Log.debug("MyActivity", "Thing I want to log");
The package is really a part of the "fully qualified class name". You can actually use that fully qualified name everywhere you use the class name, e.g.
com.android.util.UtilClass myUtil = new com.android.util.UtilClass();
But that's rather inconvenient. Therefore, classes in the same package (and in the package java.lang) can be used shorthand (i.e. only the class name) without imports. Classes from other packages have to be imported before they can be used that way.
It's just a way to organize the code and prevent problems when different programmers write classes with the same name - as long as they are in different packages, the collision can always be resolved by using the fully qualified class name.
public class SelectionListAdapter extends BaseAdapter {
private static final String TAG = SelectionListAdapter.class.getSimpleName();
private static LayoutInflater inflater = null;
// ArrayList<Selection> selections;
ArrayList<MultiSelection> multiselections;
ArrayList<MultiSelection> multiselectionsTemp;
Context mContext;
ArrayList<String> arrSelectedIDs;
ArrayList<String> arrSelectedNames;
String type;
public SelectionListAdapter(Activity ctx, ArrayList<MultiSelection> multiselections, String type) {
mContext = ctx;
inflater = (LayoutInflater) mContext.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.selections = selections;
this.multiselections = multiselections;
this.multiselectionsTemp = new ArrayList<>();
multiselectionsTemp.addAll(multiselections);
arrSelectedIDs = new ArrayList<>();
arrSelectedNames = new ArrayList<>();
this.type = type;
}
public int getCount() {
return multiselections.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.selection_list_row, null);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.txt_item.setText(multiselections.get(i).name);
final MultiSelection multiSelection = multiselections.get(i);
if (multiSelection.isChecked) {
holder.check.setBackgroundResource(R.drawable.chacked);
if (!arrSelectedIDs.contains(multiSelection.id.trim()))
arrSelectedIDs.add(multiSelection.id.trim());
if (!arrSelectedNames.contains(multiSelection.name.trim()))
arrSelectedNames.add(multiSelection.name);
} else {
holder.check.setBackgroundResource(R.drawable.unchacked);
}
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (multiSelection.isChecked) {
holder.check.setBackgroundResource(R.drawable.unchacked);
arrSelectedIDs.remove(multiSelection.id.trim());
arrSelectedNames.remove(multiSelection.name);
if (type != null && type.equals("search")) {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS_SEARCH, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES_SEARCH, arrSelectedNames.toString());
} else {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES, arrSelectedNames.toString());
}
multiSelection.isChecked = false;
} else {
holder.check.setBackgroundResource(R.drawable.chacked);
arrSelectedIDs.add(multiSelection.id.trim());
arrSelectedNames.add(multiSelection.name);
if (type != null && type.equals("search")) {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS_SEARCH, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES_SEARCH, arrSelectedNames.toString());
} else {
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_IDS, arrSelectedIDs.toString());
Util.WriteSharePrefrence(mContext, Constant.SHRED_PR.SELECTED_WTT_NAMES, arrSelectedNames.toString());
}
multiSelection.isChecked = true;
}
}
});
return view;
}
public class ViewHolder {
#InjectView(R.id.txt_item)
TextView txt_item;
#InjectView(R.id.check)
ImageView check;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
multiselections.clear();
if (charText.length() == 0) {
multiselections.addAll(multiselectionsTemp);
} else {
for (MultiSelection wp : multiselectionsTemp) {
if (wp.name.toLowerCase(Locale.getDefault())
.contains(charText)) {
multiselections.add(wp);
}
}
}
notifyDataSetChanged();
}
}
public boolean isChecked;
private SwipeRefreshLayout swipeRefreshLayout;
implements SwipeRefreshLayout.OnRefreshListener
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setProgressBackgroundColor(R.color.colorPrimary);
swipeRefreshLayout.setColorSchemeColors(getActivity().getResources().getColor(R.color.color_white));
// swipeRefreshLayout.post(new Runnable()
// {
// #Override
// public void run()
// {
// swipeRefreshLayout.setRefreshing(true);
// }
// });
swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setRefreshing(false); // not call
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
if (Utils.isInternetConnected(getActivity())) {
getNearbyUserList();
} else {
MDToast mdToast = MDToast.makeText(getActivity(), "Please check the internet connection.",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
**Connection Detector Class**
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
} else {
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
}
return false;
}
public boolean connectionDetected()
{
if (isConnectingToInternet(context)) {
return true;
} else {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.connection_checker);
dialog.setCancelable(false);
dialog.show();
Button ok = (Button) dialog.findViewById(R.id.dialog_ok);
Button cancel = (Button) dialog.findViewById(R.id.dialog_cancel);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
dialog.dismiss();
connectionDetected();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
return false;
}
}
}
**Datetime**
//Click
fromDatePickerDialog.show();
// Defin Oncreat()
private SimpleDateFormat dateFormatter;
dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
setDateTimeField();
private void setDateTimeField()
{
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
startDateTv.setText(dateFormatter.format(newDate.getTime()));
getDateTimeDifference();
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
endDateTv.setText(dateFormatter.format(newDate.getTime()));
getDateTimeDifference();
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
GLIDE_WITH BLUER
Glide.with(mContext)
.load(user.card_image.toString())
.bitmapTransform(new BlurTransformation(mContext))
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(((ItemTypeViewHolder) viewHolder).iv_card_pic);
if (!user.profile_image.toString().equals(""))
Glide.with(mContext)
.load(user.profile_image.toString()) // Uri of the picture
.into(holder.img_pp);
else
Glide.with(mContext)
.load(R.drawable.ico_profile_default) // Uri of the picture
.into(holder.img_pp);
Push Notification
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private static int count = 0;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Displaying data in log
Log.d(TAG, "Notification Message TITLE: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Notification Message BODY: " + remoteMessage.getNotification().getBody());
Log.d(TAG, "Notification Message DATA: " + remoteMessage.getData().toString());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody(), remoteMessage.getData());
}
//This method is only generating push notification
private void sendNotification(String messageTitle, String messageBody, Map<String, String> row) {
PendingIntent contentIntent = null;
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap))
.setSmallIcon(R.mipmap.)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count, notificationBuilder.build());
count++;
}
}
Snackbar
<string name="no_internet">It seems like there is problem with your internet connection</string>
Main View
android:id="#+id/ll_main"
llMain = findViewById(R.id.ll_main);
Snackbar snackbar = Snackbar.make(llMain, R.string.no_internet, Snackbar.LENGTH_LONG);
snackbar.show();
Custom Spinner
public void CustomSpinner() {
pd = new ProgressDialog(Over75Lakh.this);
pd.setIndeterminate(false);
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
ApiInterface apiServiceData =
ApiClient.getClient().create(ApiInterface.class);
Call<GetServicesMainResponse> callServices = apiServiceData.getServices();
callServices.enqueue(new Callback<GetServicesMainResponse>() {
#Override
public void onResponse(Call<GetServicesMainResponse> call, Response<GetServicesMainResponse> response) {
if ((pd != null) && pd.isShowing()) {
pd.dismiss();
}
getServices = new ArrayList<String>();
getServicesDataResponses = response.body().getData();
for (GetServicesDataResponse getServicesDataResponse : getServicesDataResponses) {
getServices.add(getServicesDataResponse.getServices());
}
ArrayAdapter<String> adapterServices = new ArrayAdapter<String>(Activit.this, android.R.layout.simple_spinner_item, getServices);
adapterServices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spMainService.setAdapter(adapterServices);
}
#Override
public void onFailure(Call<GetServicesMainResponse> call, Throwable t) {
pd.dismiss();
}
});
}
Get CallLogs.
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.CallLog;
public class CallLogHelper {
public static Cursor getAllCallLogs(ContentResolver cr) {
String strOrder = CallLog.Calls.DATE + " DESC"; // ASC --> then latest calls will get the latest txn no
Cursor curCallLogs = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, strOrder);
return curCallLogs;
}
}
public class timer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
= new ArrayList<>();
}
#SuppressLint("DefaultLocale")
#Override
protected String doInBackground(String... params) {
if (ActivityCompat.checkSelfPermission(CallHistoryRevenueActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
return null;
}
Cursor managedCursor = CallLogHelper.getAllCallLogs(getContentResolver());
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
int callType11 = managedCursor.getColumnIndex(android.provider.CallLog.Calls.TYPE);
if (managedCursor.moveToFirst()) {
do {
String contactNumber = managedCursor.getString(number);
String callType = managedCursor.getString(callType11);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = CallType.OUTGOING_CALL_END;
break;
case CallLog.Calls.INCOMING_TYPE:
dir = CallType.INCOMING_CALL_END;
break;
case CallLog.Calls.MISSED_TYPE:
dir = CallType.MISS_CALL;
break;
case CallLog.Calls.VOICEMAIL_TYPE:
dir = CallType.VoiceMail;
break;
case 5:
dir = CallType.Rejected;
break;
case 6:
dir = CallType.Refused;
break;
}
if (str_unit.equals("sec")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = ((str_def_Rate / str_per) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
} else if (str_unit.equals("min")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = (((str_def_Rate / str_per) / 60) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
} else if (str_unit.equals("hr")) {
if (callDuration != null) {
if (callDuration.length() > 0) {
total_rate = (((str_def_Rate / str_per) / 3600) * Integer.parseInt(callDuration));
sum_count_running = sum_count_running + total_rate;
publishProgress(String.valueOf(roundDouble(sum_count_running, 2)));
}
}
}
}
#Override
public void onFailure() {
}
});
}
while (managedCursor.moveToNext());
}
managedCursor.close();
// If the AsyncTask cancelled
if (isCancelled()) {
}
return "run";
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
setText(str_currency + " " + values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
finish();
}
}
JAVA utitlity / Helper Class is here
imports
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class is here
public class Utils {
/**
* Convertim to time format
*
* #param unix is time with long value
* #return string time
*/
public static String convertUnix2Date(long unix) {
if (unix == 0) return "";
String result;
Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
#SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
f.setTimeZone(TimeZone.getDefault());
result = f.format(date);
return result;
}
/**
* Handling the keyboard on device
*
* #param activity
*/
private static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Handling the listener to dismiss the keyboard on device
*
* #param context <br>
* #param view is parent view <br>
*/
public static void setupDismissKeyboardListener(Context context, View view) {
// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener((v, event) -> {
hideSoftKeyboard((Activity) context);
return false;
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupDismissKeyboardListener(context, innerView);
}
}
}
/**
* Converting the DP value to PX to display on device
*
* #param context <br>
* #param value is DP value
* #return PX value
*/
public static int parseFromDPtoPX(Context context, float value) {
Resources resources = context.getResources();
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
value,
resources.getDisplayMetrics()
);
}
public static void setupUI(View view, final Activity activity) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener((v, event) -> {
hideSoftKeyboard(activity);
return false;
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView, activity);
}
}
}
/**
*
*/
protected Utils() {
}
public static final String TAG = "Utils";
public static final int DEFAULT_BUFFER_SIZE = 8192;
private static String sFormatEmail = "^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\\.[a-zA-Z]{2,4}$";
/**
* #return true if JellyBean or higher
*/
public static boolean isJellyBeanOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
/**
* #return true if Ice Cream or higher
*/
public static boolean isICSOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
/**
* #return true if HoneyComb or higher
*/
public static boolean isHoneycombOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
/**
* #return true if GingerBreak or higher
*/
public static boolean isGingerbreadOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
/**
* #return true if Froyo or higher
*/
public static boolean isFroyoOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
/**
* Check SdCard
*
* #return true if External Strorage available
*/
public static boolean isExtStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}
/**
* Check internet
*
* #param context
* #return true if Network connected
*/
public static boolean isNetworkConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
return activeNetworkInfo.isConnected();
}
return false;
}
/**
* Check wifi
*
* #param context
* #return true if Wifi connected
*/
public static boolean isWifiConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetworkInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetworkInfo != null) {
return wifiNetworkInfo.isConnected();
}
return false;
}
/**
* Check on/off gps
*
* #return true if GPS available
*/
public static boolean checkAvailableGps(Context context) {
LocationManager manager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* Download data url
*
* #param urlString
* #return InputStream
* #throws IOException IOException
*/
/**
* #return an {#link HttpURLConnection} using sensible default settings for
* mobile and taking care of buggy behavior prior to Froyo.
* #throws IOException exception
*/
public static HttpURLConnection buildHttpUrlConnection(String urlString)
throws IOException {
Utils.disableConnectionReuseIfNecessary();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
conn.setRequestMethod("GET");
return conn;
}
/**
* Prior to Android 2.2 (Froyo), {#link HttpURLConnection} had some
* frustrating bugs. In particular, calling close() on a readable
* InputStream could poison the connection pool. Work around this by
* disabling connection pooling.
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (!isFroyoOrHigher()) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* Check an email is valid or not
*
* #param email the email need to check
* #return {#code true} if valid, {#code false} if invalid
*/
public static boolean isValidEmail(Context context, String email) {
boolean result = false;
Pattern pt = Pattern.compile(sFormatEmail);
Matcher mt = pt.matcher(email);
if (mt.matches()) {
result = true;
}
return result;
}
/**
* A method to download json data from url
*/
#SuppressWarnings("ThrowFromFinallyBlock")
public static String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
assert iStream != null;
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
*********************************************
Calling Api USing Retrofit
*********************************************
**Dependancies** :-
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:cardview-v7:27.1.1'
enter code here
**Model**
use the Pozo class
**Api Call**
-> getLogin() // use the method
//API call for Login
private void getLogin()
{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("email_id", edit_email.getText().toString());
requestParams.put("password", edit_password.getText().toString());
Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
ShowProgress();
}
#Override
public void onFinish() {
super.onFinish();
Hideprogress();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("", "Login RESPONSE-" + response);
Login login = new Gson().fromJson(String.valueOf(response), Login.class);
edit_email.setText("");
edit_password.setText("");
if (login.getStatus().equals("true")) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
mdToast.show();
Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
hideKeyboard(SignInActivity.this);
Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("", throwable.getMessage());
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
mdToast.show();
}
});
}
**Q :- How to Calling a Api Using Retrofit in Android**
Library :-
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
**[1] Insert & Show Record :-**
*[i]ApiClient :-*
public class ApiClient
{
public static final String BASE_URL ="";
private static Retrofit retrofit = null;
public static Retrofit getClient()
{
if (retrofit == null)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
*[ii]ApiInterface :-*
public interface ApiInterface
{
#FormUrlEncoded
#POST("api/name")
Call<MainStatus> getDetails(#FieldMap HashMap<String, String> params);
}
*[iii]MainStatus :-*
public class MainStatus
{
#SerializedName("status")
#Expose
private String status;
#SerializedName("msg")
#Expose
private String msg;
}
*[iv]MainActivity.java :-*
public class Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
new getData();
}
public void getData()
{
ApiInterface apiObj = ApiClient.getClient().create(ApiInterface.class);
//Optional
//HashMap<String, String> hashMap = new HashMap<>();
//hashMap.put("emp_id", read(USERID));
Call<MainStatus> call = apiObj.getDetails(hashMap);
call.enqueue(new Callback<MainStatus>()
{
#Override
public void onResponse(Call<MainStatus> call, Response<MainStatus> response)
{
Log.d("RESPONS#",""+response);
if (response.body().getStatus().equalsIgnoreCase("true"))
{
mainstatus= response.body().getDetails();
}
}
#Override
public void onFailure(Call<EmployeeLeaveMainDetails> call, Throwable t)
{
Toast.makeText(LeaveApplicationDetails.this, getString("Error"), Toast.LENGTH_SHORT).show();
}
});
}

Categories

Resources