Not able to record call using MediaRecorder - java

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.

Related

No auth token firebase storage android

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.

Android broadcast reciever called but doesn't starts foreground service

I set up broadcast reciever for restarting my foreground service after reboot.
I have two devices and it works on Meizu M1 note (android 5.1) but doesn't work on Samsung A8 (android 9). Looking for reason in restrictions after Oreo and seems like it ok, but just in case https://developer.android.com/about/versions/oreo/background.html
On the second one broadcast reciever called, but service not started after reboot.
Service tracks location and uses startForeground() with Notification for correct work.
Also tried to add Worker to restart service after reboot, but seems like work missing after that.
Please, geve any suggestions why my reciever doesn't run service.
Thanks.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tracker">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".ui.di.App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:isolatedProcess="true"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name="com.example.tracker.ui.broadcast.ServiceRestart">
<intent-filter>
<action android:name="restartService" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name="com.example.tracker.ui.service.TrackerService"
android:enabled="true" />
<service
android:name="com.example.tracker.ui.worker.RestartIntentService"
android:enabled="true" />
<activity android:name=".ui.screen.main.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Reciever:
public class ServiceRestart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Broadcast: ServiceRestart launched " + intent.getAction(), Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, TrackerService.class));
} else {
context.startService(new Intent(context, TrackerService.class));
}
}
}
Service:
public class TrackerService extends Service implements LocationListener {
public static final String TAG = "TrackerService";
private static final int PROCESS_ID = 1024;
private static final int INTERVAL = 120; //seconds
private ConnectivityManager connectivityManager;
private PeriodicWorkRequest workRequest;
private PeriodicWorkRequest restartTrackerRequest;
private DbFirebaseModel dbFirebaseModel = new DbFirebaseModel();
private ServiceHandler mServiceHandler;
private static final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message message) {
}
}
public void onCreate() {
super.onCreate();
HandlerThread mHandlerThread = new HandlerThread("TrackerService.HandlerThread");
mHandlerThread.start();
mServiceHandler = new ServiceHandler(mHandlerThread.getLooper());
}
public TrackerService() {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
addNotificationAndStartForeground();
addWorkers();
mServiceHandler.post(() -> {
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
runLocationTransfer();
});
Log.d(TAG, "===== SERVICE START");
return START_STICKY;
}
private void addWorkers() {
workRequest = new PeriodicWorkRequest.Builder(
FirebaseWorker.class, 15, TimeUnit.MINUTES, 2, TimeUnit.MINUTES)
.build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
FirebaseWorker.TAG,
ExistingPeriodicWorkPolicy.REPLACE,
workRequest);
restartTrackerRequest = new PeriodicWorkRequest.Builder(
TrackerRestartWorker.class, 15, TimeUnit.MINUTES, 2, TimeUnit.MINUTES
).build();
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
TrackerRestartWorker.TAG,
ExistingPeriodicWorkPolicy.REPLACE,
restartTrackerRequest);
}
private void addNotificationAndStartForeground() {
String name = getString(R.string.app_name);
String description = "Service running...";
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
Integer.toString(PROCESS_ID), "Tracker", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Notify me when location tracking");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
notificationBuilder = new Notification.Builder(this, Integer.toString(PROCESS_ID));
notificationBuilder.setContentTitle(name)
.setContentText(description)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent);
notificationManager.notify(PROCESS_ID, notificationBuilder.build());
} else {
notificationBuilder = new Notification.Builder(this);
notificationBuilder.setContentTitle(name)
.setContentText(description)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent);
}
startForeground(PROCESS_ID, notificationBuilder.build());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "===== SERVICE STOP");
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
WorkManager.getInstance(this).cancelWorkById(workRequest.getId());
WorkManager.getInstance(this).cancelWorkById(restartTrackerRequest.getId());
Log.d(TAG, "===== WORKERS STOP");
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.d(TAG, "TASK REMOVED");
Toast.makeText(this, "LOCATION TASK REMOVED", Toast.LENGTH_SHORT).show();
super.onTaskRemoved(rootIntent);
}
private void runLocationTransfer() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
locationRequest.setInterval(INTERVAL * 1000);
locationRequest.setFastestInterval(INTERVAL * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
try {
getFusedLocationProviderClient(this).requestLocationUpdates(locationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(#NonNull Location location) {
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
stopSelf();
Log.d(TAG, "====== SERVICE STOPPED by itself");
} else if (connectivityManager.getActiveNetworkInfo() != null
&& connectivityManager.getActiveNetworkInfo().isConnected()) {
dbFirebaseModel.saveLocation(location);
// test using sound notifications
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "LOCATION ------ LATITUDE: " + location.getLatitude() + " LONGITUDE: " + location.getLongitude(), Toast.LENGTH_SHORT).show();
} else {
saveToLocalStorage(location);
}
}
private void saveToLocalStorage(Location location) {
Hawk.init(this).build();
String userId = Objects.requireNonNull(
FirebaseAuth.getInstance().getCurrentUser()
).getUid();
LocationData locationData = new LocationData(userId, location);
long count = 0;
if (Hawk.count() > count) {
count = Hawk.count();
}
while (Hawk.contains(String.valueOf(count))) {
count++;
}
Hawk.put(String.valueOf(count), locationData);
Log.d(TAG, "HAWK /// Saved to local storage. COUNT = " + Hawk.count());
}
}
Following steps helped me solve it:
Remove and reinstall app
Change manifest according to this
<receiver android:name="com.foxminded.tracker.ui.broadcast.ServiceRestart"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="restartService" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Here added "android.intent.action.LOCKED_BOOT_COMPLETED" and android:exported="true" android:enabled="true"

