Change Class After Notification Is Clicked Android - java

I am trying to change my class to to go to Login.java I have tried numerous solutions but can't seem to get it. I have a PromximityAlert set-up to check location and after that location is confirmed it will display the notification and when that notification is clicked, it will initiate the Login class.
Here is my code:
public class ProxAlertActivity extends Activity {
private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000; // in Milliseconds
private static final long POINT_RADIUS = 1000; // in Meters
private static final long PROX_ALERT_EXPIRATION = -1;
private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY";
private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY";
private static final String PROX_ALERT_INTENT = "com.example.mysqltest.ProximityAlert";
private static final NumberFormat nf = new DecimalFormat("##.########");
private LocationManager locationManager;
private EditText latitudeEditText;
private EditText longitudeEditText;
private Button findCoordinatesButton;
private Button savePointButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
new MyLocationListener()
);
latitudeEditText = (EditText) findViewById(R.id.point_latitude);
longitudeEditText = (EditText) findViewById(R.id.point_longitude);
findCoordinatesButton = (Button) findViewById(R.id.find_coordinates_button);
savePointButton = (Button) findViewById(R.id.save_point_button);
findCoordinatesButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
populateCoordinatesFromLastKnownLocation();
}
});
savePointButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveProximityAlertPoint();
}
});
}
private void saveProximityAlertPoint() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location==null) {
Toast.makeText(this, "No last known location. Aborting...", Toast.LENGTH_LONG).show();
return;
}
saveCoordinatesInPreferences((float)location.getLatitude(), (float)location.getLongitude());
addProximityAlert(location.getLatitude(), location.getLongitude());
}
private void addProximityAlert(double latitude, double longitude) {
Intent intent = new Intent(PROX_ALERT_INTENT);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(
41.69519672, // the latitude of the central point of the alert region
-87.80026184, // the longitude of the central point of the alert region
POINT_RADIUS, // the radius of the central point of the alert region, in meters
PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
registerReceiver(new ProximityIntentReceiver(), filter);
}
private void populateCoordinatesFromLastKnownLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null) {
latitudeEditText.setText(nf.format(location.getLatitude()));
longitudeEditText.setText(nf.format(location.getLongitude()));
}
}
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude);
prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude);
prefsEditor.commit();
}
private Location retrievelocationFromPreferences() {
SharedPreferences prefs = this.getSharedPreferences(getClass().getSimpleName(), Context.MODE_PRIVATE);
Location location = new Location("POINT_LOCATION");
location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY, 0));
location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY, 0));
return location;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
Location pointLocation = retrievelocationFromPreferences();
float distance = location.distanceTo(pointLocation);
Toast.makeText(ProxAlertActivity.this,
"Distance from Point:"+distance, Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
}
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
#Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}
else {
Log.d(getClass().getSimpleName(), "exiting");
}
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!", "You are near your point of interest.", pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_menu_notifications;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}

Add this , I think its missing
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setContentIntent(pendingIntent );

Related

android - locationManager stops proving updates

