iBeacon Event won't fire

Home - iBeacon Event won't fire

Ignatius Alex asked 7 months ago

iBeacon Event that I’ve tried to call: didEnterRegion, didExitRegion, and didDetermineStateForRegion. But no overide method was called on MainActivity.java. But, they can be called in MesosferApp.java (same like in tutorial Notification). At first, I though if method in MesosferApp.java  and MainActivity.java is redundant or something like that. And then I delete the overide method in MesosferApp.java. But still didn’t work. Here is my code in MainActivity.java:

Start your code here

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,CBServiceListener, CBRangingListener, CBMonitoringListener {

private BluetoothAdapter mBluetoothAdapter;
private final static int REQUEST_ENABLE_BT = 1;
private final static int REQUEST_ENABLE_INTERNET = 2;
public boolean CHECK_BLUETOOTH = true;

//Check Session User Login
// SharedPreferences pref;
private static final String DEBUG_TAG = "NetworkStatus";

// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();

// Session Manager Class
SessionManager session;
private String user_id;

//Set Session
NavigationView navigationView;
View hView;
TextView nav_user;
ImageView nav_user_img;

//Navigation Item Selected
public int selectedNavigation = 0;

RequestParams params = new RequestParams();
Map<String, String> map = new HashMap<String, String>();

//Exit App Dialog
DemoTask blockingDialog;

//Cubeacon
// Now, the code to start and stop ranging as the activity appears and disappears on screen.
// You need to implement CBServiceListener before connecting to service
private static final String TAG = MainActivity.class.getSimpleName();
private Cubeacon cubeacon;
private CBRegion region;
private List<Map<String, String>> data;
private List<CBBeacon> beacons;

protected void onCreate(Bundle savedInstanceState) {
// Session class instance
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.directions);
onNavigationItemSelected(navigationView.getMenu().getItem(0));
Log.d("main","on create");

data = new ArrayList<>();
// assign local instance of Cubeacon manager
cubeacon = Cubeacon.getInstance();
// create a new region for ranging beacons
region = new CBRegion("com.eyro.cubeacon.ranging_region",
UUID.fromString("CB10023F-A318-3394-4199-A8730C7C1AEC"));
}

public Integer isConnected(){
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);
Integer result = 0;
if(isWifiConn && isMobileConn){
result = 2;
} else if(isWifiConn || isMobileConn){
result = 1;
}
return result;
}

public boolean isOnline() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Log.d("ONLINE",""+networkInfo.isConnected());
return (networkInfo != null && networkInfo.isConnected());
}

@Override
protected void onResume() {
super.onResume();

if(isConnected() == 0){
Intent enableInternet = new Intent(Settings.ACTION_SETTINGS);
startActivityForResult(enableInternet, REQUEST_ENABLE_INTERNET);
} else{
if(!isOnline()){
try{
DemoTask aw = new DemoTask(MainActivity.this);
aw.getDialog(1);
aw.execute();
}catch(Exception e){
Log.e("Error", e.getMessage());
e.printStackTrace();
}
} else{

if (SystemRequirementManager.checkAllRequirementUsingDefaultDialog(this)) {
// connecting to Cubeacon service when all requirements completed
cubeacon.connect(this);
// disable background mode, because we're going to use full
// scanning resource in foreground mode
cubeacon.setBackgroundMode(false);
}

session = new SessionManager(getApplicationContext());
session.checkLogin();
Log.d("SESSION MAIN RESUME",""+session.getUserDetails().get("pic")+" Name "+session.getUserDetails().get("name"));
hView = navigationView.getHeaderView(0);
nav_user = (TextView)hView.findViewById(R.id.header_username);
if(session.getUserDetails().get("name") != null || session.getUserDetails().get("pic") != null){
user_id = session.getUserDetails().get("id");

Integer nameLength = session.getUserDetails().get("name").length();
String name = session.getUserDetails().get("name");
String[] str, str2;
//Manipulation Name in Navigation Drawer
String nameAf = "";
if(nameLength > 25){
str = name.split(" ");
str2 = name.split(" ",24);
int i,count=0;

for(i=0; i<str.length; i++){
count += str[i].length();
if(count<=25){
nameAf += str[i] + " ";
} else{
nameAf.trim();
break;
}
}
// Log.d("SESSION UPDATE","nameAf: "+nameAf+" lengthz:"+nameAf.length()+
// "\nsplit1_length: "+str.length+
// "\nsplit2_length: "+str2.length+
// "\nsplit1: "+str[2]+
// "\nsplit2: "+str2[2]);
nav_user.setText(nameAf);
} else{
nav_user.setText(name);
}

String picAddress;
if( session.getUserDetails().get("pic") == null){
picAddress = "images/default/default-avatar.png";
} else{
picAddress = session.getUserDetails().get("pic");
}
picAddress = picAddress.replace(" ","%20");
Log.d("PIC ADDRESS",""+picAddress);

//Change User State to: ONLINE
//Update User State

map.clear();
map.put("type","ONLINE");
map.put("u_id",user_id);
params.put("user", map);
Log.d("PREPARE UPDATE_STATE","type: "+map.get("type")+" ID: "+map.get("u_id"));
try {
updateUserState(params);
} catch (JSONException e) {
e.printStackTrace();
Log.d("Error Param","updateUserState map params");
}
}
}
}

Log.d("state MAIN","Resume");
}

