I'm trying to make an app that blocks calls with ITelephony depending on which radio button is pressed in my main activity. However, my onReceive method never gets called and therefore, doesn't block the call.
Here is my class that extends BroadcastReceiver
public class CallBlocking extends BroadcastReceiver {
private static final int MODE_WORLD_READABLE = 1;
private String mPhoneNumber;
private String mCallerName;
private SharedPreferences mPreferences;
#Override
public void onReceive(Context context, Intent intent) {
mPreferences = context.getSharedPreferences("mPreferences", MODE_WORLD_READABLE);
String blockMode = mPreferences.getString("mode", "not retrieved");
if (!blockMode.equals("cancel")) {
Bundle b = intent.getExtras();
String phoneState = b.getString(TelephonyManager.EXTRA_STATE);
if ((phoneState.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))) {
mPhoneNumber = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (blockMode.equals("all")) {
disconnect(context);
} else if (blockMode.equals("unsaved")) {
mCallerName = getContactName( mPhoneNumber, context);
if((mCallerName == null) || (mCallerName.length() < 2))
disconnect(context);
else if (blockMode.equals("list"))
{
if(CallBlockerFragment.sBlockedList.contains(new BlockedList(mPhoneNumber)))
disconnect(context);
}
}
}
}
}
#SuppressWarnings({"rawtypes", "unchecked"})
private void disconnect(Context context) {
ITelephony telephonyService;
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getContactName(String phoneNumber, Context context) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String callerName = "?";
String data = null;
ContentResolver contentResolver = context.getContentResolver();
Cursor findContact = contentResolver.query(uri, new String[] {BaseColumns._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
try {
if (findContact != null && findContact.getCount() > 0) {
findContact.moveToNext();
data = findContact.getString((findContact.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));
}
}
finally
{
if(findContact != null)
findContact.close();
}
return data;
}
}
and here is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.uwp.sean.pike.csci323.callblocker">
<application
android:allowBackup="true"
android:icon="#drawable/quevedo"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".CallBlockerActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".AddToBlockedListActivity">
android:label="#string/app_name"
android:parentActivityName=".CallBlockerActivity">
</activity>
<activity
android:name=".BlockedListActivity">
android:label="#string/app_name"
android:parentActivityName=".CallBlockerActivity">
</activity>
<receiver android:name=".CallBlocking">
<intent-filter android:priority="100" >
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
</manifest>
Why isn't it calling the onReceive method?
maybe what you would like to achieve is to listen for phone state changes...please check out the following link Listen to Change of Phone State State - Android
Related
I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.
I have an android application and I have a receiver from WakefulBroadcastReceiver which is never called.
I put a breakpoint on the AlaramReceiver.java and never stepped into.
I checked the case and how it spelled the receiver class name.
I will add my manifest and the java classes linked.
Thank for your help.
Manifest :
<receiver android:name="fr.cls.mobility.myclsdroiddata.service.android.OnAlarmReceiver_">
AlarmReceiver_.class :
public final class OnAlarmReceiver_
extends OnAlarmReceiver
{
}
AlamarReceiver.java :
#EReceiver
public class OnAlarmReceiver extends WakefulBroadcastReceiver {
private static final String LOG_MESSAGE_ON_RECEIVE = "startWakefulService with context and DataDownloadIntentServiceFactory.getIntentAlarmReceived";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(OnAlarmReceiver.class.getSimpleName(), LOG_MESSAGE_ON_RECEIVE);
startWakefulService(context, DataDownloadIntentServiceFactory.getIntentAlarmReceived(context, null));
}
}
DataDownloadIntentServiceFactory.java :
package fr.cls.mobility.myclsdroiddata.service.android;
import com.effitic.delegates.Action;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.os.ResultReceiver;
/**
* Cette classe crée les différents services Android de mise à jour des positions. <br>
* <br>
* Copyright : Copyright (c) 2013 <br>
* <br>
* Société : CLS (Collecte Localisation Satellites)
*
* #author Effitic
* #version Revision: 1.1.0.02 - Date: 2014-01-15
*/
public final class DataDownloadIntentServiceFactory {
/**
* Constructeur.
*/
private DataDownloadIntentServiceFactory() {
super();
}
public static Intent getIntentNetworkStateChanged(Context context, boolean networkAvailable) {
Intent dataDownloadIntentService = createIntent(context, null, DataDownloadIntentService.NETWORK_STATE_CHANGED);
dataDownloadIntentService.putExtra(DataDownloadIntentService.NETWORK_STATE_CHANGED, networkAvailable);
return dataDownloadIntentService;
}
private static Intent createIntent(Context context, ResultReceiver resultReceiver, String type) {
Intent dataDownloadIntentService = DataDownloadIntentService_.intent(context).get();
dataDownloadIntentService.putExtra(DataDownloadIntentService.TYPE, type);
dataDownloadIntentService.putExtra(DataDownloadIntentService.RESULT_RECEIVER, resultReceiver);
return dataDownloadIntentService;
}
public static Intent getIntentAlarmReceived(Context context, final Action<Object> refreshFinishedHandler) {
ResultReceiver resultReceiver = new ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, android.os.Bundle resultData) {
if (refreshFinishedHandler != null) {
refreshFinishedHandler.execute(null);
}
};
};
Intent dataDownloadIntentService = createIntent(context, resultReceiver, DataDownloadIntentService.ALARM_RECEIVED);
return dataDownloadIntentService;
}
public static Intent getIntentRefresh(Context context, final Action<Object> refreshFinishedHandler) {
ResultReceiver resultReceiver = new ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, android.os.Bundle resultData) {
if (refreshFinishedHandler != null) {
refreshFinishedHandler.execute(null);
}
};
};
Intent dataDownloadIntentService = createIntent(context, resultReceiver, DataDownloadIntentService.REFRESH);
return dataDownloadIntentService;
}
public static Intent getIntentBootCompleteReceived(Context context) {
Intent dataDownloadIntentService = createIntent(context, null, DataDownloadIntentService.BOOT_COMPLETE_RECEIVED);
return dataDownloadIntentService;
}
public static <T extends ResultReceiver> T getResultReceiverFromIntent(Intent intent, Class<T> clazz) {
Parcelable o = intent.getParcelableExtra(DataDownloadIntentService.RESULT_RECEIVER);
if (clazz.isInstance(o)) {
return clazz.cast(o);
}
return null;
}
}
my manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="51" android:versionName="1.3.01-SNAPSHOT" package="fr.cls.mobility.myclsdroiddata">
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="14"/>
<!-- permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- pour le stockages des tuiles de carto -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application android:allowBackup="false" android:debuggable="true" android:icon="#drawable/notif" android:label="#string/app_name" android:name="fr.cls.mobility.myclsdroiddata.view.application.CLSApplication_" android:theme="#style/AppTheme2">
<activity android:configChanges="keyboardHidden|orientation|screenSize" android:hardwareAccelerated="false" android:label="#string/app_name" android:launchMode="singleTop" android:name="fr.cls.mobility.myclsdroiddata.view.activity.MapViewActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:configChanges="keyboardHidden|orientation|screenSize" android:name="fr.cls.mobility.myclsdroiddata.view.activity.PanelFragmentActivity" android:windowSoftInputMode="stateHidden"/>
<service android:name="fr.cls.mobility.myclsdroiddata.service.android.DataDownloadIntentService_"/>
<receiver android:name="fr.cls.mobility.myclsdroiddata.service.android.OnBootReceiver_">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<receiver android:name="fr.cls.mobility.myclsdroiddata.service.android.OnNetworkStateChangedReceiver_">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
<receiver android:name="fr.cls.mobility.myclsdroiddata.service.android.OnAlarmReceiver_"/>
</application>
</manifest>
You have not specified the intent filter for the receiver in manifest. Without the intent filter it does not know when to trigger or otherwise you need to invoke it explicitly
<receiver android:name="fr.cls.mobility.myclsdroiddata.service.android.OnAlarmReceiver" >
<intent-filter>
<action android:name="android.intent.action.YOUR_INTENT_ACTION" />
<!--If you want to watch network connectivity state-->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
otherwise you have to invoke it explicitly
Intent intent = new Intent(getApplicationContext(), fr.cls.mobility.myclsdroiddata.service.android.OnAlarmReceiver.class);
sendBroadcast(intent);`
In my PlanifyAlarmHandler
I had :
Intent alarmIntent = new Intent();
alarmIntent.setClassName("fr.cls.mobility.service.android", "OnAlarmReceiver_");
instead of
Intent alarmIntent = new Intent(context, OnAlarmReceiver_.class);
Now it's working.
Thanks for all your answers.
I've rooted Nexus phone with lollipop. I'm trying to record incoming & outgoing calls.
My application extends DeviceAdminReceiver with policy of <force-lock />
I'm able to create the file with size > 0bytes. But when I play it, it is blank.
Please take a look at the code below:
Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.STORAGE" />
.....
<service android:name=".RCService"
android:exported="false" >
</service>
.....
<receiver
android:name=".utils.MyDeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN" >
<intent-filter>
<!-- This action is required -->
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
<action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
</intent-filter>
<!-- This is required this receiver to become device admin component. -->
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/device_admin" />
</receiver>
<receiver android:name=".CallRecoderBroadcast">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
device_admin.xml
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
CallRecoderBroadcast.java
/**
* Lifecycle :
* Incoming call : RINGING -> OFFHOOK -> IDLE
* Outgoing Call : OFFHOOK -> IDLE
*/
public class CallRecoderBroadcast extends BroadcastReceiver {
private static final String TAG = "CallRecoderBroadcast";
private static final String ACTION_PHONE = "android.intent.action.PHONE_STATE";
private static final String OUTGOING_CALL = "android.intent.action.NEW_OUTGOING_CALL";
private static Boolean mCallOnGoing = Boolean.FALSE;
private MediaRecorder mRecorder = new MediaRecorder();
// private File mFile = null;
private String mNumber;
#Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals(ACTION_PHONE)) {
Bundle bundle = intent.getExtras();
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
Log.e(TAG, state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Log.e(TAG, bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER));
mNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
if (!mCallOnGoing) {
recordCall(context);
}
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
if (mCallOnGoing) {
stopRecording();
}
}
} else if (intent.getAction().equals(OUTGOING_CALL)) {
Log.e(TAG, "OUTGOING cALL");
Log.e(TAG, intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
mNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
private void recordCall(Context context) throws IOException, CustomExcpetion {
File file = prepareFile(context);
if (file.exists()) {
mCallOnGoing = Boolean.TRUE;
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(file.getAbsolutePath());
mRecorder.prepare();
mRecorder.start();
}
}
private void stopRecording() {
mCallOnGoing = Boolean.FALSE;
// mRecorder.stop();
mRecorder.release();
}
private File prepareFile(Context context) throws CustomExcpetion {
File outputFile = null;
try {
File dir = new File(context.getFilesDir(), "recorderdFiles");
if (!dir.exists()) {
dir.mkdirs();
}
Long timeStamp = System.currentTimeMillis();
outputFile = new File(dir, timeStamp.toString());
if (!outputFile.exists()) {
outputFile.createNewFile();
}
} catch (IOException exp) {
throw new CustomExcpetion(context, exp);
}
return outputFile;
}
}
P.S. - I've also tried with example given here, but it only working form Mic & not for uplink & downlink at the same time.
Unfortunately, voice call recorder is not supported on that device,
I think that will work fine on other devices.
I have tried to simplify my code as much as possible, basically hte issue is that the ActivityRecognitionIntentService appears to be called a couple of times, then stalls out. It appears to be related to the requestCode in the PendingIntent, but I am not sure, can someone please advise me as to what is going wrong? Thanks.
Dashboard.java
public class Dashboard extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private BroadcastReceiver receiver;
private TextView tvActivity;
private GoogleApiClient mGoogleApiClient;
//String Locationp = "null";
//private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
tvActivity = (TextView) findViewById(R.id.tvActivity);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
// Create a GoogleApiClient instance
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
//.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle arg0) {
Intent i = new Intent(this, ActivityRecognitionIntentService.class);
PendingIntent mActivityRecognitionPendingIntent = PendingIntent.getService(this, 2000, i, PendingIntent.FLAG_UPDATE_CURRENT);
Log.e("MAIN", "Connected to ActRec");
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mGoogleApiClient, 1000, mActivityRecognitionPendingIntent);
}
#Override
public void onConnectionSuspended(int arg0) {
Log.e("MAIN", "Connection suspended to ActRec");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("MAIN", "Not Connected to ActRec");
}
ActivityRecognitionIntentService.java
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
DetectedActivity mostProbAct = result.getMostProbableActivity();
int confidence = mostProbAct.getConfidence();
String mostProbActName = getActivityName(mostProbAct.getType());
Intent i = new Intent("com.xxx.abc.ACTIVITY_RECOGNITION_DATA");
i.putExtra("act", mostProbActName);
i.putExtra("confidence", confidence);
Log.e("ARS", mostProbActName + "," + confidence);
//sendBroadcast(i);
} else
Log.e("ARS", "Intent had no ActivityRecognitionData");
}
private String getActivityName(int activityType) {
switch (activityType) {
case DetectedActivity.IN_VEHICLE:
return "in_vehicle";
case DetectedActivity.ON_BICYCLE:
return "on_bicycle";
case DetectedActivity.ON_FOOT:
return "on_foot";
case DetectedActivity.STILL:
return "still";
case DetectedActivity.UNKNOWN:
return "unknown";
case DetectedActivity.TILTING:
return "tilting";
}
return "unknown";
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tigerblood.com.node" >
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<service android:enabled="true" android:name="com.xxx.abc.ActivityRecognitionIntentService"></service>
<activity
android:name="com.tigerblood.node.Dashboard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I cant get registration ID for all the devices.
The manifest is good and i add all premission.
the Sender_ID is good.
the device has an account logged in. (Google account).
the code below is the activity which handles with the GCM device register.
Please help me!
public class ClientRegisterActivity extends Activity {
private static final String SENDER_ID = "*******";
private Client client = null;
private GoogleCloudMessaging gcm;
TextView tvHeader;
EditText etEmail;
EditText etPass;
EditText etPassConf;
EditText etFname;
EditText etLname;
EditText etPhone;
// Spinner spWorkArea;
Button bReg;
// Variables used for conversion into database
String fName;
String lName;
String email;
String password;
String phone;
// String workArea;
String regId = "";
String rg;
MyGCMBroadcastReceiver myReci;
// SQLLiteData entry = new SQLLiteData(RegisterActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_activity_register);
initialize();
}
private void initialize() {
tvHeader = (TextView) findViewById(R.id.ctvHeader);
etEmail = (EditText) findViewById(R.id.cemail);
etPass = (EditText) findViewById(R.id.cpassword);
etPassConf = (EditText) findViewById(R.id.cpassword_confirm);
etFname = (EditText) findViewById(R.id.cfirst_name);
etLname = (EditText) findViewById(R.id.clast_name);
etPhone = (EditText) findViewById(R.id.cetPhone);
// spWorkArea = (Spinner) findViewById(R.id.cspWorkArea);
bReg = (Button) findViewById(R.id.cbRegister);
regId="";
// Avoiding NullPointerException in checks
etEmail.setText("");
etPass.setText("");
etPassConf.setText("");
etFname.setText("");
etLname.setText("");
etPhone.setText("");
myReci=new MyGCMBroadcastReceiver();
registerReceiver(myReci,new IntentFilter("com.avshalom.ilani.easymovers.DISPLAY_MESSAGE_ACTION"));
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean didItWork;
registerInBackground();
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
}
else
setContentView(R.layout.client_activity_register);
Log.d("Text", "kobi: regId = " + regId);
Gson gson = new Gson();
client = new Client();
SendHttpRequest snd = new SendHttpRequest((etFname.getText()
.toString()), etLname.getText().toString(), etEmail
.getText().toString(), etPass.getText().toString(),
etPhone.getText().toString(), regId.toString());
snd.start();
// HttpResponse
// response=SendHttpRequest.SendLogin(etFname.getText().toString(),etLname.getText().toString(),etEmail.getText().toString(),etPass.getText().toString(),etPhone.getText().toString(),
// regId.toString());
Log.d("Text", "kobi: after httpresponse");
// client = gson.fromJson(reader, Client.class);
Toast.makeText(ClientRegisterActivity.this,
client.getFirstName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.register, menu);
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
// while(regId=="")
rg = gcm.register(SENDER_ID);
regId=rg;
msg = "Device registered, registration ID=" + regId;
System.out.println(msg);
Log.d("Text", msg);
Log.d("Text", "kobi: " + regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
}
register activity after onpreexecute:
bReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//boolean didItWork;
registerInBackground();
/*
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
}
else
setContentView(R.layout.client_activity_register); */
Log.d("Text", "kobi: regId = " + regId);
Gson gson = new Gson();
client = new Client();
SendHttpRequest snd = new SendHttpRequest((etFname.getText()
.toString()), etLname.getText().toString(), etEmail
.getText().toString(), etPass.getText().toString(),
etPhone.getText().toString(), regId.toString());
snd.start();
// HttpResponse
// response=SendHttpRequest.SendLogin(etFname.getText().toString(),etLname.getText().toString(),etEmail.getText().toString(),etPass.getText().toString(),etPhone.getText().toString(),
// regId.toString());
Log.d("Text", "kobi: after httpresponse");
// client = gson.fromJson(reader, Client.class);
Toast.makeText(ClientRegisterActivity.this,
client.getFirstName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.register, menu);
return true;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
}
// while(regId=="")
rg = gcm.register(SENDER_ID);
regId=rg;
msg = "Device registered, registration ID=" + regId;
System.out.println(msg);
Log.d("Text", msg);
Log.d("Text", "kobi: " + regId);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
boolean didItWork;
if (everythingOK()) {
// fName, lName, email, password have been updated in check
// function
// Write details in DB and continue to main screen / show
// confirmation message
if (!regId.equals(null))
didItWork = true;
// not null ?
else
setContentView(R.layout.client_activity_register);
}
}
}.execute(null, null, null);
}
Here is the Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avshalom.ilani.easymovers"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<!-- For receiving messaged from the GCM -->
<permission
android:name="com.avshalom.ilani.easymovers.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.avshalom.ilani.easymovers.permission.C2D_MESSAGE" />
<!-- For receiving messaged from the GCM -->
<!-- For receiving the GCM messages -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- For accessing the internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- For google accounts -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- When receiving a message, to keep the device awake -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.avshalom.ilani.easymovers.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.Choose"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.ClientRegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.offers.tabs"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.avshalom.ilani.easymovers.MoverRegisterActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<receiver
android:name="com.avshalom.ilani.easymovers.MyGCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.avshalom.ilani.easymovers" />
</intent-filter>
</receiver>
<service android:name="com.avshalom.ilani.easymovers.GCMIntentService" />
</application>
</manifest>