I am making a tracking app, which has a service getting location updates and storing them into a database. And activity gets notified and retrieves location data from the DB.
The problem is that all works fine what the activity is running, yet when the activity is not in the foreground, service gets a few more locations and stops updating.
Once I open the activity, the updates continue.
I have checked, the service itself is running, I could add a countdown timer adding random numbers to the DB and it continues working. What do you think might be causing the location to stop updating?...
public class ServiceClass extends Service implements NavigationView.OnNavigationItemSelectedListener{
IBinder binder; // interface for clients that bind
boolean allowRebind; // indicates whether onRebind should be used
Notification notification;
MediaPlayer mp;
SharedPreferences sharedPreferences;
SharedPreferences.Editor spEdit;
LocationManager locationManager;
Context mContext;
ArrayList<CameraClass> camList = new ArrayList<CameraClass>();
Double carSpeed = 0.0;
int distance_to_nearest_radar = 999999;
boolean alarm = false;
int speedLimit = 100;
float bearing = 0;
Box<CoordinatePoint> cpBox;
Location loc;
Location locTemp;
#Override
public void onCreate() {
mContext = this;
mp = MediaPlayer.create(this, R.raw.beep01);
mp.setLooping(true);
BoxStore bs = ObjectBoxSingleton.get();
cpBox = bs.boxFor(CoordinatePoint.class);
Toast.makeText(this,"Service STARTED",Toast.LENGTH_SHORT).show();
loadCSV ( getResources().openRawResource(R.raw.radar_map));
}
/////////////////////////////////////////////////////////////////////////////////////////
#SuppressLint("MissingPermission")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, locationListenerGPS);
Intent intent_recallActivity = new Intent(getApplicationContext(), MapsActivity.class);
intent_recallActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ServiceClass.this, 0, intent_recallActivity, 0);
notification = new NotificationCompat.Builder(this, "nc01")
.setContentTitle("RADAR AHEAD!")
.setContentText("Waiting for GPS signal...")
.setSmallIcon(R.drawable.ic_nogps_notification)
.build();
startForeground(1, notification);
return START_STICKY;
}
/////////////////////////////////////////////////////////////////////////////////////////
LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(android.location.Location location) {
Log.e("GPS","NEW POINT!");
Toast.makeText(mContext,"NEW POINT",Toast.LENGTH_SHORT).show();
CoordinatePoint cp = new CoordinatePoint();
cp.latPoint = location.getLatitude();
cp.lonPoint = location.getLongitude();
cpBox.put(cp);
carSpeed = roundUp(Double.parseDouble(String.valueOf(location.getSpeed()))*3.6 , 1 );
checkForRadars();
updateNotification();
}
};
/////////////////////////////////////////////////////////////////////////////////////////
private void updateNotification() {
Intent intent_recallActivity = new Intent(getApplicationContext(), MapsActivity.class);
intent_recallActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ServiceClass.this, 0, intent_recallActivity, 0);
String a = "ACTIVITY ON PAUSE";
if ( isActivityRunningInForeground() )
{
a ="ACTIVITY RUNNING";
sendMessageToActivity();
}
notification = new NotificationCompat.Builder(this, "nc01")
.setContentTitle(a + ", objBox: " + String.valueOf( cpBox.count() ) )
.setContentText( "Speed: " + String.valueOf(carSpeed) + " km/h | Radar in: "
+ String.valueOf( roundUp( (double)distance_to_nearest_radar/1000, 2) )+" km " )
.setSmallIcon(R.drawable.ic_radar_notification)
.build();
startForeground(1, notification);
}
/////////////////////////////////////////////////////////////////////////////////////////
private void sendMessageToActivity() {
Intent intent = new Intent("GPSLocationUpdates");
intent.putExtra("carSpeed", Double.valueOf(carSpeed) );
intent.putExtra("distance_to_nearest_radar", distance_to_nearest_radar);
intent.putExtra("speedLimit", speedLimit);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
};

AudioPlaybackCapture (Android 10) not working and recording empty sounds

