Unit Testing on a Xmpp Android app on Android Studio - java

I'm trying to code some unit test for some OnCreate() methode on my XMPP app on android Studio, the problem is that i have never done that and i'm a little bit lost.
Here is my methode :
public class ChatActivity extends AppCompatActivity {
private static final String TAG ="ChatActivity";
private String contactJid;
private ChatView mChatView;
private SendButton mSendButton;
private BroadcastReceiver mBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mChatView =(ChatView) findViewById(R.id.rooster_chat_view);
mChatView.setEventListener(new ChatViewEventListener() {
#Override
public void userIsTyping() {
//Here you know that the user is typing
}
#Override
public void userHasStoppedTyping() {
//Here you know that the user has stopped typing.
}
});
mSendButton = mChatView.getSendButton();
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Only send the message if the client is connected
//to the server.
if (RoosterConnectionService.getState().equals(RoosterConnection.ConnectionState.CONNECTED)) {
Log.d(TAG, "The client is connected to the server,Sending Message");
//Send the message to the server
Intent intent = new Intent(RoosterConnectionService.SEND_MESSAGE);
intent.putExtra(RoosterConnectionService.BUNDLE_MESSAGE_BODY,
mChatView.getTypedString());
intent.putExtra(RoosterConnectionService.BUNDLE_TO, contactJid);
sendBroadcast(intent);
//Update the chat view.
mChatView.sendMessage();
} else if (RoosterConnectionService.getState().equals(RoosterConnection.ConnectionState.DISCONNECTED)){
Toast.makeText(getApplicationContext(),
"Client not connected to server ,Message not sent!",
Toast.LENGTH_LONG).show();
}
}
});
Intent intent = getIntent();
contactJid = intent.getStringExtra("EXTRA_CONTACT_JID");
setTitle(contactJid);
}
My question is that i don't know how to proceed and what to put in my OnCreateTest() method and what to test, could anyone help please :(

Related

Why my android app is giving "your app keeps stopping" while connecting to mqtt broker

