How to properly stop all the threads in Android? - java

In the code below, I maintain the "isFound" boolean variable to determine whether a thread should run or not. However, when I set the "isFound" to true. My threads will run exactly one more time. In other words, they will not stop properly which also causes the UI to not update the Textview properly. I guess this is due to some synchronized problems but I am not sure how to deal with it and I have tried using a synchronized block but it still does not work.
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView message;
private TextView magicNumDisplay;
private boolean isFound = false;
private NotificationManager notificationManager;
private Notification notifyDetail;
private final Handler handler = new Handler(){
public void handleMessage(Message msg) {
if (isMagic(msg.what)) {
isFound = true;
progressBar.setVisibility(View.INVISIBLE);
magicNumDisplay.setText("The magic number is " + msg.what);
handler.removeMessages(0);
message.setText("A magic number s found");
Intent intent = new Intent("MAGIC_NUMBER");
intent.putExtra("THREAD_NAME", msg.obj.toString());
intent.putExtra("MAGIC_NUMBER", String.valueOf(msg.what));
sendBroadcast(intent);
} else {
message.setText("Finding a magic number...");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (TextView) findViewById(R.id.message);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
magicNumDisplay = (TextView) findViewById(R.id.magic_num_display);
progressBar.setVisibility(View.VISIBLE);
IntentFilter filter = new IntentFilter("MAGIC_NUMBER");
BroadcastReceiver receiver = new MagicNumberReceiver();
registerReceiver(receiver, filter);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public void onStart(){
super.onStart();
Thread firstThread = new Thread(backgroundTask, "First");
Thread secondThread = new Thread(backgroundTask, "Second");
firstThread.start();
secondThread.start();
}
public boolean isMagic(int num) {
return (num % 7 == 0 && isLastDigitEqualTwo(num));
}
public boolean isLastDigitEqualTwo(int num) {
String numString = String.valueOf(num);
return Integer.parseInt(numString.substring(numString.length() - 1))==2;
}
Runnable backgroundTask = new Runnable() {
#Override
public void run() {
try {
while (!isFound) {
Thread.sleep(1000);
int number = (int) (Math.random() * 9999);
Message msg = handler.obtainMessage(number, Thread.currentThread().getName());
handler.sendMessage(msg);
Log.e(Thread.currentThread().getName(), "The number is :" + number);
}
} catch(InterruptedException e){
Log.e("Exception", e.getMessage());
}
}
};
public class MagicNumberReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context localContext, Intent callerIntent) {
String threadName = callerIntent.getStringExtra("THREAD_NAME");
String magicNum = callerIntent.getStringExtra("MAGIC_NUMBER");
Log.e("Magic", "Thread name:"+threadName+" Magic Number:"+magicNum);
int MAGIC_NUMBER_NOTIFICATION_ID=200;
notifyDetail = new Notification.Builder(getApplicationContext())
.setContentTitle("Magic Number")
.setContentText("Thread Name: " + threadName + ". Magic Number: " + magicNum+".")
.setSmallIcon(R.drawable.droid)
.setVibrate(new long[] {1000, 1000, 1000, 1000})
.setLights(Integer.MAX_VALUE, 500, 500)
.build();
notificationManager.notify(MAGIC_NUMBER_NOTIFICATION_ID,notifyDetail);
}
}
}

Related

How do I end a repeating handler when it hits a certain condition?