I tried to use new AudioPlaybackCapture method to record some media in an android 10 device. But unfortunately my code which uses this API does not seem to be working well.
Here I used an activity which starts a separate service for media recording. That service is registered to a broadcast receiver to start and stop recordings. And the broadcast intents are fired using my main activity via button clicks (start, stop)
No exceptions are printed. Also the file is created at the desired location. But with no content (0bytes). All the required manifest and runtime permissions are given. What i'm doing wrong here.
Here is my service
public class MediaCaptureService extends Service {
public static final String ACTION_ALL = "ALL";
public static final String ACTION_START = "ACTION_START";
public static final String ACTION_STOP = "ACTION_STOP";
public static final String EXTRA_RESULT_CODE = "EXTRA_RESULT_CODE";
public static final String EXTRA_ACTION_NAME = "ACTION_NAME";
private static final int RECORDER_SAMPLERATE = 8000;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
NotificationCompat.Builder _notificationBuilder;
NotificationManager _notificationManager;
private String NOTIFICATION_CHANNEL_ID = "ChannelId";
private String NOTIFICATION_CHANNEL_NAME = "Channel";
private String NOTIFICATION_CHANNEL_DESC = "ChannelDescription";
private int NOTIFICATION_ID = 1000;
private static final String ONGING_NOTIFICATION_TICKER = "RecorderApp";
int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
int BytesPerElement = 2; // 2 bytes in 16bit format
AudioRecord _recorder;
private boolean isRecording = false;
private MediaProjectionManager _mediaProjectionManager;
private MediaProjection _mediaProjection;
Intent _callingIntent;
public MediaCaptureService() {
}
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Call Start foreground with notification
Intent notificationIntent = new Intent(this, MediaCaptureService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
_notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Starting Service")
.setContentText("Starting monitoring service")
.setTicker(ONGING_NOTIFICATION_TICKER)
.setContentIntent(pendingIntent);
Notification notification = _notificationBuilder.build();
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(NOTIFICATION_CHANNEL_DESC);
_notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
_notificationManager.createNotificationChannel(channel);
startForeground(NOTIFICATION_ID, notification);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
_mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
_callingIntent = intent;
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_ALL);
registerReceiver(_actionReceiver, filter);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void startRecording(Intent intent) {
//final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
_mediaProjection = _mediaProjectionManager.getMediaProjection(-1, intent);
startRecording(_mediaProjection);
}
#TargetApi(29)
private void startRecording(MediaProjection mediaProjection ) {
AudioPlaybackCaptureConfiguration config =
new AudioPlaybackCaptureConfiguration.Builder(mediaProjection)
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
.build();
AudioFormat audioFormat = new AudioFormat.Builder()
.setEncoding(RECORDER_AUDIO_ENCODING)
.setSampleRate(RECORDER_SAMPLERATE)
.setChannelMask(RECORDER_CHANNELS)
.build();
_recorder = new AudioRecord.Builder()
// .setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(audioFormat)
.setBufferSizeInBytes(BufferElements2Rec * BytesPerElement)
.setAudioPlaybackCaptureConfig(config)
.build();
_recorder.startRecording();
writeAudioDataToFile();
}
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
private void writeAudioDataToFile() {
// Write the output audio in byte
Log.i(MainActivity.LOG_PREFIX, "Recording started. Computing output file name");
File sampleDir = new File(getExternalFilesDir(null), "/TestRecordingDasa1");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String fileName = "Record-" + new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss").format(new Date()) + ".pcm";
String filePath = sampleDir.getAbsolutePath() + "/" + fileName;
//String filePath = "/sdcard/voice8K16bitmono.pcm";
short sData[] = new short[BufferElements2Rec];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
_recorder.read(sData, 0, BufferElements2Rec);
System.out.println("Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, BufferElements2Rec * BytesPerElement);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.i(MainActivity.LOG_PREFIX, String.format("Recording finished. File saved to '%s'", filePath));
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void stopRecording() {
// stops the recording activity
if (null != _recorder) {
isRecording = false;
_recorder.stop();
_recorder.release();
_recorder = null;
}
_mediaProjection.stop();
stopSelf();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(_actionReceiver);
}
BroadcastReceiver _actionReceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_ALL)) {
String actionName = intent.getStringExtra(EXTRA_ACTION_NAME);
if (actionName != null && !actionName.isEmpty()) {
if (actionName.equalsIgnoreCase(ACTION_START)) {
startRecording(_callingIntent);
} else if (actionName.equalsIgnoreCase(ACTION_STOP)){
stopRecording();
}
}
}
}
};
And here is an extract from the main activity where the service and start / stop actions are started.
public class MainActivity extends AppCompatActivity {
public static final String LOG_PREFIX = "CALL_FUNCTION_TEST";
private static final int ALL_PERMISSIONS_PERMISSION_CODE = 1000;
private static final int CREATE_SCREEN_CAPTURE = 1001;
Button _btnInitCapture;
Button _btnStartCapture;
Button _btnStopCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnGetOkPermissions = findViewById(R.id.btnGetOkPermissions);
_btnGetOkPermissions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkOkPermissions();
}
});
_btnInitCapture = findViewById(R.id.btnInitCapture);
_btnInitCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initAudioCapture();
}
});
_btnStartCapture = findViewById(R.id.btnStartCapture);
_btnStartCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startRecording();
}
});
_btnStopCapture = findViewById(R.id.btnStopAudioCapture);
_btnStopCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopRecording();
}
});
}
...
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAudioCapture() {
_manager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
Intent intent = _manager.createScreenCaptureIntent();
startActivityForResult(intent, CREATE_SCREEN_CAPTURE);
}
private void stopRecording() {
Intent broadCastIntent = new Intent();
broadCastIntent.setAction(MediaCaptureService.ACTION_ALL);
broadCastIntent.putExtra(MediaCaptureService.EXTRA_ACTION_NAME, MediaCaptureService.ACTION_STOP);
this.sendBroadcast(broadCastIntent);
}
private void startRecording() {
Intent broadCastIntent = new Intent();
broadCastIntent.setAction(MediaCaptureService.ACTION_ALL);
broadCastIntent.putExtra(MediaCaptureService.EXTRA_ACTION_NAME, MediaCaptureService.ACTION_START);
this.sendBroadcast(broadCastIntent);
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (CREATE_SCREEN_CAPTURE == requestCode) {
if (resultCode == RESULT_OK) {
Intent i = new Intent(this, MediaCaptureService.class);
i.setAction(MediaCaptureService.ACTION_START);
i.putExtra(MediaCaptureService.EXTRA_RESULT_CODE, resultCode);
i.putExtras(intent);
this.startService(i);
} else {
// user did not grant permissions
}
}
}
}
Well, nothing sets isRecording true. Also, you're doing your recording in a blocking method, but you're on the UI thread, which ought to cause your interface to freeze as soon as you start recording.

