No Permissions Pop Up Anymore? - java

So I am creating an app that requests permission to a users google account. I used mine to test and so I gave it permission and then removed it to see if it would ask for it again. It was still using the token it got so I deleted the app from my phone and reinstalled it. I didn't change any code and now all of a sudden it only shows the account page (to select which account) and then once I press ok, nothing shows to give it permission. In my run console I get the following:
$ adb push C:\Users\James Singleton\AndroidStudioProjects\ChffrAPI\app\build\outputs\apk\app-debug.apk /data/local/tmp/com.example.jamessingleton.chffrapi
$ adb shell pm install -r "/data/local/tmp/com.example.jamessingleton.chffrapi"
pkg: /data/local/tmp/com.example.jamessingleton.chffrapi
Success
$ adb shell am start -n "com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 25029 on device samsung-sm_g935v-0d75cc0d
E/Zygote: v2
W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0010
E/Zygote: accessInfo : 0
I/libpersona: KNOX_SDCARD checking this for 10269
I/libpersona: KNOX_SDCARD not a persona
W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.example.jamessingleton.chffrapi
I/art: Late-enabling -Xcheck:jni
D/ActivityThread: Added TimaKeyStore provider
D/RelationGraph: garbageCollect()
I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
D/ContextRelationManager: ContextRelationManager() : FEATURE_ENABLED=true
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
D/ResourcesManager: For user 0 new overlays fetched Null
I/InjectionManager: Inside getClassLibPath caller
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
W/art: Failed to open zip archive '/system/framework/dpmapi.jar': I/O Error
W/System: ClassLoader referenced unknown path: /data/app/com.example.jamessingleton.chffrapi-2/lib/arm64
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
D/InjectionManager: InjectionManager
D/InjectionManager: fillFeatureStoreMap com.example.jamessingleton.chffrapi
I/InjectionManager: Constructor com.example.jamessingleton.chffrapi, Feature store :{}
I/InjectionManager: featureStore :{}
D/RelationGraph: garbageCollect()
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/ResourcesManager: getTopLevelResources: /data/app/com.example.jamessingleton.chffrapi-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.example.jamessingleton.chffrapi
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/ResourcesManager: getTopLevelResources: /data/app/com.google.android.gms-2/base.apk / 1.0 running in com.example.jamessingleton.chffrapi rsrc of package com.google.android.gms
I/InjectionManager: Inside getClassLibPath caller
D/ResourcesManager: For user 0 new overlays fetched Null
D/ChimeraCfgMgr: Reading stored module config
W/System: ClassLoader referenced unknown path: /data/user/0/com.google.android.gms/app_chimera/m/00000007/n/arm64-v8a
D/ChimeraFileApk: Primary ABI of requesting process is arm64-v8a
D/ChimeraFileApk: Classloading successful. Optimized code found.
D/Activity: performCreate Call Injection manager
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.WifivsDataDialog isFragment :true
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{3c6164c V.E...... R.....I. 0,0-0,0}
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
D/SecWifiDisplayUtil: Metadata value : SecSettings2
I/InjectionManager: dispatchOnViewCreated > Target : com.example.jamessingleton.chffrapi.MainActivity isFragment :false
D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{ead695 I.E...... R.....ID 0,0-0,0}
I/Adreno: QUALCOMM build : c0299d7, I241dab1ec4
Build Date : 01/25/16
OpenGL ES Shader Compiler Version: XE031.06.00.05
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.HB.1.1.1.06.00.01.063.117
Remote Branch : NONE
Reconstruct Branch : NOTHING
D/libEGL: eglInitialize EGLDisplay = 0x7f62194188
I/OpenGLRenderer: Initialized EGL, version 1.4
I/InjectionManager: dispatchCreateOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
I/InjectionManager: dispatchPrepareOptionsMenu :com.example.jamessingleton.chffrapi.MainActivity
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : com.example.jamessingleton.chffrapi
W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#7d80ce5 time:2598350
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/WifiManager: isAllowWifiWarning() -> isCscWifiEnableWarning : false ChinaNalSecurityType :
D/ViewRootImpl: #3 mView = null
E/ViewRootImpl: sendUserActionEvent() mView == null
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 1128) vi=Rect(0, 96 - 0, 1128) or=1
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
I/Timeline: Timeline: Activity_launch_request id:android time:2603031
D/ViewRootImpl: MSG_RESIZED: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
V/ActivityThread: updateVisibility : ActivityRecord{65ce05f token=android.os.BinderProxy#7d80ce5 {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : true
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#7d80ce5 time:2605454
V/ActivityThread: updateVisibility : ActivityRecord{65ce05f token=android.os.BinderProxy#7d80ce5 {com.example.jamessingleton.chffrapi/com.example.jamessingleton.chffrapi.MainActivity}} show : false
Application terminated.
Nothing changed in my code so I have no idea why I am not getting the pop up to allow me to give the app permission.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
Context mContext = MainActivity.this;
private AccountManager mAccountManager;
private AuthPreferences authPreferences;
EditText emailText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "";
static final String API_URL = "https://api.comma.ai/v1/auth/?access_token=";
static final String ClientId = "45471411055-m902j8c6jo4v6mndd2jiuqkanjsvcv6j.apps.googleusercontent.com";
static final String ClientSecret = "";
static final String SCOPE = "https://www.googleapis.com/auth/userinfo.email";
private static final int AUTHORIZATION_CODE = 1993;
private static final int ACCOUNT_CODE = 1601;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
final Context context = this;
mAccountManager = AccountManager.get(this);
authPreferences = new AuthPreferences(this);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (authPreferences.getUser() != null && authPreferences.getToken() != null) {
doCoolAuthenticatedStuff();
new RetrieveFeedTask().execute();
} else {
chooseAccount();
}
}
});
// Button queryButton = (Button) findViewById(R.id.queryButton);
//
// queryButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (isNetworkAvailable() == true) {
// new RetrieveFeedTask().execute();
// Intent intent = new Intent(context, NavDrawerActivity.class);
// startActivity(intent);
// } else {
// Toast.makeText(MainActivity.this, "No Network Service, please check your WiFi or Mobile Data Connection", Toast.LENGTH_SHORT).show();
// }
// }
// });
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
boolean dontShowDialog = sharedPref.getBoolean("DONT_SHOW_DIALOG", false);
if (!dontShowDialog) {
WifivsDataDialog myDiag = new WifivsDataDialog();
myDiag.show(getFragmentManager(), "WiFi");
myDiag.setCancelable(false);
}
}
private void doCoolAuthenticatedStuff() {
Log.e("AuthApp", authPreferences.getToken());
}
private void chooseAccount() {
Intent intent = AccountManager.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
public void requestToken() {
Account userAccount = null;
String user = authPreferences.getUser();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
for (Account account : mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)) {
if (account.name.equals(user)) {
userAccount = account;
break;
}
}
mAccountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this, new OnTokenAcquired(), null);
}
private void invalidateToken() {
AccountManager mAccountManager = AccountManager.get(this);
mAccountManager.invalidateAuthToken("com.google", authPreferences.getToken());
authPreferences.setToken(null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == AUTHORIZATION_CODE) {
requestToken();
} else if (requestCode == ACCOUNT_CODE) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
authPreferences.setUser(accountName);
// invalidate old tokens which might be cached. we want a fresh
// one, which is guaranteed to work
invalidateToken();
requestToken();
}
}
}
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
Bundle bundle = result.getResult();
Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, AUTHORIZATION_CODE);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
authPreferences.setToken(token);
System.out.println(authPreferences);
doCoolAuthenticatedStuff();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
}
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "Available");
return true;
}
Log.e("Network Testing", "Not Available");
return false;
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
// Do some validation here
try {
URL url = new URL(API_URL + authPreferences.getToken());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = urlConnection.getResponseCode();
System.out.println("GET Response code:" + responseCode);
// urlConnection.addRequestProperty("client_id", ClientId);
// urlConnection.addRequestProperty("client_secret", ClientSecret);
// urlConnection.setRequestProperty("Authorization", "JWT " + authPreferences);
Log.i("URL", url.toString());
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
//
// TODO: check this.exception
// TODO: do something with the feed
// try {
// JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
// String requestID = object.getString("requestId");
// int likelihood = object.getInt("likelihood");
// JSONArray photos = object.getJSONArray("photos");
// .
// .
// .
// .
// } catch (JSONException e) {
// e.printStackTrace();
// }
}
}}
And then here is my AuthPreferences.java
public class AuthPreferences {
private static final String KEY_USER = "user";
private static final String KEY_TOKEN = "token";
private SharedPreferences preferences;
public AuthPreferences(Context context) {
preferences = context
.getSharedPreferences("auth", Context.MODE_PRIVATE);
}
public void setUser(String user) {
Editor editor = preferences.edit();
editor.putString(KEY_USER, user);
editor.commit();
}
public void setToken(String password) {
Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, password);
editor.commit();
}
public String getUser() {
return preferences.getString(KEY_USER, null);
}
public String getToken() {
return preferences.getString(KEY_TOKEN, null);
}
}