I have written a code to connect my android app to mqtt server in android studio. I have added button "connect" after clicking it will show me connect message on screen. The moment I click the connect button, I get the message your android app keeps stopping. here is my code. I have uploaded necessary repositories and dependency and also permissions
public class MainActivity extends AppCompatActivity {
MqttAndroidClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String clientId = MqttClient.generateClientId();
client =
new MqttAndroidClient(this.getApplicationContext(), "tcp://mqtt.eclipse.org:1883",
clientId);
}
public void test(View V){
try {
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this,"connected",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Toast.makeText(MainActivity.this,"disconnected",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
Error Solved. There was problem in local broadcast manager file.

Android app terminates after certain time when minimized

I have this app which parses SMS and then converts them into Audio. My app users usually minimize the app and runs it all the time. But my app is getting terminated after sometime. How can i make sure my app will run till a user "terminates" it. Since the core functionality of the app is to convert SMS to audio, i need it running all the time.How can i do this ?
My current MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView txtGateway, txtTime, txtAmount;
Speakerbox speakerbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textView = findViewById(R.id.txt_message);
speakerbox = new Speakerbox(getApplication());
txtAmount = findViewById(R.id.tv_amount);
txtGateway = findViewById(R.id.tv_gateway);
txtTime = findViewById(R.id.tv_time);
requestSmsPermission();
}
#Override
public void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onResume();
}
#Override
public void onPause() {
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
super.onPause();
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("otp")) {
final String message = intent.getStringExtra("message");
String gateway = intent.getStringExtra("gateway");
String time = intent.getStringExtra("time");
String amount = intent.getStringExtra("amount");
speakerbox.play(message);
txtGateway.setText(gateway);
txtTime.setText(time);
txtAmount.setText(amount);
// message is the fetching OTP
}
}
};
/**
* Requesting multiple permissions (storage and location) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestSmsPermission() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.RECEIVE_SMS,
Manifest.permission.READ_SMS,
Manifest.permission.SEND_SMS,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
// Toast.makeText(getApplicationContext(), "All permissions are granted!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
}
Use a foreground service to ensure that your app is not killed by Android. On newer version of Android, app's background process gets killed after sometime. Having a foreground service will ensure that your app stays active. Keep the service on background thread and not on the main thread.
Read more at:
https://developer.android.com/guide/components/services
and
https://androidwave.com/foreground-service-android-example/
Activities are used for user facing parts of your application. Use service instead. Most likely, your application is getting terminated by os due to low memory situation.
Use service for the core functionality if you want to run all the time in background.If user is not using your app actively yet app is taking RAM memory then OS will terminate the app to avoid out of memory.

Bluetooth OnReceive Method Doesn't Get Called

I'm trying to make an android app which has some issues about Bluetooth. I simply enable Bluetooth, find devices, connect one of the devices, send & receive data. First thing is done. But in second, there are some problems. I make a Broadcast Receiver to discover devices nearby my phone. But OnReceive method doesn't get called. The weird thing is, it was getting called at first and I was able to see devices nearby. Then something that I cannot figure out happened and now OnReceive method doesn't get called. I've searched topics about these but none of them could solve my problem. MyDevice and MyAdapter are my own classes to show Bluetooth devices in listview with my own layout. Here is my code:
public class FoundDevicesActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
ListView foundedDevicesListView;
MyDeviceAdapter deviceAdapter;
List<MyDevice> foundedDevicesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_found_devices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
foundedDevicesListView = (ListView) findViewById(R.id.foundDevicesListview);
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(receiver, filter);
bluetoothAdapter.startDiscovery();
deviceAdapter = new MyDeviceAdapter(this, foundedDevicesList);
foundedDevicesListView.setAdapter(deviceAdapter);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(FoundDevicesActivity.this, "Discovery is started !!", Toast.LENGTH_SHORT).show();
Log.d("Found Devices Activity", "Discovery is started !!");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
MyDevice dvc = new MyDevice();
if (device.getName().equals(null)) {
dvc.name = "UNDEFINED NAME";
} else {
dvc.name = device.getName();
}
if(device.getAddress().equals(null)) {
dvc.address = "UNDEFINED ADDRESS";
} else {
dvc.address = device.getAddress();
}
foundedDevicesList.add(dvc);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
bluetoothAdapter.cancelDiscovery();
Toast.makeText(FoundDevicesActivity.this, "Discovery is finished !!", Toast.LENGTH_SHORT).show();
Log.d("Found Devices Activity", "Discovery is finished !!");
}
}
};
}
Any idea ?

Android: Broadcast Receiver does not receive BluetoothDevice.ACTION_ACL_CONNECTED on restarting the application

I want my app to auto-connect to already connected bluetooth device on restarting the app. Below is procedure I am performing:-
[Initially] Bluetooth device is 'ON': Then on starting the app.
[Behavior]--> Bluetooth device gets paired and connected successfully ( Intent 'ACTION_ACL_CONNECTED' is received)
Bluetooth device is 'ON': Closed the app, then started the app again.
[Behavior]--> Even though it is connected as displayed on Bluetooth setting, and Broadcast Receiver does not receive Intent 'ACTION_ACL_CONNECTED'.
Note:- On closing the app, it does not disconnect the bluetooth connection.
So, on successful connection app straightaway goes to the HomeScreen. Otherwise, the app goes to a screen having button that takes it to Bluetooth setting(onClickListener present in the code below)
I am new to android development, so I really don't know where am I going wrong. I looked up the solutions for similar issues and applied them, but to no effect.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(mReceiver, filter);
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
m_app = (BtApp) getApplication();
imagebt = (ImageView) this.findViewById(R.id.imagebt);
imagebt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Toast tag = Toast.makeText(getApplicationContext(), "Connect to device", Toast.LENGTH_LONG);
tag.show();
new CountDownTimer(1000, 1000)
{
public void onTick(long millisUntilFinished) {tag.show();}
public void onFinish() {
//tag.show();
}
}.start();
if(mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.startDiscovery();
}
Intent intentBluetooth = new Intent();
intentBluetooth.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intentBluetooth);
}
});
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if ( BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
m_app.m_main.setupCommPort();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
m_app.m_device = device;
isconnected = true;
new Timer().schedule(new TimerTask() {
#Override
public void run() {
if ( m_app.m_main.m_BtService != null && m_app.m_main.m_BtService.getState() != BluetoothRFCommService.STATE_CONNECTED ) {
m_app.m_main.m_BtService.connect(device, false);
}
}
}, 3500);
} else if ( BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action) ) {
isconnected = false;
m_app.m_main.tabHost.setCurrentTab(0);
}
}
};
#Override
protected void onStop()
{
unregisterReceiver(mReceiver);
super.onStop();
}
You won't get BluetoothDevice.ACTION_ACL_CONNECTED event since the device is still connected. The event is fired only on changing of device state from disconnected to connected.
You have 2 options.
You can put your BroadcastReceiver with BluetoothDevice.ACTION_ACL_CONNECTED and BluetoothDevice.ACTION_ACL_DISCONNECTED filters into the Service and track the device connection state in the background. On your app startup you can ask the service to give you the current state of the device.
You can check if some of the Bluetooth profiles contains your device name in the list of connected devices.
For API 18+ you can use BluetoothManager#getConnectedDevices() for API below 18 you can use the following snippet (for each Bluetooth profile)
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
for (BluetoothDevice device : proxy.getConnectedDevices()) {
if (device.getName().contains("DEVICE_NAME")) {
deviceConnected = true;
}
}
if (!deviceConnected) {
Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
}
mBluetoothAdapter.closeProfileProxy(profile, proxy);
}
public void onServiceDisconnected(int profile) {
// TODO
}
};
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);

IntentService does broadcast but onReceive doesn't receive broadcast

(NOTE that at the end of this Question I have an EDIT in which I have replaced one method with what the Answer said to do in order to fix the problem of onReceive never getting called and added onDestroy to fix a new problem that cropped up after fixing first problem.)
Here's how I attempted to capture the broadcast data, but onReceive never gets called since Log.w never displays anything:
public class MatchesActivity extends Activity implements DatabaseConnector.DatabaseProcessListener
{
public static String SOME_ACTION = "com.dslomer64.servyhelperton.SOME_ACTION";
public static String STRING_EXTRA_NAME = "match";
#Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver
(
new BroadcastReceiver()
{
#Override public void onReceive(Context context, Intent intent)
{
String s = txaMatches.getText().toString() + intent.getStringExtra(STRING_EXTRA_NAME) ;
txaMatches.setText(s);
Log.w("MatchesActivity","`````onReceive <" + s + ">");
}
}, new IntentFilter(SOME_ACTION)
);
...
DatabaseConnector dbc = new DatabaseConnector(getApplicationContext(), assets);
dbc.setDbProcesslistener(this); // set way to know matches has been defined
dbc.findDBMatches();
} // end onCreate
} // end MatchesActivity
Database connector:
public DatabaseConnector(Context _context, AssetManager _assets)
{
mContext = _context;
//This method, called in `MatchesActivity` on button press, does start the service:
public void findDBMatches()
{
Intent i= new Intent(mContext, QueryDB.class);
mContext.startService(i);
}
// Here's the service:
public static class QueryDB extends IntentService
{
public QueryDB() { super(QueryDB.class.getSimpleName()); }
public QueryDB(String name) { super(name); }
//Here's the procedure that does all the work (and it does execute):
#Override protected void onHandleIntent(Intent intent)
{ ...
publishProgress(dicWord); // a String
}
//This does execute but it doesn't send `progress` back to `MatchesActivity`,
//which initiated request for service (note: `publishProgress` is so named
//because `QueryDB` used to be an `AsyncTask` and I just didn't change the name):
protected void publishProgress(String progress)
{
Intent intent = new Intent(MatchesActivity.SOME_ACTION);
intent.putExtra(MatchesActivity.STRING_EXTRA_NAME, progress);
this.sendBroadcast(intent); // THIS LINE IS THE PROBLEM, FIXED BELOW
Log.w("DatabaseConnector", "`````publishProgress <" + progress + ">");
}
}
What connection(s) have I failed to make?
EDIT
This is the CORRECTED method found just above:
protected void publishProgress(String progress)
{
Intent intent = new Intent(MatchesActivity.SOME_ACTION);
intent.putExtra(MatchesActivity.STRING_EXTRA_NAME, progress);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
Here is onDestroy in MatchesActivity (which starts the service), necessary to call when service has finished its work:
#Override protected void onDestroy()
{
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
Note that onDestroy refers to a new MatchesIntent variable, defined as:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver()
{
#Override public void onReceive(Context context, Intent intent)
{
String s = intent.getStringExtra(STRING_EXTRA_NAME) ;
txaMatches.append(s + "\n");
}
};
And onCreate in MatchesActivity got simpler because of defining mMessageReceiver:
#Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LocalBroadcastManager.getInstance(this).registerReceiver
(
mMessageReceiver, new IntentFilter(SOME_ACTION)
);
}
What connection(s) have I failed to make?
In your first block of code, you are using LocalBroadcastManager. In your second block of code, you are not.
Replace:
this.sendBroadcast(intent);
with:
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Categories

Resources