//UPDATE STATE OFFLINE/ONLINE
public void updateUserState(RequestParams params) throws JSONException {
String url = "jsonUpdateUserState.php";
IPSClient.get(url, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("UPDATE_STATE","onSuccess JSONObject");
try {
Integer status = Integer.valueOf(response.getString("status"));
if(status == 1){
Log.d("UPDATE_STATE","STATUS: 1 -> GO ONLINE");
// Toast.makeText(MainActivity.this, "User State: ONLINE", Toast.LENGTH_LONG).show();
}else if(status == 2){
Log.d("UPDATE_STATE","STATUS: 2 -> GO OFFLINE");
// Toast.makeText(MainActivity.this, "User State: OFFLINE", Toast.LENGTH_LONG).show();
}
else if(status == 0){
Log.d("UPDATE_STATE","FAIL");
// Toast.makeText(MainActivity.this, "User State: OFFLINE", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.d("UPDATE_STATE","FAIL");
}
}

@Override
public void onSuccess(int statusCode, Header[] headers, String aw) {
// Pull out the first event on the public timeline
Log.d("UPDATE_STATE","onSuccess String");
}

@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
Log.d("UPDATE_STATE","onSuccess JSONArray");
}

@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("onFailure String","RESPONSE_STRING");
Log.d("Failed: ", ""+statusCode);
Log.d("Error : ", "" + throwable);
}