Related

No task registered for key error while using headless JS

I am using foreground service for detecting beacons since Android Oreo kills all background services, we decided to go on with foreground service to detect beacons when the app is in foreground/killed/in background.
This works fine on android 7.0 and below but on android 8 it throws an error "No task registered for key "didEnterRegion"
This is my code
Helper.java
public static void sendNewBeacons(Context context, Collection<Beacon> beacons) {
if (beacons != null && beacons.size() > 0) {
for (Beacon beacon : beacons) {
Intent service = new Intent(context, MyTaskService.class);
service.putExtra("eventName", "didEnterRegion");
service.putExtra("beacon", (Parcelable) beacon);
context.startService(service);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
}
public static void sendRemovedBeacons(Context context, Collection<Beacon> beacons) {
if (beacons != null && beacons.size() > 0) {
for (Beacon beacon : beacons) {
Intent service = new Intent(context, MyTaskService.class);
service.putExtra("eventName", "didExitRegion");
service.putExtra("beacon", (Parcelable) beacon);
context.startService(service);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
}
This is TaskService code
public class MyTaskService extends HeadlessJsTaskService {
private final String TAG = "TaskService";
#Override
protected #Nullable
HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null) {
return null;
}
String event = extras.getString("eventName");
if (TextUtils.isEmpty(event)) {
return null;
}
WritableMap map = new WritableNativeMap();
if (extras.containsKey("beacon")) {
map = BeaconHelper.getObject((Beacon)
extras.getParcelable("beacon"));
}
Log.d(TAG, event);
return new HeadlessJsTaskConfig(event, map,5000, true);
}
#Override
public void onHeadlessJsTaskFinish(int taskId) {
super.onHeadlessJsTaskFinish(taskId);
}
This is my App.js
AppRegistry.registerHeadlessTask('didEnterRegion', () =>
require('./BeaconEntering.js'));
AppRegistry.registerHeadlessTask('didExitRegion', () =>
require('./BeaconExiting.js'));
const myModuleEvt = new
NativeEventEmitter(NativeModules.BeaconManager);
const rangeBeacon = myModuleEvt.addListener('didRangeBeacons',
Util.didRangeBeacons);
const exitRegion = myModuleEvt.addListener('didExitRegion',
Util.didExitRegion);
const entryRegion =
myModuleEvt.addListener('didEnterRegion',Util.didEnterRegion);
This is a log before crash
09-12 20:03:25.801 15850-22489/com.kr_beaconmanager D/BluetoothAdapter: isLeEnabled(): ON
09-12 20:03:25.802 15850-15850/com.kr_beaconmanager I/ScanJob: We are inside a beacon region. We will not scan between cycles.
09-12 20:03:25.809 15850-15850/com.kr_beaconmanager I/System.out: null checkBeacons [id1: 341e458b-ad9e-4981-b01f-ddbce8f43d5c id2: 18 id3: 18]
handleNewAndRemovedBeacon 1 >< 0
09-12 20:03:25.824 15850-15850/com.kr_beaconmanager I/System.out: showNotification didRangeBeaconsInRegion
09-12 20:03:25.828 15850-15850/com.kr_beaconmanager I/System.out: didEnterRegion
09-12 20:03:25.830 15850-15913/com.kr_beaconmanager E/ReactNativeJS: No task registered for key didEnterRegion
09-12 20:03:26.031 15850-15850/com.kr_beaconmanager I/CycledLeScanner: Using Android O scanner
09-12 20:03:26.033 15850-15850/com.kr_beaconmanager I/ScanJob: Using immediateScanJobId from manifest: 208352939 Running immediate scan job: instance is org.altbeacon.beacon.service.ScanJob#f13f916
09-12 20:03:26.034 15850-15850/com.kr_beaconmanager I/ScanJob: scanJob version 2.15.1 is starting up on the main process
09-12 20:03:26.035 15850-15855/com.kr_beaconmanager I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.(android.content.Context, android.util.AttributeSet, int, int)
09-12 20:03:26.037 15850-15850/com.kr_beaconmanager W/ModelSpecificDistanceCalculator: Cannot find match for this device. Using default Cannot find match for this device. Using default
Found the fix,
We need to define the function first
const didEnterRegion = async (data) => {
console.log(data);
};
and then register the headlessTask
AppRegistry.registerHeadlessTask('didEnterRegion', () => didEnterRegion);

Android get json from webhost to add markers ERROR E/zygote64

i am making one project example to get json coordinates from 000webhost and show marks in maps in Android.
This is my java main code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
public static final String URL="http://rrsaikat.mydiscussion.net/myjson/location.php";
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
mMap.setMyLocationEnabled(true);
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JSONResult" , response.toString());
JSONObject j = null;
try{
j =new JSONObject(response);
result = j.getJSONArray("FL");
for(int i=0;i<result.length();i++){
JSONObject jsonObject1=result.getJSONObject(i);
String lat_i = jsonObject1.getString("1");
String long_i = jsonObject1.getString("2");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(Double.parseDouble(lat_i) , Double.parseDouble(long_i)))
.title(Double.valueOf(lat_i).toString() + "," + Double.valueOf(long_i).toString())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(23.6850,90.3563), 6.0f));
}
}catch (NullPointerException e){
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MapsActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
int socketTimeout = 10000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
But i dont have the marks in Android and i have this debug:
W/zygote64: Skipping duplicate class check due to unrecognized classloader I/DynamiteModule: Considering local module
com.google.android.gms.maps_dynamite:0 and remote module
com.google.android.gms.maps_dynamite:220 I/DynamiteModule: Selected
remote version of com.google.android.gms.maps_dynamite, version >= 220
W/zygote64: Skipping duplicate class check due to unrecognized
classloader I/Google Maps Android API: Google Play services client
version: 12451000 I/Google Maps Android API: Google Play services
package version: 12685023 I/zygote64: Do partial code cache
collection, code=23KB, data=29KB
After code cache collection, code=23KB, data=29KB
Increasing code cache capacity to 128KB E/zygote64: The String#value field is not present on Android versions >= 6.0
D/NetworkSecurityConfig: No Network Security Config specified, using
platform default I/System.out: (HTTPLog)-Static: isSBSettingEnabled
false I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/zygote64: Do partial code cache collection, code=61KB, data=59KB
D/TcpOptimizer: TcpOptimizer-ON I/zygote64: After code cache
collection, code=61KB, data=59KB
Increasing code cache capacity to 256KB D/ViewRootImpl#82b5652[MapsActivity]: setView =
DecorView#42ced23[MapsActivity] TM=true MM=false
D/ViewRootImpl#4f69478[Launcher]: MSG_WINDOW_FOCUS_CHANGED 0
D/ViewRootImpl#82b5652[MapsActivity]: dispatchAttachedToWindow
V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
D/ViewRootImpl#82b5652[MapsActivity]: Relayout returned:
old=[0,0][0,0] new=[0,0][1080,2220] result=0x7 surface={valid=true
490213584896} changed=true D/mali_winsys: EGLint
new_window_surface(egl_winsys_display *, void *, EGLSurface,
EGLConfig, egl_winsys_surface **, egl_color_buffer_format *,
EGLBoolean) returns 0x3000, [1080x2220]-format:1 D/OpenGLRenderer:
eglCreateWindowSurface = 0x7230f51fa0
D/ViewRootImpl#82b5652[MapsActivity]: MSG_RESIZED_REPORT:
frame=Rect(0, 0 - 1080, 2220) ci=Rect(0, 63 - 0, 0) vi=Rect(0, 63 - 0,
0) or=1
MSG_WINDOW_FOCUS_CHANGED 1 V/InputMethodManager: Starting input:
tba=android.view.inputmethod.EditorInfo#9c8881 nm :
com.a9831.sapires.samuel9831 ic=null I/InputMethodManager:
startInputInner - mService.startInputOrWindowGainedFocus V/Surface:
sf_framedrop debug : 0x4f4c, game : false, logging : 0 V/Surface:
sf_framedrop debug : 0x4f4c, game : false, logging : 0 D/mali_winsys:
EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface,
EGLConfig, egl_winsys_surface **, egl_color_buffer_format *,
EGLBoolean) returns 0x3000, [1080x2157]-format:2 D/OpenGLRenderer:
eglDestroySurface = 0x7242c28a00 D/ViewRootImpl#4f69478[Launcher]:
Relayout returned: old=[0,0][1080,2220] new=[0,0][1080,2220]
result=0x5 surface={valid=false 0} changed=true I/System.out:
(HTTPLog)-Static: isSBSettingEnabled false I/System.out:
(HTTPLog)-Static: isSBSettingEnabled false
D/ViewRootImpl#4f69478[Launcher]: dispatchDetachedFromWindow
D/InputEventReceiver: channel 'f8f1abc
com.a9831.sapires.samuel9831/com.a9831.sapires.samuel9831.Launcher
(client)' ~ Disposing input event receiver.
channel 'f8f1abc com.a9831.sapires.samuel9831/com.a9831.sapires.samuel9831.Launcher
(client)' ~NativeInputEventReceiver. I/zygote64: Do full code cache
collection, code=124KB, data=118KB I/zygote64: After code cache
collection, code=111KB, data=63KB W/DynamiteModule: Local module
descriptor class for com.google.android.gms.googlecertificates not
found. I/DynamiteModule: Considering local module
com.google.android.gms.googlecertificates:0 and remote module
com.google.android.gms.googlecertificates:4
Selected remote version of com.google.android.gms.googlecertificates, version >= 4 W/zygote64:
Skipping duplicate class check due to unrecognized classloader
I/zygote64: Do partial code cache collection, code=122KB, data=79KB
I/zygote64: After code cache collection, code=122KB, data=79KB
Increasing code cache capacity to 512KB I/zygote64: Compiler allocated 4MB to compile void
com.google.maps.api.android.lib6.gmm6.vector.bs.b(javax.microedition.khronos.opengles.GL10)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false I/System.out:
(HTTPLog)-Static: isSBSettingEnabled false V/InputMethodManager:
Starting input: tba=android.view.inputmethod.EditorInfo#b8feb38 nm :
com.a9831.sapires.samuel9831 ic=null I/InputMethodManager:
startInputInner - mService.startInputOrWindowGainedFocus
D/ViewRootImpl#82b5652[MapsActivity]: performDraw() was skipped by
AOD_SHOW_STATE... DisplayState=3 D/ViewRootImpl#82b5652[MapsActivity]:
MSG_WINDOW_FOCUS_CHANGED 0 D/OpenGLRenderer: eglDestroySurface =
0x7230f51fa0
The only RED error is:
E/zygote64: The String#value field is not present on Android versions >= 6.0
but the program dont stop and work but withou Markers.
Thks in advance