I'm making an application that plays audio files off the device's storage, and I have a seek bar that checks the progress of the audio file (how long it has played) every second, and updates the seekbar accordingly.
The audio is played through a service that runs in the foreground, and also displays a notification that the audio is playing.
When the audio ends, I noticed the handler still goes in it's cycle, and I want to end the handler once the audio is done.
What I'm currently trying to do is to end the handler from inside the runnable that the handler runs, as I'm not sure how else I can end it.
Main Activity, where I handle OnClick from the ListView where you can select an audio file and also handles the seekbar update.
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
SeekBar musicProgBar;
Handler progBarHandler = null;
Runnable r = null;
private MP3Service.MyBinder myService = null;
TextView progressText = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
musicProgBar = findViewById(R.id.musicProgressBar);
progressText = findViewById(R.id.progressText);
final ListView lv = (ListView) findViewById(R.id.musicList);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.IS_MUSIC + "!= 0",
null,
null);
progBarHandler = new Handler();
final int progBarDelay = 1000; // delay for the handler, making it repeat itself only every 1000 miliseconds (1 second)
lv.setAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[] { MediaStore.Audio.Media.DATA},
new int[] { android.R.id.text1 }));
Intent tempIntent = new Intent(this, MP3Service.class);
startService(tempIntent);
bindService(tempIntent, serviceConnection, 0);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter,
View myView,
int myItemInt,
long myLong) {
Cursor c = (Cursor) lv.getItemAtPosition(myItemInt);
String uri = c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA));
Log.d("g53mdp", uri);
if (myService.fetchPlayerState() != MP3Player.MP3PlayerState.STOPPED)
myService.stopMusic();
myService.loadMusic(uri);
myService.playMusic();
musicProgBar.setMax(myService.fetchDuration()); // set the max value of the seekbar to be the duration of the song
r = new Runnable()
{
#Override
public void run()
{
int tempInt = myService.fetchProgress();
Log.d("progress ticking", tempInt + " " + musicProgBar.getProgress());
musicProgBar.setProgress(tempInt); // sets the current progress of the seekbar to be the progress of the song
long minutes = TimeUnit.MILLISECONDS.toMinutes(tempInt);
long seconds = TimeUnit.MILLISECONDS.toSeconds(tempInt);
if (seconds >= 60)
seconds = seconds - 60;
String tempString = minutes + ":" + seconds;
progressText.setText(tempString);
progBarHandler.postDelayed(this, progBarDelay);
if (musicProgBar.getProgress() == myService.fetchDuration())
progBarHandler.removeCallbacks(this);
}
};
progBarHandler.post(r);
}});
}
private ServiceConnection serviceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
myService = (MP3Service.MyBinder) service;
}
#Override
public void onServiceDisconnected(ComponentName name)
{
myService = null;
}
};
public void playButClicked(View view)
{
myService.playMusic();
}
public void pauseButClicked(View view)
{
myService.pauseMusic();
}
public void stopButClicked(View view)
{
myService.stopMusic();
}
#Override
protected void onDestroy()
{
unbindService(serviceConnection);
progBarHandler.removeCallbacks(r);
super.onDestroy();
}
}
What is strange is that in onDestroy(), I do use removeCallbacks to end the handler, and that works nicely. I know that it comes to the point where it calls for removeCallbacks in the Runnable r, confirmed through debugging and logging. Also tried implementing a method that is specifically for removing the handler and calling that, no luck. Also tried using return.
The part I'm struggling with is
r = new Runnable()
{
#Override
public void run()
{
int tempInt = myService.fetchProgress();
Log.d("progress ticking", tempInt + " " + musicProgBar.getProgress());
musicProgBar.setProgress(tempInt); // sets the current progress of the seekbar to be the progress of the song
long minutes = TimeUnit.MILLISECONDS.toMinutes(tempInt);
long seconds = TimeUnit.MILLISECONDS.toSeconds(tempInt);
if (seconds >= 60)
seconds = seconds % 60;
String tempString = minutes + ":" + seconds;
progressText.setText(tempString);
progBarHandler.postDelayed(this, progBarDelay);
if (musicProgBar.getProgress() == myService.fetchDuration())
progBarHandler.removeCallbacks(this);
}
};
progBarHandler.post(r);
}});
The service which handles the music player and handles playing the music
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
public class MP3Service extends Service
{
public static MP3Service instance = null; // implementing singleton by instantiating a reference to the instance
private final String SERVICE_ID = "100"; // id for the service
public static boolean isRunning = false; //
NotificationManager notificationManager = null;
int notificationID = 001;
private final IBinder binder = new MyBinder();
MP3Player mainPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return binder;
}
#Override
public void onRebind(Intent intent)
{
// TODO: implement Rebind for screen orientation change
}
#Override
public void onCreate()
{
instance = this;
isRunning = true;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mainPlayer = new MP3Player();
super.onCreate();
Handler handler = new Handler();
}
#Override
public void onDestroy()
{
isRunning = false;
instance = null;
notificationManager.cancel(notificationID);
}
public void createNotification()
{
CharSequence name = "MP3 Notification";
String description = "Displays a notification when a song is playing";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(SERVICE_ID, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// when the user clicks the notification, this will bring them to the activity
PendingIntent navToMainActivity = PendingIntent.getActivity(this, 0, intent, 0);
// sets up the info and details for the notification
final NotificationCompat.Builder mNotification = new NotificationCompat.Builder(this, SERVICE_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("MP3 Player")
.setContentText("Playing music")
.setContentIntent(navToMainActivity)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
startForeground(notificationID, mNotification.build());
}
public void removeNotification()
{
stopForeground(false);
notificationManager.cancelAll();
}
public class MyBinder extends Binder
{
public void loadMusic(String filePath)
{
mainPlayer.load(filePath);
}
public void playMusic()
{
mainPlayer.play();
createNotification();
}
public void pauseMusic()
{
mainPlayer.pause();
removeNotification();
}
public void stopMusic()
{
mainPlayer.stop();
removeNotification();
}
public MP3Player.MP3PlayerState fetchPlayerState()
{
return mainPlayer.getState();
}
public int fetchDuration()
{
return mainPlayer.getDuration();
}
public int fetchProgress()
{
return mainPlayer.getProgress();
}
}
}
Thanks in advance for any help, and I am happy to provide with more information if required
EDIT: changed the progBarHandler.postDelay() that is outside the runnable to a simple progBarHandler.post()
I think the only reason you failed to stop the handler is constantly invoking progBarHandler.postDelayed(this, progBarDelay);,you need to check why it's still running.
Managed to get it working by introducing a different kind of if statement to the runnable, like so
Runnable r = new Runnable()
{
#Override
public void run()
{
if (musicProgBar.getProgress() == myService.fetchProgress() && myService.fetchProgress() != 0)
Log.d("audio", "over");
else {
int tempInt = myService.fetchProgress();
long minutes = TimeUnit.MILLISECONDS.toMinutes(tempInt);
long seconds = TimeUnit.MILLISECONDS.toSeconds(tempInt);
if (seconds >= 60)
seconds = seconds % 60;
String tempString = minutes + ":" + seconds;
progressText.setText(tempString);
musicProgBar.setProgress(tempInt); // sets the current progress of the seekbar to be the progress of the song
progBarHandler.postDelayed(this, progBarDelay);
}
}
};
It seemed for some reason, using .fetchDuration() and .fetchProgress() will never equalize each other, so changing the if statement worked.

My application is working in an endless loop

So I have an application which has to monitor and range after beacons and than calculates the position of the user. After calculating this , the value is passed to the Wayfindigoverlayactivity.class where the value should be putt on the map with the blue dot.
I don know how to assign the value to the blue dot but before that my application is working on an endless loop and is opening the activity on ranging about 100x .
RangingActivity:
package com.indooratlas.android.sdk.examples.wayfinding;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.EditText;
import android.content.Context;
import com.google.android.gms.maps.model.LatLng;
import com.indooratlas.android.sdk.IALocationRequest;
import com.indooratlas.android.sdk.examples.R;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
public class RangingActivity extends Activity implements BeaconConsumer,Runnable{
protected static final String TAG = "RangingActivity";
public LatLng center;
private final BlockingQueue queue;
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ranging);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBeaconServiceConnect() {
RangeNotifier rangeNotifier = new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
int beacon_number = beacons.size();
Beacon[] beacon_array = beacons.toArray(new Beacon[beacons.size()]);
Beacon device1 = null, device2 = null, device3 = null;
Constants constants = new Constants();
float txPow1 = 0;
double RSSI1Unfiltered = 0;
double RSSI2Unfiltered = 0;
float txPow2 = 0;
double RSSI3Unfiltered = 0;
float txPow3 = 0;
if (beacon_number == 4) {
if (beacon_array[0].getIdentifier(0).toString() == constants.DEVICE1_UUID) {
device1 = beacon_array[0];
} else if (beacon_array[1].getIdentifier(0).toString() == constants.DEVICE1_UUID) {
device1 = beacon_array[1];
} else {
device1 = beacon_array[2];
}
if (beacon_array[0].getIdentifier(0).toString() == constants.DEVICE2_UUID) {
device2 = beacon_array[0];
} else if (beacon_array[1].getIdentifier(0).toString() == constants.DEVICE2_UUID) {
device2 = beacon_array[1];
} else {
device2 = beacon_array[2];
}
if (beacon_array[0].getIdentifier(0).toString() == constants.DEVICE3_UUID) {
device3 = beacon_array[0];
} else if (beacon_array[1].getIdentifier(0).toString() == constants.DEVICE3_UUID) {
device3 = beacon_array[1];
} else {
device3 = beacon_array[2];
}
RSSI1Unfiltered = device1.getRssi();
RSSI2Unfiltered = device2.getRssi();
RSSI3Unfiltered = device3.getRssi();
txPow1 = device1.getTxPower();
txPow2 = device2.getTxPower();
txPow3 = device3.getTxPower();
} else if (beacon_number > 0) {
Log.d(TAG, "didRangeBeaconsInRegion called with beacon count: " + beacons.size());
for (int i = 0; i < beacon_number; i++) {
Beacon nextBeacon = beacon_array[i];
Log.d(TAG, "The next beacon " + nextBeacon.getIdentifier(0) + " is about " + nextBeacon.getDistance() + " meters away." + "RSSI is: " + nextBeacon.getRssi());
logToDisplay("The next beacon" + nextBeacon.getIdentifier(0) + " is about " + nextBeacon.getDistance() + " meters away." + "RSSI is: " + nextBeacon.getRssi());
}
}
Log.d(TAG, "FLOAT!!!!!!!!" + txPow1);
LocationFinder locationFinder = new LocationFinder();
//pass location
center = locationFinder.findLocation(RSSI1Unfiltered, txPow1, RSSI2Unfiltered, txPow2, RSSI3Unfiltered, txPow3);
Log.d(TAG, "Current coordinates: asta e asta e !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " + center.toString());
Bundle args = new Bundle();
args.putParcelable("b", center);
Intent intent00 = new Intent(RangingActivity.this, WayfindingOverlayActivity.class);
intent00.putExtras(args);
startActivity(intent00);
}
private void logToDisplay(final String s) {
runOnUiThread(new Runnable() {
#Override
public void run() {
EditText editText = RangingActivity.this.findViewById(R.id.textView3);
editText.append(s+"\n");
}
});
}
};
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
beaconManager.addRangeNotifier(rangeNotifier);
} catch (RemoteException e) {
}
}
/* Blockinqueue try---not working
RangingActivity(BlockingQueue q)
{
queue = q;
}
public void run() {
LatLng res;
try
{
res = center;
queue.put(res);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
*/
}
Everything works fine here , until I open the next class where my map is the WayfindingOverlayActivity
package com.indooratlas.android.sdk.examples.wayfinding;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.fragment.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.indooratlas.android.sdk.IALocation;
import com.indooratlas.android.sdk.IALocationListener;
import com.indooratlas.android.sdk.IALocationManager;
import com.indooratlas.android.sdk.IALocationRequest;
import com.indooratlas.android.sdk.IAOrientationListener;
import com.indooratlas.android.sdk.IAOrientationRequest;
import com.indooratlas.android.sdk.IAPOI;
import com.indooratlas.android.sdk.IARegion;
import com.indooratlas.android.sdk.IARoute;
import com.indooratlas.android.sdk.IAWayfindingListener;
import com.indooratlas.android.sdk.IAWayfindingRequest;
import com.indooratlas.android.sdk.examples.R;
import com.indooratlas.android.sdk.examples.SdkExample;
import com.indooratlas.android.sdk.resources.IAFloorPlan;
import com.indooratlas.android.sdk.resources.IALatLng;
import com.indooratlas.android.sdk.resources.IALocationListenerSupport;
import com.indooratlas.android.sdk.resources.IAVenue;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
#SdkExample(description = R.string.example_wayfinding_description)
public class WayfindingOverlayActivity extends FragmentActivity
implements GoogleMap.OnMapClickListener, OnMapReadyCallback ,Runnable{
private final BlockingQueue queue;
private static final String TAG = "IndoorAtlasExample";
/* used to decide when bitmap should be downscaled */
private static final int MAX_DIMENSION = 2048;
//kalman filter
private static final double KALMAN_R = 0.125d;
private static final double KALMAN_Q = 0.5d;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Circle mCircle;
private IARegion mOverlayFloorPlan = null;
private GroundOverlay mGroundOverlay = null;
private IALocationManager mIALocationManager;
private Target mLoadTarget;
private boolean mCameraPositionNeedsUpdating = true; // update on first location
private Marker mDestinationMarker;
private Marker mHeadingMarker;
private IAVenue mVenue;
private List<Marker> mPoIMarkers = new ArrayList<>();
private List<Polyline> mPolylines = new ArrayList<>();
private IARoute mCurrentRoute;
private IAWayfindingRequest mWayfindingDestination;
private IAWayfindingListener mWayfindingListener = new IAWayfindingListener() {
#Override
public void onWayfindingUpdate(IARoute route) {
mCurrentRoute = route;
if (hasArrivedToDestination(route)) {
// stop wayfinding
showInfo("You're there!");
mCurrentRoute = null;
mWayfindingDestination = null;
mIALocationManager.removeWayfindingUpdates();
}
updateRouteVisualization();
}
};
private IAOrientationListener mOrientationListener = new IAOrientationListener() {
#Override
public void onHeadingChanged(long timestamp, double heading) {
updateHeading(heading);
}
#Override
public void onOrientationChange(long timestamp, double[] quaternion) {
// we do not need full device orientation in this example, just the heading
}
};
private int mFloor;
// circle
private void showLocationCircle(LatLng center, double accuracyRadius) {
if (mCircle == null) {
// location can received before map is initialized, ignoring those updates
if (mMap != null) {
mCircle = mMap.addCircle(new CircleOptions()
.center(center)
.radius(accuracyRadius)
.fillColor(0x201681FB)
.strokeColor(0x500A78DD)
.zIndex(1.0f)
.visible(true)
.strokeWidth(5.0f));
mHeadingMarker = mMap.addMarker(new MarkerOptions()
.position(center)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_blue_dot))
.anchor(0.5f, 0.5f)
.flat(true));
}
} else {
// move existing markers position to received location
mCircle.setCenter(center);
mHeadingMarker.setPosition(center);
mCircle.setRadius(accuracyRadius);
}
}
private void updateHeading(double heading) {
if (mHeadingMarker != null) {
mHeadingMarker.setRotation((float) heading);
}
}
private IALocationListener mListener = new IALocationListenerSupport() {
public void onLocationChanged(IALocation location) {
Log.d(TAG, "NEW" + location.getLatitude() + " " + location.getLongitude());
if (mMap == null) {
return;
}
final LatLng center = new LatLng(location.getLatitude(),location.getLongitude());
final int newFloor = location.getFloorLevel();
if (mFloor != newFloor) {
updateRouteVisualization();
}
mFloor = newFloor;
showLocationCircle(center, location.getAccuracy());
if (mCameraPositionNeedsUpdating) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(center, 15.5f));
mCameraPositionNeedsUpdating = false;
}
}
};
/**
* Listener that changes overlay if needed
*/
private IARegion.Listener mRegionListener = new IARegion.Listener() {
#Override
public void onEnterRegion(final IARegion region) {
if (region.getType() == IARegion.TYPE_FLOOR_PLAN) {
Log.d(TAG, "enter floor plan " + region.getId());
mCameraPositionNeedsUpdating = true; // entering new fp, need to move camera
if (mGroundOverlay != null) {
mGroundOverlay.remove();
mGroundOverlay = null;
}
mOverlayFloorPlan = region; // overlay will be this (unless error in loading)
fetchFloorPlanBitmap(region.getFloorPlan());
//setupPoIs(mVenue.getPOIs(), region.getFloorPlan().getFloorLevel());
} else if (region.getType() == IARegion.TYPE_VENUE) {
mVenue = region.getVenue();
}
}
#Override
public void onExitRegion(IARegion region) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// prevent the screen going to sleep while app is on foreground
findViewById(android.R.id.content).setKeepScreenOn(true);
// instantiate IALocationManager
mIALocationManager = IALocationManager.create(this);
// Try to obtain the map from the SupportMapFragment.
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map))
.getMapAsync(this);
Intent myIntent = new Intent(this, RangingActivity.class);
this.startActivity(myIntent);
Intent intent00 = getIntent();
LatLng center = intent00.getParcelableExtra("b");
Log.d(TAG,"Location!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + center);
}
#Override
protected void onDestroy() {
super.onDestroy();
// remember to clean up after ourselves
mIALocationManager.destroy();
}
/*Some blockingqueue---does not work
public class BlockinQueueExample
{
public void main(String[] args) throws Exception
{
BlockingQueue q = new ArrayBlockingQueue(1000);
RangingActivity producer = new RangingActivity(q);
WayfindingOverlayActivity consumer = new WayfindingOverlayActivity(q);
new Thread(producer).start();
new Thread(consumer).start();
}
}
WayfindingOverlayActivity(BlockingQueue q)
{
this.queue = q;
}
public void run() {
try{
queue.take();
Log.d(TAG,"BIANCABICA"+queue.take());
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
*/
#Override
protected void onResume() {
super.onResume();
// start receiving location updates & monitor region changes
mIALocationManager.requestLocationUpdates(IALocationRequest.create(), mListener);
mIALocationManager.registerRegionListener(mRegionListener);
mIALocationManager.registerOrientationListener(
// update if heading changes by 1 degrees or more
new IAOrientationRequest(1, 0),
mOrientationListener);
if (mWayfindingDestination != null) {
mIALocationManager.requestWayfindingUpdates(mWayfindingDestination, mWayfindingListener);
}
}
EDIT , LAUNCHER ACTIVITY
package com.indooratlas.android.sdk.examples;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.indooratlas.android.sdk.examples.imageview.ImageViewActivity;
import com.indooratlas.android.sdk.examples.wayfinding.MonitoringActivity;
import com.indooratlas.android.sdk.examples.wayfinding.RangingActivity;
import com.indooratlas.android.sdk.examples.wayfinding.WayfindingOverlayActivity;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.BootstrapNotifier;
import org.altbeacon.beacon.startup.RegionBootstrap;
public class Bianca extends Activity implements BootstrapNotifier {
private static final String TAG = "RANGE";
private RegionBootstrap regionBootstrap;
private Button button;
private BackgroundPowerSaver backgroundPowerSaver;
private boolean haveDetectedBeaconsSinceBoot = false;
private MonitoringActivity monitoringActivity = null;
private String cumulativeLog = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
BeaconManager beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
//--------------------------------meniu -------------------------------
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openAct();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openAct2();
}
});
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openAct3();
}
});
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openAct4();
}
});
//-----------------------------meniu----------------------------------
Notification.Builder builder = new Notification.Builder(this);
Intent intent = new Intent(this,WayfindingOverlayActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel("My Notification Channel ID",
"My Notification Name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("My Notification Channel Description");
NotificationManager notificationManager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channel.getId());
}
beaconManager.enableForegroundServiceScanning(builder.build(), 456);
Log.d(TAG, "setting up background monitoring for beacons and power saving");
// wake up the app when a beacon is seen
Region region = new Region("backgroundRegion",
null, null, null);
regionBootstrap = new RegionBootstrap((BootstrapNotifier) this, region);
backgroundPowerSaver = new BackgroundPowerSaver(this);
}
public void openAct()
{
Intent intent = new Intent(this, WayfindingOverlayActivity.class);
startActivity(intent);
}
public void openAct2()
{
Intent intent2 = new Intent(this, RangingActivity.class);
startActivity(intent2);
}
public void openAct3()
{
Intent intent4 = new Intent(this, ImageViewActivity.class);
startActivity(intent4);
}
public void openAct4()
{
Intent intent5 = new Intent(this,RegionsActivity.class);
startActivity(intent5);
}
public void disableMonitoring() {
if (regionBootstrap != null) {
regionBootstrap.disable();
regionBootstrap = null;
}
}
public void enableMonitoring() {
Region region = new Region("backgroundRegion",
null, null, null);
regionBootstrap = new RegionBootstrap((BootstrapNotifier) this, region);
}
public void didEnterRegion(Region arg0) {
// In this example, this class sends a notification to the user whenever a Beacon
// matching a Region (defined above) are first seen.
Log.d(TAG, "did enter region.");
if (!haveDetectedBeaconsSinceBoot) {
Log.d(TAG, "auto launching MainActivity");
// The very first time since boot that we detect an beacon, we launch the
// MainActivity
Intent intent = new Intent(this, WayfindingOverlayActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Important: make sure to add android:launchMode="singleInstance" in the manifest
// to keep multiple copies of this activity from getting created if the user has
// already manually launched the app.
this.startActivity(intent);
haveDetectedBeaconsSinceBoot = true;
} else {
if (monitoringActivity != null) {
// If the Monitoring Activity is visible, we log info about the beacons we have
// seen on its display
Log.d(TAG, "I see a beacon again");
} else {
// If we have already seen beacons before, but the monitoring activity is not in
// the foreground, we send a notification to the user on subsequent detections.
Log.d(TAG, "Sending notification.");
}
}
}
public void didExitRegion(Region arg0) {
Log.d(TAG,"I no longer see a beacon.");
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
}
The second class is not fully posted , only where I make changes.
The intent in the second class is in the OnCreate part
The location is calculated in the logcat , the only problem is that the application is working in a loop
Please help me , I am stuck. Thanks
I guess, you only need to open RangingActivity from onCreate() of WayFindingOverlayActivity if center is null. This means, we need to open RangingActivity to get the value for center. Doing null check for the center will also ensure that the application doesn't go in loop and proceed when we have the value for center. The code in the onCreate() of WayFindingOverlayActivity may look like this :
// edited here
Bundle extras = getIntent().getExtras();
if(extras == null){
Intent myIntent = new Intent(this, RangingActivity.class);
this.startActivity(myIntent);
} else{
LatLng center = extras.getParcelable("b");
Log.d("Location!!", center);
// call showLocationCircle() to show the blue dot
showLocationCircle(center, yourAccuracyRadius);
}

Trying to process different scenarios in Service

I am having a problem and I ran out of ideas how to fix it.
The goal is, when the user clicks the button an URL is loaded depending on what's selected in settings.
Problem is, I am having trouble setting it up in a right way.
Logically(to me), I tried to set it up in a service. Button is clicked > Service starts > URL is loaded from "IF ELSE".
Problem is, I get an error in "IF ELSE" - "Method length must be called from the UI Thread, currently inferred thread is is worker.
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
#Override
protected void onHandleIntent(Intent intent) {
MainActivity mainActivity;
mainActivity = new MainActivity();
if (mainActivity.mEditTextHashtag.length() > 2) {
WallpaperManager wm = WallpaperManager.getInstance(this);
int height = wm.getDesiredMinimumHeight();
int width = wm.getDesiredMinimumWidth();
String url = "https://source.unsplash.com/all/?" + mainActivity.mEditTextHashtag.getText() + "/" + width + "x" + height + "/";
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
}
}
}
Ok, fair enough.
I created new Method getPhoto(); in UI Thread and put the code in there. Then, I called mainActivity.getPhoto(); in Service.
Problem is, I get an error - "Attempt to invoke virtual method 'int android.widget.EditText.length()' on a null object reference"
Any ideas on what I should do?
Full code in all its glory:
package com.edip.splashwallpaper;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.InputStream;
import java.net.URL;
public class MainActivity extends android.app.Activity {
final static String TAG = "AllInOne";
final static int CHANGE_INTERVAL = 30 * 1000; //30 sec for testing
static boolean loading = false;
WallpaperManager wm;
//Layout Views
Switch mSwitchFixedPhoto, mSwitchControls, mSwitchSave, mSwitchPause;
Spinner mSpinnerCategories, mSpinnerInterval;
EditText mEditTextHashtag;
Button mWallpaperButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Layout Views Initialized
mSwitchFixedPhoto = (Switch) findViewById(R.id.sw_fixedphoto);
mSwitchControls = (Switch) findViewById(R.id.switch_controls);
mSwitchSave = (Switch) findViewById(R.id.switch_save);
mSwitchPause = (Switch) findViewById(R.id.switch_pause);
mSpinnerCategories = (Spinner) findViewById(R.id.spinner_categories);
mSpinnerInterval = (Spinner) findViewById(R.id.spinner_interval);
mEditTextHashtag = (EditText) findViewById(R.id.et_hashtag);
mWallpaperButton = (Button) findViewById(R.id.btn_set_wallpaper);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapterCategory = ArrayAdapter.createFromResource(this,
R.array.categories_array, R.layout.dialog_spinner_layout);
// Specify the layout to use when the list of choices appears
adapterCategory.setDropDownViewResource(R.layout.dialog_spinner_layout);
// Apply the adapter to the spinner
mSpinnerCategories.setAdapter(adapterCategory);
ArrayAdapter<CharSequence> adapterInterval = ArrayAdapter.createFromResource(this,
R.array.interval_array, R.layout.dialog_spinner_layout);
adapterInterval.setDropDownViewResource(R.layout.dialog_spinner_layout);
mSpinnerInterval.setAdapter(adapterInterval);
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PendingIntent pending = PendingIntent.getBroadcast(MainActivity.this,
666, new Intent("com.edip.splashwallpaper.CHANGE_WALLPAPTER_TIMER"),
PendingIntent.FLAG_CANCEL_CURRENT);
((AlarmManager) getSystemService(Context.ALARM_SERVICE))
.setRepeating(AlarmManager.RTC, System.currentTimeMillis(),
CHANGE_INTERVAL, pending);
}
});
}
public void getPhoto() {
if (mEditTextHashtag.length() > 2) {
wm = WallpaperManager.getInstance(this);
int height = wm.getDesiredMinimumHeight();
int width = wm.getDesiredMinimumWidth();
String url = "https://source.unsplash.com/all/?" + mEditTextHashtag.getText() + "/" + width + "x" + height + "/";
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
} else {
Toast.makeText(this, "Something else", Toast.LENGTH_SHORT).show();
}
}
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
#Override
protected void onHandleIntent(Intent intent) {
MainActivity mainActivity;
mainActivity = new MainActivity();
mainActivity.getPhoto();
}
}
public static class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if (!loading) {
loading = true;
context.startService(new Intent(context, Service.class));
}
}
}
}
Thanks :)
First of all, you should never instantiate an activity by yourself.
Second, as a best practice, your service shouldn't know about your activity, or that it has an edit text. Instead you should send the URL to load inside your intent, when the PendingIntent is created, like this :
Intent intent = new Intent("com.edip.splashwallpaper.CHANGE_WALLPAPTER_TIMER");
intent.putExtra("USER_URL", "https://source.unsplash.com/all/?" + mEditTextHashtag.getText() + "/" + width + "x" + height + "/");
PendingIntent pending = PendingIntent.getBroadcast(MainActivity.this,
666, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Then within your service, read the url like so :
#Override
protected void onHandleIntent(Intent intent) {
String url = intent.getStringExtra("USER_URL");
// ...
}

Output every minute for ten minutes

I am trying to print something out for an android app every minute for ten minutes. I would preferably like to access the phone's clock to have the code start automatically at a specific time. However, I am not exactly sure how to do that part. Here is what I have so far.
So here is my main code I want to add the code below in along with the answer provided below:
package com.example.james.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private TextToSpeech myTTS;
//status check code
private int MY_DATA_CHECK_CODE = 0;
//create the Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get a reference to the button element listed in the XML layout
Button speakButton = (Button)findViewById(R.id.speak);
Button speakButton1 = (Button)findViewById(R.id.button);
Button speakButton2 = (Button)findViewById(R.id.button2);
//listen for clicks
speakButton.setOnClickListener(this);
speakButton1.setOnClickListener(this);
speakButton2.setOnClickListener(this);
//check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
//respond to button clicks
public void onClick(View v) {
//get the text entered
EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
//speak the user text
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
//act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
//setup TTS
public void onInit(int initStatus) {
//check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
}
else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
}
import java.util.*;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ClassExecutingTask {
long delay = 10 * 60000; // delay in milliseconds
LoopTask task = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() {
timer.cancel();
timer = new Timer("TaskName");
Date executionDate = new Date(); // no params = now
timer.scheduleAtFixedRate(task, executionDate, delay);
}
private class LoopTask extends TimerTask {
public void run() {
while (delay > 0) {
System.out.println("Formation will form up in " + delay + " minutes");
delay--;
}
}
}
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
}
<!---->
public void run() {
while (delay > 0) {
System.out.println("Formation will form up in " + delay + " minutes");
delay--;
}
}
<!---->
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
If you want to do above thing in android then following code will help you add those lines in your onCreate()method
new CountDownTimer(600000, 60000) {//CountDownTimer(edittext1.getText()+edittext2.getText()) also parse it to long
public void onTick(long millisUntilFinished) {
System.out.println("Your message on every minute");
//here you can have your logic to set text to edittext
}
public void onFinish() {
System.out.println("Your message after 10 minute");
}
}
.start();

In AsyncTask, stop making registerReceiver() freeze the app

Since I finally figured out that the registerReceiver() method is usually running on the UI-Thread, I now want to change that. I just need some advice of how I could do that.
How would I be able to change registerReceiver() to stop freezing my app?
My doInBackground() method from the AsyncTask, runs another method that is using the registerReceiver(mReceiver, filter) method (both variables are already defined). But I want to keep seeing my ProgressDialog instead of making the app freezing.
I read about using a Handler and a new Thread, but I need some help there.
Thanks in advance.
Code:
package ch.scs.mod.tools.messagegenerator.business;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.scs.mod.tools.messagegenerator.R;
import ch.scs.mod.tools.messagegenerator.model.Testcase;
import ch.scs.mod.tools.messagegenerator.model.Testset;
public class ReportActivity extends Activity implements OnClickListener {
private static final String TAG = "ReportActivity";
private TextView title;
private TextView lblReport;
private TextView lblEmail;
private TableLayout tblReport;
private Button btnBack;
private Testset testset;
private Testcase testcase;
private List<Testcase> testcases = new ArrayList<Testcase>();
private String number;
private String apn = "not used";
private String error;
private ArrayList<String> resultarray = new ArrayList<String>();
private ProgressDialog progressdialog;
private boolean running = false;
public enum State {
UNKNOWN, CONNECTED, NOT_CONNECTED
}
private ConnectivityManager mConnMgr;
private PowerManager.WakeLock mWakeLock;
private ConnectivityBroadcastReceiver mReceiver;
private NetworkInfo mNetworkInfo;
private State mState;
private boolean mListening;
private boolean mSending;
private SendMms sendMms = SendMms.getInstance();
private MMSTest myTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
title = (TextView) findViewById(R.id.lblTitle);
lblReport = (TextView) findViewById(R.id.lblReport);
lblEmail = (TextView) findViewById(R.id.lblMmsEmail);
tblReport = (TableLayout) findViewById(R.id.tblReport);
btnBack = (Button) findViewById(R.id.btnBack);
progressdialog = new ProgressDialog(this);
progressdialog.setTitle("Please wait...");
progressdialog.setMessage("Sending...");
progressdialog.setCancelable(false);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/TheSansB_TT4_App.ttf");
title.setTypeface(tf);
lblEmail.setTypeface(tf);
lblReport.setTypeface(tf);
btnBack.setTypeface(tf);
lblEmail.setText(Html
.fromHtml("<a href=\'mailto:mathias.hubacher#swisscom.com\'>mathias.hubacher#swisscom.com</a>"));
lblEmail.setMovementMethod(LinkMovementMethod.getInstance());
btnBack.setOnClickListener(this);
testset = (Testset) this.getIntent().getSerializableExtra("testset");
number = (String) this.getIntent().getStringExtra("number");
lblReport.setText(getResources().getString(R.string.reportText1) + " "
+ number + " " + getResources().getString(R.string.reportText2));
testcases = testset.getTestcases();
resultarray.clear();
// Creating Views for Asynctask
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
HorizontalScrollView hsv = new HorizontalScrollView(this);
sv.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, getWindowManager().getDefaultDisplay().getHeight()/2));
sv.setVerticalScrollBarEnabled(true);
sv.setHorizontalScrollBarEnabled(true);
sv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
hsv.setLayoutParams(new HorizontalScrollView.LayoutParams(HorizontalScrollView.LayoutParams.MATCH_PARENT, HorizontalScrollView.LayoutParams.MATCH_PARENT));
hsv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
for (Testcase testc : testcases) {
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
TextView tvok = new TextView(this);
TextView tverror = new TextView(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv.setText(testc.getName() + " ");
tv.setTextColor(getResources().getColor(R.color.white));
tr.addView(tv);
tvok.setText("Sending...");
tvok.setTextColor(getResources().getColor(R.color.white));
tverror.setText("");
tverror.setTextColor(getResources().getColor(R.color.orange));
tr.addView(tvok);
tr.addView(tverror);
ll.addView(tr);
testc.setTextView(tv);
testc.setTextViewOk(tvok);
testc.setTextViewError(tverror);
}
hsv.addView(ll);
sv.addView(hsv);
tblReport.addView(sv);
myTask = new MMSTest();
myTask.execute();
}
private void createSms(List<Testcase> tcs) {
for (Testcase testc : tcs) {
error = "";
if (!testc.isExecute()) {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
} else {
sendSms(number, testc);
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok));
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed));
resultarray.add(error);
}
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
}
private class MMSTest extends AsyncTask<String, String, ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mReceiver = new ConnectivityBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
// progressdialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
if (testset.getType().equals("sms")) {
Log.v(TAG, "Testtype SMS");
createSms(testcases);
} else if (testset.getType().equals("mms")) {
Log.v(TAG, "Testtype MMS");
mListening = true;
mSending = false;
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// mReceiver = new ConnectivityBroadcastReceiver();
apn = (String) ReportActivity.this.getIntent().getStringExtra("apn");
startMms();
} else {
lblReport.setText("Error Testset Type not valid");
}
return resultarray;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
for (Testcase testc : testcases) {
if (testc.getRunning()) {
TextView tvok = testc.getTextViewOk();
TextView tverror = testc.getTextViewError();
if (testc.isExecute()) {
if (testc.isSuccsess()) {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.green));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.orange));
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
testc.setRunning(false);
break;
}
}
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
// int r = 0;
// for (Testcase testc : testcases) {
// TextView tvok = testc.getTextViewOk();
// TextView tverror = testc.getTextViewError();
// if (testc.isExecute()) {
// if (testc.isSuccsess()) {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.green));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.orange));
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// r = r + 2;
// }
// progressdialog.dismiss();
}
}
private void sendMms() {
int responseCode=0;
for (Testcase testc : testcases) {
error = "";
if (testc.isExecute()) {
File file = new File(Environment.getExternalStorageDirectory(), ".MODTest/" + testc.getContentFile());
if (file.exists()) {
if (file.length() > 300000) {
Log.v(TAG, "File Length="+ Long.toString(file.length()));
error=getResources().getString(R.string.warningFileSize);
}
responseCode = sendMms.startMms(testc.getSubject(), number, apn, testc.getContentFile(), testc.getContentType(), getApplicationContext());
Log.v(TAG,"Test: "+ testc.getName() + " / Response code: " + Integer.toString(responseCode));
if (responseCode == 200) {
testc.setSuccsess(true);
responseCode = 0;
} else {
testc.setSuccsess(false);
error =Integer.toString(responseCode);
}
} else {
testc.setSuccsess(false);
error =getResources().getString(R.string.errorNoFile);
}
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok) + " ");
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed) + " ");
resultarray.add(error);
}
} else {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
endMmsConnectivity();
mSending = false;
mListening = false;
}
public void startMms() {
for (Testcase tcs : testcases) {
testcase = tcs;
number = number + "/TYPE=PLMN";
// IntentFilter filter = new IntentFilter();
// filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
// registerReceiver(mReceiver, filter);
try {
// Ask to start the connection to the APN. Pulled from Android
// source code.
int result = beginMmsConnectivity();
Log.v(TAG, "Result= " + Integer.toString(result));
if (result != PhoneEx.APN_ALREADY_ACTIVE) {
Log.v(TAG, "Extending MMS connectivity returned " + result
+ " instead of APN_ALREADY_ACTIVE");
// Just wait for connectivity startup without
// any new request of APN switch.
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendSms(String nr, Testcase tc) {
if (!tc.getBody().equals("")) {
SmsManager sm = SmsManager.getDefault();
sm.getDefault().sendTextMessage(nr, null, tc.getBody(), null, null);
tc.setSuccsess(true);
} else {
tc.setSuccsess(false);
error = getResources().getString(R.string.errorEmptySms);
}
}
#Override
public void onClick(View v) {
if (v.equals(findViewById(R.id.btnBack))) { // Wenn Button zurück
// geklickt wird
Intent startMmsTest = new Intent(ReportActivity.this,
StartActivity.class);
startActivity(startMmsTest);
}
}
protected void endMmsConnectivity() {
// End the connectivity
try {
Log.v(TAG, "endMmsConnectivity");
if (mConnMgr != null) {
mConnMgr.stopUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE,
PhoneEx.FEATURE_ENABLE_MMS);
}
} finally {
releaseWakeLock();
}
}
protected int beginMmsConnectivity() throws IOException {
// Take a wake lock so we don't fall asleep before the message is
// downloaded.
createWakeLock();
int result = mConnMgr.startUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE, PhoneEx.FEATURE_ENABLE_MMS);
Log.v(TAG, "beginMmsConnectivity: result=" + result);
switch (result) {
case PhoneEx.APN_ALREADY_ACTIVE:
case PhoneEx.APN_REQUEST_STARTED:
acquireWakeLock();
return result;
}
throw new IOException("Cannot establish MMS connectivity");
}
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int responseCode;
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| mListening == false) {
Log.w(TAG, "onReceived() called with " + mState.toString()
+ " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.NOT_CONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
// mOtherNetworkInfo = (NetworkInfo) intent
// .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// mReason =
// intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// mIsFailover =
// intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER,
// false);
// Check availability of the mobile network.
if (mNetworkInfo == null) {
/**
* || (mNetworkInfo.getType() !=
* ConnectivityManager.TYPE_MOBILE)) {
*/
Log.v(TAG, " type is not TYPE_MOBILE_MMS, bail");
return;
}
if (!mNetworkInfo.isConnected()) {
Log.v(TAG, " TYPE_MOBILE_MMS not connected, bail");
return;
} else {
Log.v(TAG, "connected..");
if (mSending == false) {
mSending = true;
sendMms();
}
}
}
}
}
Move it to onProgressUpdate() method, or better , onPostExecute()/onPreExecuteMethod() depending on your need.
These methods run on UI thread and not on the new thread creetaed by the Asynctask

Categories

Resources