CountDownTimer Service crashing when it is opened

I am trying to make a countdown timer screen that will keep counting down if I back out of the app or change screens or something. For some reason it keeps crashing saying that timeLeft is null. I can't figure out why it would be because I know the time variable in my Countdown class is there. Thanks for any help!
Countdown Activity
public class Countdown extends Activity {
public static String time;
public static String address;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
Intent confIntent = getIntent();
time = confIntent.getStringExtra("time");
address = confIntent.getStringExtra("address");
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView= findViewById(R.id.t1);
String timeLeftString = intent.getStringExtra("timeSent");
int timeLeft = Integer.parseInt(timeLeftString);
if(timeLeft>0) {
textView.setText("You have " + timeLeft + " minutes left");
}
else{
textView.setText("Y'all outta time, see ya again soon!");
killIt();
}
}
}, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);
Intent toService = new Intent(this, CountdownService.class);
startService(toService);
}
#Override
protected void onResume() {
super.onResume();
TextView textView= findViewById(R.id.t1);
textView.setText("You have " + CountdownService.toSend + " minutes left");
}
#Override
protected void onPause() {
super.onPause();
}
public void killIt(){
stopService(new Intent(this, CountdownService.class));
}
}
Countdown Service
public class CountdownService extends Service{
public static int toSend=0;
public int time;
public static final String
ACTION_LOCATION_BROADCAST = CountdownService.class.getName() +
"LocationBroadcast";
public final String timeFromCD = Countdown.time;
public final String address = Countdown.address;
#Override
public void onCreate() {
super.onCreate();
time = Integer.parseInt(timeFromCD);
time = time*60000;
new CountDownTimer(time, 5000) {
public void onTick(long millisUntilFinished) {
int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000); //Whole number of minutes left, ceiling
sendBroadcastMessage(timeLeftInt);
toSend = timeLeftInt;
if(timeLeftInt == 5){
Notify("Not Done");
}
}
public void onFinish() {
sendBroadcastMessage(0);
Notify("done");
Response.Listener<String> response = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//creating a jsonResponse that will receive the php json
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(CountdownService.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SpotAmountRequest spotAmountRequest = new SpotAmountRequest(address, "0", response);
RequestQueue queue = Volley.newRequestQueue(CountdownService.this);
queue.add(spotAmountRequest);
}
}.start();
}
private void sendBroadcastMessage(int timeSent) {
Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
intent.putExtra("timeSent", timeSent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
Notification n = new Notification.Builder(this)
.setContentTitle("Time to leave!")
.setContentText("Your PrePark spot has expired, time to go home!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(1000);
}
else{
Notification n = new Notification.Builder(this)
.setContentTitle("Ya got 5 minutes left in your PrePark spot!")
.setContentText("Better get going soon here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
}
}
}
You're storing an int value in the intent that you're broadcasting from the service, but you're then trying to get it out as a String where you receive the broadcast. Either change the receiver to use getIntExtra instead of getStringExtra, or convert the int to a String in the service before storing it in the intent.

Trying to get the user's location loaded onto a map, using a singleton, service and an alarm

So far I have an alarm set to wake up every so often and then take the latitude and longitude of the user. This is stored in the singleton class Position which will be loaded in a different activity and placed as a marker on a map, based on the last recorded position.
Objective
I want the app to track the user's location even when it is closed, as to why i've used an AlarmManager to wake the device after a certain amount of seconds and take the coordinates, until they request to stop it.
Problem
Even though the class returns the previously-recorded Position values i.e. the coordinates, the activity which calls this to place the position on the map returns the coordinates (0.0, 0.0) i.e. null, assuming that it is initialising the object as if it doesn't already exist.
What could be the problem?
Position - the Singleton
public class Position {
private double latitude;
private double longitude;
private String coordinate;
private String service;
private static Position instance;
private Position() {
}
public String getCoordinate() {
return coordinate;
}
public void setCoordinate(String coordinate) {
this.coordinate = coordinate;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public static Position getInstance() {
if (instance == null) {
instance = new Position();
}
return instance;
}
}
The Alarm - where the location is tracked
public class Alarm extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// get the service code
String serviceCode = intent.getStringExtra("serviceCode");
// get the last known location
LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
//store the latitude and longitude locally
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String coordinate = latitude + ", " + longitude;
Position pos = Position.getInstance();
Log.d("", "Previous position: " + pos.getCoordinate());
pos.setLatitude(latitude);
pos.setLongitude(longitude);
pos.setCoordinate(coordinate);The
pos.setService(serviceCode);
Log.d("", "Found new position: " + pos.getCoordinate());
wl.release();
}
public void SetAlarm(Context context) {
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Location Service - what initialises the alarm
public class LocationService extends android.app.Service {
Alarm alarm = new Alarm();
private NotificationManager nm;
#Override
public void onCreate() {
super.onCreate();
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
alarm.SetAlarm(LocationService.this);
return START_STICKY;
}
private void showNotification() {
// set up notification label to notify user that the app is still tracking the location
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
CharSequence text = "Press to stop tracking";
// don't let user close it, for the purpose of always letting them know the location tracker is still running
Notification notification = new Notification(R.drawable.fav_buses, text, System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR;
// for older APIs
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, PushLocationActivity.class), 0);
notification.setLatestEventInfo(this, "Tracking Your Location", text, contentIntent);
nm.notify(R.string.notification_id, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
alarm.CancelAlarm(LocationService.this);
nm.cancel(R.string.notification_id);
Log.d("", "DESTROYED");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
StopsFragment - where the NullPointerException occurs
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stops = new HashMap<>();
stopList = StopList.getInstance(getActivity()).getStops();
request = getArguments().getString("request");
position = Position.getInstance();
Log.d("", position.getCoordinate());
}
You should not follow that approach, this will drain the device battery. Android have specific API to receive significant location changes for a user, you should use them. Follow this links:
https://developer.android.com/training/location/receive-location-updates.html
Just adapt the code, instead of an activity, the code should be executed from a service, and the service should be called to execute on boot.

Android AlarmManager Won't Start Service

I have two implementations of AlarmManager which are supposed to start two services - LMW and BWM - for some reason BWM starts each time and LMW does not. I've looked the source code over many times and I'm really not sure why this could be happening.
P.S.
adb shell dumpsys alarm shows a reference to BWM but no reference to LWM
Any input is greatly appreciated!
ALARMMANAGER SOURCE:
public class Rules extends Activity {
private String password;
private PendingIntent mPendingIntent;
String TIMELIMIT = "10";
TextView textSsid, textSpeed, textRssi, Time;
private static final int NOTIFY_ME_ID = 1337;
private int count = 0;
private NotificationManager notifyMgr = null;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rules);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
Time = (TextView) findViewById(R.id.Time);
Time.setText(time);
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Time = (TextView) findViewById(R.id.Time);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED
|| mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView) findViewById(R.id.RX);
TextView TX = (TextView) findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes() - mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer) findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public Date getTimeFromTimeString(String time) {
String[] splitStrings = time.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
return timeDate;
}
// Long.parseLong(time)
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed())
+ " " + WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
;
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
// Start 2nd service using AlarmManager
// Calendar cal = Calendar.getInstance();
// cal.add(Calendar.SECOND, 10);
// Intent intent2 = new Intent(Rules.this, KillTimer.class);
// PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0,
// intent2,
// 0);
// AlarmManager alarm2 = (AlarmManager)
// getSystemService(Context.ALARM_SERVICE);
// alarm2.setRepeating(AlarmManager.RTC_WAKEUP,
// cal.getTimeInMillis(),
// time != null ? 1000 : 0, pintent2);
// Date futureDate = new Date(new Date().getTime() + 86400000);
// futureDate.setHours(8);
// futureDate.setMinutes(0);
// futureDate.setSeconds(0);
// Start 3rd service using AlarmManager
Intent intent3 = new Intent(Rules.this, BWM.class);
PendingIntent pintent3 = PendingIntent.getActivity(Rules.this, 0,
intent3, 0);
AlarmManager alarm3 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm3.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent3);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), LMW.class));
startService(new Intent(getBaseContext(), BWM.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), LMW.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
}
};
}
LMW SOURCE:
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!",
Toast.LENGTH_SHORT).show();
Parse.initialize(this, "7gjqmUcoqu1IZPJSSxXLdE4L8efAugCXA7snLSH6",
"5NckF83MUBumQ8L8zL7Akc4p07beMRnmvgCfhZdH");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground();
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(
android.provider.Browser.BOOKMARKS_URI, projection, null, null,
null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor
.getColumnIndex(Browser.BookmarkColumns.URL));
// Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1)
|| url.toLowerCase().contains(Dirty2)
|| url.toLowerCase().contains(Dirty3)
|| url.toLowerCase().contains(Dirty4)
|| url.toLowerCase().contains(Dirty5)
|| url.toLowerCase().contains(Dirty6)
|| url.toLowerCase().contains(Dirty7)
|| url.toLowerCase().contains(Dirty8)
|| url.toLowerCase().contains(Dirty9)
|| url.toLowerCase().contains(Dirty10)) {
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
}
} while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}

Categories

Resources