Android Bluetooth Discovery does not log anything

I have been working on an app which needs to find some discoverable Bluetooth devices. I have followed guides and looked at answers on here and followed. However I cannot seem to get the phone to start scanning.
Here is the full activity code:
public class MainActivity extends AppCompatActivity {
private TextView scanningText;
private ListView scanningListView;
private Button scanningButton;
boolean scanComplete;
private final static int REQUEST_ENABLE_BT = 1;
private ArrayList<String> mDeviceList;
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceList = new ArrayList<>();
scanningButton = (Button) findViewById(R.id.scanningButton);
scanningText = (TextView) findViewById(R.id.scanningText);
scanningListView = (ListView) findViewById(R.id.scanningList);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
scanningText.setText("Your device does not support Bluetooth, Sorry!");
}
else if (!mBluetoothAdapter.isEnabled()) {
scanningText.setText("You need to enable bluetooth to use this app..");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
scanningButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
scanningListView.setAdapter(new ArrayAdapter<>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
else {
Log.i("BT", "none"+ "");
}
}
};
}
When I check the android log console, there are no logs.
Thanks
Update:
I have moved startDiscovery to the onclick listener.
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
Log.i("found", pairedDevices + "");
}
The following check takes place when i press the scan button. I am told the device is not discovering by the toast.
scanningButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.isDiscovering();
Toast toast = Toast.makeText(getApplicationContext(), "discovering", Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(getApplicationContext(), "not discovering", Toast.LENGTH_LONG);
toast.show();
}
}
});
Entire Log:
06-14 14:50:13.356 25211-25211/? E/Zygote: v2
06-14 14:50:13.356 25211-25211/? I/libpersona: KNOX_SDCARD checking this for 10319
06-14 14:50:13.356 25211-25211/? I/libpersona: KNOX_SDCARD not a persona
06-14 14:50:13.357 25211-25211/? E/Zygote: accessInfo : 0
06-14 14:50:13.361 25211-25211/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[1], Con:u:r:zygote:s0 SPD:SEPF_SECMOBILE_7.0_0006 RAM:SEPF_SECMOBILE_7.0_0005, [-1 -1 0 1 0 1]
06-14 14:50:13.362 25211-25211/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.smartscan.app.smartscanapp
06-14 14:50:13.365 25211-25211/? I/art: Late-enabling -Xcheck:jni
06-14 14:50:13.408 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /data/app/com.smartscan.app.smartscanapp-2/lib/arm64
06-14 14:50:13.417 25211-25211/com.smartscan.app.smartscanapp I/InstantRun: Instant Run Runtime started. Android package is com.smartscan.app.smartscanapp, real application class is null.
06-14 14:50:13.607 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /data/app/com.smartscan.app.smartscanapp-2/lib/arm64
06-14 14:50:13.688 25211-25211/com.smartscan.app.smartscanapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-14 14:50:13.770 25211-25211/com.smartscan.app.smartscanapp I/found: [C1:20:21:40:9C:65, 8C:C8:CD:BB:95:28, C9:50:76:7B:89:F2, 54:53:ED:A3:B1:70, 88:A3:F2:BE:DE:42, C4:73:1E:02:1F:6B, E4:04:39:29:74:E6]
06-14 14:50:13.826 25211-25250/com.smartscan.app.smartscanapp I/OpenGLRenderer: Initialized EGL, version 1.4
06-14 14:50:13.880 25211-25211/com.smartscan.app.smartscanapp I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus
06-14 14:50:22.465 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /system/framework/QPerformance.jar
06-14 14:50:22.465 25211-25211/com.smartscan.app.smartscanapp E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
Try adding those permissions in the manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Also, it's always recommended to ask the user for permissions, so here you go :
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
You should start by adding logs at every steps.
Log.i("TAG", "Message")
Does your manifest file contains the appropriate permissions?
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Next, it seems like you do not check if the bluetooth is enabled on the device. You should use an intent to do so.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_BLUETOOTH);
}