@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
//super.onFailure(statusCode, headers, throwable, errorResponse);
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(MainActivity.this,
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(MainActivity.this,
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(
MainActivity.this,
"Error.. \nMost Common Error: \n1. Device not connected to Internet\n2. Device does not support BLE\n3. App server is not running HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ArrayList nav = new ArrayList();
if (selectedNavigation == 1){
nav.add("R.id.directions");
nav.add(0);
Log.d("Array nav",""+nav.get(0)+"\n"+nav.get(1));
outState.putStringArrayList("restoreNav",nav);
}else if(selectedNavigation == 2){
nav.add("R.id.person");
nav.add(1);
outState.putStringArrayList("restoreNav",nav);
}else if(selectedNavigation == 3){
nav.add("R.id.friends");
nav.add(2);
outState.putStringArrayList("restoreNav",nav);
}

// navigationView.setNavigationItemSelectedListener(this);
// //navigationView.getMenu().getItem(0).setChecked(true);
// navigationView.setCheckedItem(R.id.directions);
// onNavigationItemSelected(navigationView.getMenu().getItem(0));
;
Log.d("state MAIN","onSaveInstance");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
ArrayList getInstance = savedInstanceState.getStringArrayList("restoreNav");
//Integer resource_id = (Integer) getInstance.get(0);
Integer item = (Integer) getInstance.get(1);
Log.d("Array nav GET",""+getInstance.get(0)+"\n"+getInstance.get(1));
//navigationView.setCheckedItem(resource_id);
onNavigationItemSelected(navigationView.getMenu().getItem(item));
Log.d("state MAIN","onRestoreInstance");
}

@Override
protected void onPause() {
super.onPause();
Log.d("state MAIN","Pause");
// enable background mode when this activity paused
cubeacon.setBackgroundMode(true);
//Change User State to: ONLINE
//Update User State
map.clear();
map.put("type", "OFFLINE");
map.put("u_id",user_id);
params.put("user", map);
try {
updateUserState(params);
} catch (JSONException e) {
e.printStackTrace();
Log.d("Error Param","updateUserState map params");
}
}

@Override
protected void onDestroy() {
super.onDestroy();
// disconnect from Cubeacon service when this activity destroyed
cubeacon.disconnect(this);
}

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else{
if (doubleBackToExitPressedOnce) {
blockingDialog = new DemoTask(MainActivity.this);
blockingDialog.execute();
Log.d("MAIN","onBackPressed");

}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {

@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
//String result=data.getStringExtra("result");
Log.d("onActivityResult: ","RESULT OK");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Jika user denied akses BLE
//Exit Apps
Log.d("onActivityResult: ","RESULT CANCELED");
finish();
}
}

if (requestCode == 2) {
if(resultCode == Activity.RESULT_OK){
//String result=data.getStringExtra("result");
// finish();
// startActivity(getIntent());
Log.d("onActivityResult LOGIN","RESULT OK");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Jika user denied akses Internet
//Exit Apps
Log.d("onActivityResult LOGIN","RESULT CANCELED");
// Intent refresh = new Intent(this, MainActivity.class);
// startActivity(refresh);
// this.finish();
}
}
//super.onActivityResult(requestCode, resultCode, data);
}

// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Log.d("Navigation Item ID",""+id);
if (id == R.id.directions) {
selectedNavigation = 1;
Log.d("main","on direction");

if(isConnected() == 0){
Intent enableInternet = new Intent(Settings.ACTION_SETTINGS);
startActivityForResult(enableInternet, REQUEST_ENABLE_INTERNET);
} else {
if (!isOnline()) {
try {
DemoTask aw = new DemoTask(MainActivity.this);
aw.getDialog(1);
aw.execute();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
// alert.showAlertDialog(MainActivity.this, "No Network Connection", "Please check your internet connection", false);
// finish();
} else{
// if(CHECK_BLUETOOTH){
// // Initializes Bluetooth adapter.
// final BluetoothManager bluetoothManager =
// (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
// mBluetoothAdapter = bluetoothManager.getAdapter();
//
// // Ensures Bluetooth is available on the device and it is enabled. If not,
// // displays a dialog requesting user permission to enable Bluetooth.
// if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// }
// CHECK_BLUETOOTH=false;
// }
}
PetaFragment peta = new PetaFragment();
FragmentManager petaFragment = getFragmentManager();
petaFragment.beginTransaction()
.replace(R.id.content_frame, peta)
.commit();
}
//temp.set();
// create new fragmap.java
//op 2 ketik disini googlemap
} else if (id == R.id.person) {
selectedNavigation = 2;
Log.d("main","on person");
if(isConnected() == 0){
Intent enableInternet = new Intent(Settings.ACTION_SETTINGS);
startActivityForResult(enableInternet, REQUEST_ENABLE_INTERNET);
} else {
if (!isOnline()) {
try {
DemoTask aw = new DemoTask(MainActivity.this);
aw.getDialog(1);
aw.execute();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
// alert.showAlertDialog(MainActivity.this, "No Network Connection", "Please check your internet connection", false);
// finish();
}
ProfileFragment person = new ProfileFragment();
FragmentManager personFragment = getFragmentManager();
personFragment.beginTransaction()
.replace(R.id.content_frame, person)
.commit();
}

// FragmentTransaction personTransaction = getFragmentManager().beginTransaction();
// personTransaction.replace(R.id.content_frame, person);
// if(personTransaction==null){
// personTransaction.replace(R.id.content_frame, person);
// }else{
// }
// personTransaction.commit();
} else if (id == R.id.friends) {
selectedNavigation = 3;
Log.d("main","on friends");
if(isConnected() == 0){
Intent enableInternet = new Intent(Settings.ACTION_SETTINGS);
startActivityForResult(enableInternet, REQUEST_ENABLE_INTERNET);
} else {
if (!isOnline()) {
try {
DemoTask aw = new DemoTask(MainActivity.this);
aw.getDialog(1);
aw.execute();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
// alert.showAlertDialog(MainActivity.this, "No Network Connection", "Please check your internet connection", false);
// finish();
}
FriendsFragment friends = new FriendsFragment();
FragmentManager fragmentFriends = getFragmentManager();
fragmentFriends.beginTransaction()
.replace(R.id.content_frame, friends)
.commit();
}
} else if (id == R.id.logout) {
Log.d("main","on logout");
session.logoutUser();
finish();

} /*else if (id == R.id.nav_share) {

} else if (id == R.id.nav_send) {

}*/

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

@Override
public void didRangeBeaconsInRegion(List<CBBeacon> beacons, CBRegion cbRegion) {
this.beacons = beacons;
String title, subtitle;
Map<String, String> map;

// clear data
data.clear();
for (CBBeacon beacon : beacons) {
title = beacon.getProximityUUID().toString().toUpperCase();
subtitle = String.format(Locale.getDefault(), "M:%d m:%d RSSI:%d Accuracy:%.2fm",
beacon.getMajor(), beacon.getMinor(), beacon.getRssi(), beacon.getAccuracy());
map = new HashMap<>();
map.put("title", title);
map.put("subtitle", subtitle);
data.add(map);
Log.d("BEACON SERVICE","UUID: "+beacon.getProximityUUID().toString().toUpperCase()+
" Major: "+beacon.getMajor()+
" Minor: "+beacon.getMinor()+
" RSSI: "+beacon.getRssi()+
" Accuracy: "+beacon.getAccuracy());
}


// update view using runnable
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// adapter.notifyDataSetChanged();
// if (getSupportActionBar() != null) {
// getSupportActionBar().setSubtitle("Ranged beacon : " + beacons.size());
// }
// }
// });
}

@Override
public void onBeaconServiceConnect() {
// add ranging listener implementation
cubeacon.addRangingListener(this);
try {
//#Cara 1
// create a new region for ranging beacons
CBRegion region = new CBRegion("com.eyro.cubeacon.ranging_region");
// start ranging beacons using region

//#Cara 2
// cubeacon = Cubeacon.getInstance();
// // create a new region for ranging beacons
// region = new CBRegion("com.eyro.cubeacon.ranging_region",
// UUID.fromString("CB10023F-A318-3394-4199-A8730C7C1AEC"));
cubeacon.startRangingBeaconsInRegion(region);

} catch (RemoteException e) {
Log.e(TAG, "Error while start ranging beacon, " + e);
}
}

//Kayake gk guna method sing ini,
//Bentrok bek sing nde MesosferApp.
@Override
public void didEnterRegion(CBRegion cbRegion) {
Log.d("REGION","ENTER");
Toast.makeText(MainActivity.this,"PIN:Entering beacon region",Toast.LENGTH_SHORT);
//RETRIEVE BEACON DATA
MesosferQuery query = MesosferBeacon.getQuery();
// query.whereEqualTo("minor",158);
String uuid = "cb10023f-a318-3394-4199-a8730c7c1aec";
uuid = uuid.toUpperCase();
query.whereEqualTo("uuid",uuid);
query.whereEqualTo("major", 111);
query.findAsync(new FindCallback<MesosferBeacon>() {
@Override
public void done(List<MesosferBeacon> list, MesosferException e) {
Log.d("REGION","Name: "+list.toString());
if (e != null) {
Log.e("REGION", "Error happen when finding storyline: " + e);
Toast.makeText(MainActivity.this,"Error Story: "+e, Toast.LENGTH_SHORT).show();
return;
}
Log.d("REGION","DONE!");
if (list != null && !list.isEmpty()) {
Log.d("REGION","DONE! LIST NOT EMPTY");
Toast.makeText(MainActivity.this,"LIST OK",Toast.LENGTH_SHORT);
MesosferBeacon detail = null;
for(int i=0; i<list.size(); i++){
detail = list.get(i);
displayBeacon(detail);
}

}
}
});
}

@Override
public void didExitRegion(CBRegion cbRegion) {
Log.d("REGION","EXIT");
Toast.makeText(MainActivity.this,"PIN:Exiting region",Toast.LENGTH_SHORT);
}
@Override
public void didDetermineStateForRegion(final MonitoringState monitoringState, CBRegion cbRegion) {
Log.d(TAG, "Region (Main Activity): " + monitoringState + ", state: " + monitoringState.name());
runOnUiThread(new Runnable() {
@Override
public void run() {
switch (monitoringState) {
case INSIDE:
// textState.setText(getString(R.string.label_state, "ENTER REGION"));
// Toast.makeText(MainActivity.this,"ENTER REGION",Toast.LENGTH_SHORT);
break;
case OUTSIDE:
// textState.setText(getString(R.string.label_state, "EXIT REGION"));
// Toast.makeText(MainActivity.this,"EXIT REGION",Toast.LENGTH_SHORT);
break;
}
}
});
}

private void displayBeacon(MesosferBeacon detail) {
Log.d("REGION","MASUK DISPLAY BEACON");
String title = detail.getName();
String message = null;
try {
Log.d("REGION","MASUK DISPLAY BEACON -> TRY");
Log.d("REGION","MASUK DISPLAY BEACON -> TRY -> GET NAME:"+detail.getName());
Log.d("REGION","MASUK DISPLAY BEACON -> TRY -> GET NAME:"+detail.getMinor());
Log.d("REGION","MASUK DISPLAY BEACON -> TRY -> GET NAME:"+detail.getData().toString());
Log.d("REGION","MASUK DISPLAY BEACON -> TRY -> GET NEW UUID:"+detail.getData().getString("newUUID"));
String newUUID = detail.getData().getString("newUUID");
String[] finalUUID = newUUID.split(",");
int length = finalUUID[0].length();
String floorNumber = finalUUID[0].substring(0,length-1);
String intermedieteFloor = finalUUID[0].substring(length-1);
Log.d("REGION","MASUK DISPLAY BEACON -> TRY -> GET PARAMETER UUID:\nFloor: "
+finalUUID[0]+" Lat: "+finalUUID[1]+" Long: "+finalUUID[2]);
message = "Floor: "+floorNumber+
"\nIntermediete Floor"+intermedieteFloor+
"\nLat: "+finalUUID[1]+
"\nLong: "+finalUUID[2];
new AlertDialog.Builder(MainActivity.this)
.setTitle(title)
.setMessage(message)
.setNegativeButton(android.R.string.ok, null)
.show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("REGION_ERROR_JSON",""+e);
}
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
private Exception failImage;

public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
failImage = e;
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
if(failImage==null){
Bitmap output = Bitmap.createBitmap(result.getWidth(),
result.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, result.getWidth(), result.getHeight());

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
// canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
canvas.drawCircle(result.getWidth() / 2, result.getHeight() / 2,
result.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(result, rect, rect, paint);
bmImage.setImageBitmap(output);
}else{
Log.d("IMAGE FAIL","Fail to download image");
}

}
}

//Block Dialog
public class DemoTask extends AsyncTask<Void, Void, String> implements ResultListener<String> {

private WeakReference<Activity> weakActivity;
private String result;
private boolean cancelled;
private int customDialog;
public void getDialog(Integer dialog){
customDialog = dialog;
}

public DemoTask(Activity activity) {
weakActivity = new WeakReference<>(activity);
}

@Override protected String doInBackground(Void... params) {

doSomeWork(500);

Activity activity = weakActivity.get();
if (activity != null && !activity.isFinishing()) {
if(customDialog == 1){
Log.d("MAIN","customDIalog");
BlockingDialogManager.getInstance().showAndWait(activity, new DemoDialogNoInternet(), this);
} else{
BlockingDialogManager.getInstance().showAndWait(activity, new DemoDialog(), this);
}

}

if (!cancelled) {
doSomeWork(1500);
}

return result;
}

@Override protected void onPostExecute(String message) {
Activity activity = weakActivity.get();
if (activity != null && !activity.isFinishing() && !cancelled) {
//Toast.makeText(activity.getApplicationContext(), message, Toast.LENGTH_LONG).show();
if(message == "YES_EXIT"){
activity.finish();
Log.d("MAIN DemoTask","FINISH!");
}else if( message == "NO_EXIT"){
Log.d("MAIN DemoTask","CANCEL");
}else if( message == "YES_NO_INET"){
Log.d("MAIN DemoTask","YES NO INET");
activity.finish();
}
}
}



@Override public void onResult(String result, boolean cancelled) {
this.cancelled = cancelled;
this.result = result;
}

private void doSomeWork(int millis) {
try {
Thread.sleep(millis); // simulate work
} catch (InterruptedException ignored) {
}
}

}

}
1 Answers
Alann Maulana Staff answered 7 months ago

Hi Ignatius,
For scanning, please refers to Cubeacon SDK for Android Wiki :

Regards.

Your Answer