BroadcastReceiver won't call onReceive method

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

Unable to instantiate service java.lang.NullPointerException

I'm trying to make a mini yamba.newcircle.com from my Android project training. I'm saving text messages when the Internet is not available, and with connectivity broadcast receiver if the Internet is up. This app automatically starts a service that loops to push all saved text rows in ActiveAndroid from a table, via HTTP posts to the web API.
When I turn Wifi off, save some messages with ActiveAndroid, and turn Wifi back on; if my app connects, it simply crashes with NullPointereException.
Any suggestions?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pt.flag.miniyamba" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="MiniYamba"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<meta-data
android:name="AA_DB_NAME"
android:value="yamba.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="5" />
<activity android:name=".Main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OnlineStatus" >
</activity>
<activity android:name=".OfflineStatus" >
</activity>
<activity android:name=".SingleStatus" >
</activity>
<activity android:name=".NewStatus" >
</activity>
<receiver android:name=".NetworkBroadCastReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
</intent-filter>
</receiver>
<service android:name=".PushOfflineSavedService"/>
</application>
</manifest>
broacast
public class NetworkBroadCastReceiver extends BroadcastReceiver {
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = manager.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnectedOrConnecting()){
Toast.makeText(context, "net is up, pushing our previous offline saved posts ", Toast.LENGTH_SHORT).show();
//inicializar o servico de push de posts, guardados anteriormente
Intent novointent = new Intent(context, PushOfflineSavedService.class);
context.startService(novointent);
}
//mudou de conectividade, mas nao tem internet
else{
Toast.makeText(context, "Connectivity is changed. Internet seens not working.", Toast.LENGTH_SHORT).show();
}
}
}
intentservice
public class PushOfflineSavedService extends IntentService {
private String LOG_TAG;
public PushOfflineSavedService() {
super("PushOfflineSavedService");
ActiveAndroid.initialize(this);
}
#Override
protected void onHandleIntent(Intent intent) {
//enviar os status guardados, por enviar
List<OfflinePostToSend> lista = new Select().from(OfflinePostToSend.class).execute();
//loop para enviar os status
if (lista.size() > 0) {
for (int i = 0; i < lista.size(); i++) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
String path = "http://yamba.newcircle.com/api/statuses/update.json";
String status = lista.get(i).getText();
URL url = new URL(path);
String userPass = "student:password";
String token = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.NO_WRAP);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
// Adicionar o token como header do pedido
urlConnection.addRequestProperty("Authorization", token);
urlConnection.setDoOutput(true);
String postParameters = "status="+status;
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Adicionar o status ao método post
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();
reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(urlConnection.getInputStream())));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
//se buffer nao for full, temos 1 respota do API
if (buffer.length() != 0) {
// Stream was NOT empty.
//apagar este elemento da lista e da db
lista.get(i).delete();
}
//return buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
}
}
}
}
The ActiveAndroid guide shows the call to initialize() in an Application subclass, like this:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ActiveAndroid.initialize(this);
}
}
Try extending Application and putting your initialize() call there instead of in the service.

Can't get GCM register ID client side android

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>

Categories

Resources