Calling MediaRecorder crashes app in AndroidStudio

I am trying to create a class that sets and starts audio recording but as soon as I click the button the app crashes. Iv isolated the problem to where I set the parameters for the MediRecorder.
private void startRec() throws IOException {
if (mrecorder!=null)
mrecorder.release();
mrecorder= new MediaRecorder();
-> mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
/*
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrecorder.setOutputFile(MFILE);
mrecorder.prepare();
mrecorder.start();
*/
}
It crashes when the line with the arrow above the start of the notes is executed. I added the following permission to the manifest as well:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Any help much appreciated.
UPDATED LOGCAT
[ 05-12 00:39:13.299 30086:30158 D/ ]
ro.exynos.dss isEnabled: 0
05-12 00:39:13.309 30086-30158/record66.record6 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
05-12 00:39:13.319 30086-30086/record66.record6 W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
05-12 00:39:13.319 30086-30158/record66.record6 D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : record66.record6
05-12 00:39:13.359 30086-30086/record66.record6 D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
05-12 00:39:13.389 30086-30086/record66.record6 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#682466c time:234401322
05-12 00:39:15.749 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 0
05-12 00:39:15.879 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 1
05-12 00:39:15.929 30086-30086/record66.record6 D/AndroidRuntime: Shutting down VM
05-12 00:39:15.939 30086-30086/record66.record6 E/AndroidRuntime: FATAL EXCEPTION: main
Process: record66.record6, PID: 30086
java.lang.RuntimeException: setAudioSource failed.
at android.media.MediaRecorder._setAudioSource(Native Method)
at android.media.MediaRecorder.setAudioSource(MediaRecorder.java:488)
at record66.record6.MainActivity.startRec(MainActivity.java:58)
at record66.record6.MainActivity.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
05-12 00:39:17.909 30086-30086/record66.record6 I/Process: Sending signal. PID: 30086 SIG: 9
Please see what logcat is.
And let us know what error you are getting. So can help.
package com.example.dhrupalpatel.test;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity implements View.OnClickListener{
MediaRecorder mrecorder;
boolean mStartRecording=false;
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start =(Button)findViewById(R.id.start);
stop =(Button)findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
private void startRec() throws IOException {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
File sdCardDirectory= Environment
.getExternalStorageDirectory();
if(mExternalStorageAvailable && !sdCardDirectory.exists())
{
sdCardDirectory.mkdir();
}
File f= new File(sdCardDirectory.getPath()+"/"+System.currentTimeMillis()+".mp3");
if( mrecorder == null ) {
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setOutputFile(f.getPath());
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if(!mStartRecording) {
try {
mrecorder.prepare();
mrecorder.start();
mStartRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRec() throws IOException {
if(mStartRecording) {
mStartRecording = false;
mrecorder.stop();
mrecorder.reset();
mrecorder.release();
mrecorder = null;
}
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.start:
try {
startRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stop:
try {
stopRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}

GCM with sample android testapp for push notification

I have been trying to learn how to use the GCM by going over their step by step guild. I get to the point of registering but it never actually does the registration part of the project. I have the configuration file in the project and I am using this website to test for push notification http://www.androidbegin.com/tutorial/gcm.html
So this is what it is giving me in the logcat:
02-18 14:07:42.866 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Main Activity: Started
02-18 14:07:42.867 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Checking PlayService: Started
02-18 14:07:42.868 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Cheking player Service: true
02-18 14:07:42.868 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Starting service:: Intent { cmp=com.example.mmillar.gcmpushnotificationtest/.Registration }
02-18 14:07:42.877 32402-32432/com.example.mmillar.gcmpushnotificationtest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-18 14:07:42.949 32402-32432/com.example.mmillar.gcmpushnotificationtest I/OpenGLRenderer: Initialized EGL, version 1.4
02-18 14:07:43.008 32402-32432/com.example.mmillar.gcmpushnotificationtest W/EGL_emulation: eglSurfaceAttrib not implemented
02-18 14:07:43.008 32402-32432/com.example.mmillar.gcmpushnotificationtest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad79f100, error=EGL_SUCCESS
02-18 14:07:45.679 32402-32407/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 12.876ms
02-18 14:07:53.143 32402-32429/com.example.mmillar.gcmpushnotificationtest I/GMPM: Tag Manager is not found and thus will not be used
02-18 14:08:33.167 32402-32411/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 5.121ms
02-18 14:10:19.493 32402-32407/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 6.036ms
02-18 14:11:15.635 32402-32407/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 12.898ms
As it shows it get down to the start(intent0 part of the onCreate method. But it never reaches to the Register class at all. I am a bit stumped on what I am doing wrong here. Any help will be appreciated.
here is the main activity code that starts the app
public class GCMMainActivity extends AppCompatActivity{
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "MainActivity";
private BroadcastReceiver mRegistrationBroadcastReceiver;
private ProgressBar mRegistrationProgressBar;
private TextView mInformationTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gcmmain);
Log.d("Main Activity", "Started");
mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Main Activity: ", "onReceive Method");
mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences.getBoolean(Preferences.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
mInformationTextView.setText("Token retrieved and sent to server! You can now use gcmsender to\n" +
" send downstream messages to this app");
} else {
mInformationTextView.setText("An error occurred while either fetching the InstanceID token,\n" +
"sending the fetched token to the server or subscribing to the PubSub topic. ");
}
}
};
mInformationTextView = (TextView) findViewById(R.id.informationTextView);
if (checkPlayServices()) {
Log.d("Checking PlayService", "Started");
Boolean check = checkPlayServices();
Log.d("Cheking player Service ", check.toString());
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, Registration.class);
//this should call the registration code
Log.d("Starting service: ", intent.toString());
startService(intent);
}
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Preferences.REGISTRATION_COMPLETE));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
//deos the device support google play?
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
And this is the registration class
public class Registration extends IntentService {
private static final String TAG = "RegIntentService";
private static final String[] TOPICS = {"global"};
private final String SENDERID = "630172590481";
public Registration() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Registration Class: ", "onHandleIntent mehtod");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//Register for the gcm
try {
// Initially this call goes out to the network to retrieve the token, subsequent calls
// are local.
InstanceID instanceID = InstanceID.getInstance(this);
//this is using the google configuration file crated at their website
//https://developers.google.com/cloud-messaging/android/start
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
/*used to hardcode the Sender ID
String token = instanceID.getToken(SENDERID),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
*/
Log.d(TAG, "GCM Registration Token: " + token);
sendRegistrationToServer(token);
// Subscribe to topic channels
subscribeTopics(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, true).apply();
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// update at a later time.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Preferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
//Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
private void subscribeTopics(String token) throws IOException {
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
}

Categories