Testing onActivityResult() - java

I have the following Activity:
package codeguru.startactivityforresult;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class StartActivityForResult extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.startButton = (Button) this.findViewById(R.id.start_button);
this.startButton.setOnClickListener(onStart);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
int result = data.getIntExtra(StartActivityForResult.this.getString(R.string.result), -1);
String msg = "requestCode=" + requestCode + ", resultCode=" + resultCode + ", result=" + result;
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
private View.OnClickListener onStart = new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(StartActivityForResult.this, ChildActivity.class);
StartActivityForResult.this.startActivityForResult(intent, R.id.child_request);
}
};
private Button startButton = null;
}
And the following JUnit test:
package codeguru.startactivityforresult;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.test.UiThreadTest;
import android.widget.Button;
import junit.framework.Assert;
public class StartActivityForResultTest extends ActivityInstrumentationTestCase2<StartActivityForResult> {
public StartActivityForResultTest() {
super(StartActivityForResult.class);
}
#Override
public void setUp() throws Exception {
super.setUp();
this.setActivityInitialTouchMode(false);
this.activity = this.getActivity();
this.startButton = (Button) this.activity.findViewById(R.id.start_button);
}
#Override
public void tearDown() throws Exception {
this.activity.finish();
super.tearDown();
}
#UiThreadTest
public void testStartButtonOnClick() {
Assert.assertTrue(this.startButton.performClick());
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, null);
Assert.assertNotNull(result);
Instrumentation.ActivityMonitor am = new Instrumentation.ActivityMonitor(ChildActivity.class.getName(), result, true);
Assert.assertNotNull(am);
Activity childActivity = this.getInstrumentation().waitForMonitorWithTimeout(am, TIME_OUT);
Assert.assertNotNull(childActivity);
Assert.fail("How do I check that StartActivityForResult correctly handles the returned result?");
}
private Activity activity = null;
private Button startButton = null;
private static final int TIME_OUT = 5 * 1000; // 5 seconds
}
As you can see, I figured out how to mock up a result using Instrumentation.ActivityResult and Instrumentation.ActivityMonitor. How do I check that StartActivityForResult.onActivityResult() properly handles this result?

Use intents framework to mock the activity result
intending(hasComponent(DummyActivity.class.getName())).respondWith(new ActivityResult(resultCode, dataIntent));
rule.getActivity().startActivityForResult(new Intent(context,DummyActivity.class));
verify on activity result logic

For testing onActivityResult() in your test class, all you need to do is:
Create an ActivityMonitor which catching ChildActivity creation and retuning the mock ActivityResult.
Simulating the button click which start the ChildActivity for result.
Do some assertion on status and the mock ActivityResult.
Sample StartActivityForResult:
public class StartActivityForResult extends Activity {
private boolean activityResultIsReturned = false;
private String activityResult = null;
... ...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
activityResultIsReturned = true;
activityResult = data.getStringExtra("result");
... ...
}
... ...
}
Sample StartActivityForResultTest:
public class StartActivityForResultTest extends ActivityInstrumentationTestCase2<StartActivityForResult> {
... ...
public void testOnActivityResult() {
// Get current Activity and check initial status:
StartActivityForResult myActivity = getActivity();
assertFalse(myActivity.getActivityResultIsReturned());
assertNull(myActivity.getActiityResult());
// Mock up an ActivityResult:
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "This is the result");
Instrumentation.ActivityResult activityResult = new Instrumentation.ActivityResult(Activity.RESULT_OK, returnIntent);
// Create an ActivityMonitor that catch ChildActivity and return mock ActivityResult:
Instrumentation.ActivityMonitor activityMonitor = getInstrumentation().addMonitor(ChildActivity.class.getName(), activityResult , true);
// Simulate a button click that start ChildActivity for result:
final Button button = (Button) myActivity.findViewById(com.company.R.id.open_next_activity);
myActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// click button and open next activity.
button.performClick();
}
});
// Wait for the ActivityMonitor to be hit, Instrumentation will then return the mock ActivityResult:
ChildActivity childActivity = getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5);
// How do I check that StartActivityForResult correctly handles the returned result?
assertTrue(myActivity.getActivityResultIsReturned());
assertEqual(myActivity.getActiityResult(), "This is the result");
}
... ...
}

please refer the sites below. It will help you to solve your problem.
http://saigeethamn.blogspot.in/2009/08/android-developer-tutorial-for_31.html
http://android-er.blogspot.in/2011/08/return-result-to-onactivityresult.html
http://www.mubasheralam.com/tutorials/android/how-start-new-activity-and-getting-results

Related

Sinch not starting

This is such a basic issue that I am not sure what I could possibly be doing wrong. Sinch is not starting for me and I don't know why. I don't have enough experience with Sinch to diagnose why a basic command is not doing what it is supposed to do. Here's what I have:
I am trying to start and making the call from the Calling.java class. The code is as follows:
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.sinch.android.rtc.calling.Call;
import com.squareup.picasso.Picasso;
import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
public class Calling extends CallActivity {
private String calleeID;
private TextView serviceName;
Bundle callDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
callDetails = getIntent().getBundleExtra("callDetails");
//Setup end button
Button endCallButton = findViewById(R.id.endcall);
endCallButton.setOnClickListener(v -> endCall());
}
private void endCall() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finishActivity(FLAG_ACTIVITY_PREVIOUS_IS_TOP);
finish();
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
//Setup Calling Screen
ImageView avatar = findViewById(R.id.dialingAvatar);
Picasso.get().load(callDetails.getString("Logo")).into(avatar);
TextView midScreenName = findViewById(R.id.memberName);
midScreenName.setText(callDetails.getString("Name"));
serviceName = findViewById(R.id.serviceName);
serviceName.setText(callDetails.getString("Service"));
TextView ratings = findViewById(R.id.rating);
ratings.setText(callDetails.getString("Rating") + " ★");
//Get CallerID and CalleeID
calleeID = callDetails.getString("CalleeID");
//Start sinch Service
if(!getSinchServiceInterface().isStarted()){
getSinchServiceInterface().startClient(callDetails.getString("CallerID"));
Call call = getSinchServiceInterface().callUserVideo(calleeID);
Intent callServiceScreen = new Intent(this, ServiceCallActivity.class);
callDetails.putString(SinchService.CALL_ID, call.getCallId());
callServiceScreen.putExtra("Call Details", callDetails);
startActivity(callServiceScreen);
}
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
}
I am coming to Calling.java from Precall.java the code for that is:
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.sinch.android.rtc.SinchError;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class precall extends CallActivity implements SinchService.StartFailedListener {
private Bundle memberDetails;
private String url;
private Button cancel;
private Button call;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_precall);
//url
url = apiCallPoints.userInfo;
//Set Member Text
memberDetails = getIntent().getBundleExtra("Member");
//Populate screen
ImageView avatar = findViewById(R.id.avatar);
Picasso.get().load(memberDetails.getString("Logo")).into(avatar);
TextView memberName = findViewById(R.id.membername);
memberName.setText(memberDetails.getString("Name"));
TextView rating = findViewById(R.id.rating);
rating.setText(memberDetails.getString("Rating") + " ★");
TextView serviceName = findViewById(R.id.servicename);
serviceName.setText(memberDetails.getString("Service"));
TextView overview = findViewById(R.id.overview);
overview.setText(memberDetails.getString("Overview"));
//Add button clicks
cancel = findViewById(R.id.cancel_button);
cancel.setOnClickListener(view -> finish());
cancel.setEnabled(false);
call = findViewById(R.id.yes_button);
call.setOnClickListener(view -> {
goToCalling();
});
call.setEnabled(false);
setHomeBar();
}
//this method is invoked when the connection is established with the SinchService
#Override
protected void onServiceConnected() {
call.setEnabled(true);
cancel.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
}
//Invoked when just after the service is connected with Sinch
#Override
public void onStarted() {
}
private void goToCalling() {
//Async search
CallBackendSync callBackendSync = new CallBackendSync();
Object [] params = {url, memberDetails};
callBackendSync.execute(params);
}
private void setHomeBar() {
final Button home = findViewById(R.id.home_button);
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, SecondActivity.class));
}
});
final Button favourites = findViewById(R.id.star_button);
favourites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, Favourite_Page.class));
}
});
final Button profile_page = findViewById(R.id.person_button);
profile_page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(getApplicationContext(), Profile.class));
}
});
final Button notifications = findViewById(R.id.notification_button);
notifications.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, Notification_Page.class));
}
});
final Button service = findViewById(R.id.service_button);
service.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
startActivity(new Intent(precall.this, services.class));
}
});
}
class CallBackendSync extends AsyncTask {
OkHttpClient client = new OkHttpClient();
#Override
protected Object doInBackground(Object [] objects) {
String url = (String) objects[0];
Bundle memberDetails = (Bundle) objects[1];
//Get access token from shared preference
isLoggedIn loggedIn = new isLoggedIn(getApplicationContext());
String token = loggedIn.getToken();
if(token != null){
//Create request
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer " + token)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
JSONObject results = new JSONObject(response.body().string());
String UserID = results.getString("UserId");
memberDetails.putString("CallerID", UserID);
Intent callIntent = new Intent(precall.this, Calling.class);
callIntent.putExtra("callDetails", memberDetails);
startActivity(callIntent);
return results;
}catch (Exception e){
e.printStackTrace();
}
} else {
startActivity(new Intent(precall.this, Login_page.class));
}
return null;
}
protected void onPostExecute(String s){
super.onPostExecute(s);
}
}
}
The failure is happening in SinchService.java
import com.sinch.android.rtc.AudioController;
import com.sinch.android.rtc.ClientRegistration;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchClientListener;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.video.VideoController;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class SinchService extends Service {
private static final String APP_KEY = "is correct";
private static final String APP_SECRET = "is correct";
//private static final String ENVIRONMENT = "clientapi.sinch.com";
private static final String ENVIRONMENT = "sandbox.sinch.com";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient = null;
private String mUserId = "";
private StartFailedListener mListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
if(mSinchClient != null){
mSinchClient.terminate();
}
super.onDestroy();
}
private void start(String userName) {
mUserId = userName;
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext())
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.userId(userName)
.enableVideoCalls(true)
.build();
mSinchClient.setSupportCalling(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.checkManifest();
mSinchClient.start();
System.out.println("Is started: " + mSinchClient.isStarted());
}
private void stop() {
if(mSinchClient != null){
mSinchClient.terminate();
}
}
private boolean isStarted() {
if(mSinchClient != null){
return mSinchClient.isStarted();
} else {
return false;
}
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public Call callUserVideo(String userId) {
return mSinchClient.getCallClient().callUserVideo(userId);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
public VideoController getVideoController() {
return mSinchClient.getVideoController();
}
public AudioController getAudioController() {
return mSinchClient.getAudioController();
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
Intent intent = new Intent(SinchService.this, Calling.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SinchService.this.startActivity(intent);
}
}
}
And the base activity is CallActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.sinch.android.rtc.calling.Call;
import com.squareup.picasso.Picasso;
import static android.content.Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP;
public class Calling extends CallActivity {
private String calleeID;
private TextView serviceName;
Bundle callDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calling);
callDetails = getIntent().getBundleExtra("callDetails");
//Setup end button
Button endCallButton = findViewById(R.id.endcall);
endCallButton.setOnClickListener(v -> endCall());
}
private void endCall() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finishActivity(FLAG_ACTIVITY_PREVIOUS_IS_TOP);
finish();
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
//Setup Calling Screen
ImageView avatar = findViewById(R.id.dialingAvatar);
Picasso.get().load(callDetails.getString("Logo")).into(avatar);
TextView midScreenName = findViewById(R.id.memberName);
midScreenName.setText(callDetails.getString("Name"));
serviceName = findViewById(R.id.serviceName);
serviceName.setText(callDetails.getString("Service"));
TextView ratings = findViewById(R.id.rating);
ratings.setText(callDetails.getString("Rating") + " ★");
//Get CallerID and CalleeID
calleeID = callDetails.getString("CalleeID");
//Start sinch Service
if(!getSinchServiceInterface().isStarted()){
getSinchServiceInterface().startClient(callDetails.getString("CallerID"));
Call call = getSinchServiceInterface().callUserVideo(calleeID);
Intent callServiceScreen = new Intent(this, ServiceCallActivity.class);
callDetails.putString(SinchService.CALL_ID, call.getCallId());
callServiceScreen.putExtra("Call Details", callDetails);
startActivity(callServiceScreen);
}
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
}
I have been banging my head against this but I cannot figure out what's wrong. I sure it's something stupid and obvious that I can't see because I am too close to the code. But any ideas you guys have would be very helpful!
It looks like you are not waiting for it to start before you try to make a call. We recommend to start the service when the app starts. If you dont do that you need to wait or the onStarted event in the service for fire

what is the 101 error code mean in in-app-billing v3 library?

I am using in app billing v3 library, it is always get error
and error code is 101
What does this error code mean?
some details:
I am a developer working from Palestine and working on an app uploadded on Indian google play account
I created activity that included three buttons to purchase remove Ads
-the first button to subscribe one month
-the second to subscribe one year
-the third to purchase lifetime
I used this library 'com.anjlab.android.iab.v3:library:1.0.44'
I created product in google play console and its name PRODUCT_ID
this product will purchased when user click on button lifeTime
and I created two subscriptions
-the first's name is SUBSCRIPTION_MONTH_ID
and will be purchased when the user click on oneMonth button
-the second's name is SUBSCRIPTION_YEAR_ID
and will be purchased when the user click on oneYear button
this the code that I used
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.anjlab.android.iab.v3.BillingProcessor;
import com.anjlab.android.iab.v3.TransactionDetails;
public class InAppBilling extends AppCompatActivity{
BillingProcessor bp;
private static final String PRODUCT_ID = "****";
private static final String SUBSCRIPTION_MONTH_ID = "***";
private static final String SUBSCRIPTION_YEAR_ID = "***";
private static final String LICENSE_KEY = "*****";
private static final String MERCHANT_ID = "**";
Button oneMonth, oneYear, lifeTime;
int flag;
String android_id;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_app_purchase);
flag = 0;
android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
final Toolbar toolbar = findViewById(R.id.toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.setTitle("Remove Ads");
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
if(!BillingProcessor.isIabServiceAvailable(this)) {
Toast.makeText(this, "In-app billing service is unavailable, please upgrade Android Market/Play to version >= 3.9.16", Toast.LENGTH_SHORT).show();
}
bp = new BillingProcessor(this, LICENSE_KEY, MERCHANT_ID, new BillingProcessor.IBillingHandler() {
#Override
public void onProductPurchased(String productId, TransactionDetails details) {
Toast.makeText(InAppBilling.this, "successfully purchased, restart the app please", Toast.LENGTH_SHORT).show();
}
#Override
public void onBillingError(int errorCode, Throwable error) {
Toast.makeText(InAppBilling.this, "Error Billing", Toast.LENGTH_SHORT).show();
Log.e("nourbilling", "onBillingError: errorCode: "+errorCode+" error: "+error);
}
#Override
public void onBillingInitialized() {
}
#Override
public void onPurchaseHistoryRestored() {
for(String sku : bp.listOwnedProducts())
Log.d("nourbilling", "Owned Managed Product: " + sku);
for(String sku : bp.listOwnedSubscriptions())
Log.d("nourbilling", "Owned Subscription: " + sku);
}
});
oneMonth = findViewById(R.id.oneMonth);
oneYear = findViewById(R.id.oneYear);
lifeTime = findViewById(R.id.lifetime);
final Activity activity = this;
oneMonth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
createDialog(savedInstanceState, activity).show();
}
});
oneYear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 2;
createDialog(savedInstanceState, activity).show();
}
});
lifeTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag = 3;
createDialog(savedInstanceState, activity).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data))
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
if (bp != null)
bp.release();
super.onDestroy();
}
public Dialog createDialog(Bundle savedInstanceState, final Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("are you sure to remove ads by billing?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (flag == 1) {
bp.subscribe(activity, SUBSCRIPTION_MONTH_ID);
} else if (flag == 2) {
bp.subscribe(activity, SUBSCRIPTION_YEAR_ID);
} else if (flag == 3) {
bp.purchase(activity, PRODUCT_ID);
}
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
can you help me, please?

When using Floating Bubble as a Background Service to take a screenshot of Live Screen. Getting two Errors

enter code here BackgroundService-
private void addNewBubble ()//ERROR , Expression expected and Missing ';' token{
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//here is all the science of params
final WindowManager.LayoutParams myParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
BubbleLayout bubbleView = (BubbleLayout) LayoutInflater.from(BackgroundService.this).inflate(R.layout.bubble_layout, null);
bubbleView.setLayoutParams(myParams);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Bitmap b = Screenshot.takescreenshotOfRootView(imageView);
imageView.setImageBitmap(b);
main.setBackgroundColor(Color.parseColor("#999999"));
//Toast.makeText(getApplicationContext(), "Clicked !",
// Toast.LENGTH_SHORT).show();
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
}
private void initializeBubblesManager() {
bubblesManager = new BubblesManager.Builder(this)
.setTrashLayout(R.layout.bubble_trash_layout)
.setInitializationCallback(new OnInitializedCallback() {
#Override
public void onInitialized() {
addNewBubble();// ERROR
}
})
.build();
bubblesManager.initialize();
}
}
This is the OnStart method which includes all the methods to create the floating bubble and to make it clickable to take a screenshot. Only addNewBubble is showing errors , whereas when the Floating Bubble code is run on the MainActivity without the creation of BackgroundService it runs fine without any errors.
Any suggestions as to what to do ?
Copy paste this code .I have tested it
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.txusballesteros.bubbles.BubbleLayout;
import com.txusballesteros.bubbles.BubblesManager;
import com.txusballesteros.bubbles.OnInitializedCallback;
/**
* Created by yohanson on 20/09/17.
*/
public class MainActivity extends AppCompatActivity {
private BubblesManager bubblesManager;
private WindowManager windowManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkDrawOverlayPermission();
}
});
}
public void checkDrawOverlayPermission() {
/** check if we already have permission to draw over other apps */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
/** if not construct intent to request permission */
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
/** request permission via start activity for result */
startActivityForResult(intent, 2);
}
else
{
initializeBubblesManager();
addNewBubble();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/** check if received result code
is equal our requested code for draw permission */
if (requestCode == 2) {
initializeBubblesManager();
addNewBubble();
}
}
private void addNewBubble() {
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
//here is all the science of params
final WindowManager.LayoutParams myParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setLayoutParams(myParams);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) { }
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Toast.makeText(getApplicationContext(), "Clicked !",
Toast.LENGTH_SHORT).show();
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
private void initializeBubblesManager() {
bubblesManager = new BubblesManager.Builder(this)
.setTrashLayout(R.layout.bubble_trash_layout)
.setInitializationCallback(new OnInitializedCallback() {
#Override
public void onInitialized() {
addNewBubble();
}
})
.build();
bubblesManager.initialize();
}
#Override
protected void onDestroy() {
super.onDestroy();
bubblesManager.recycle();
}
}
Call addNewBubble() function in UiThread
runOnUiThread(new Runnable() {
public void run() {
addNewBubble()
}
});
like this.

Bypass Android UI error screen Speech Recognition [duplicate]

Is this possible without modify the android APIs?
I've found a article about this.
There's one a comment that I should do modifications to the android APIs.
But it didn't say how to do the modification.
Can anybody give me some suggestions on how to do that?
Thanks!
I've found this article;
SpeechRecognizer
His needs is almost the same as mine.
It is a good reference for me!
I've totally got this problem solved.
I googled a usable sample code from this China website
Here's my source code
package voice.recognition.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import android.util.Log;
public class voiceRecognitionTest extends Activity implements OnClickListener
{
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button speakButton = (Button) findViewById(R.id.btn_speak);
mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
mText.setText("error " + error);
}
public void onResults(Bundle results)
{
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
mText.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn_speak)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
}
}
}
Be sure to delete the annoying Logs after debugging!
Use the SpeechRecognizer interface. Your app needs to have the RECORD_AUDIO permission, and you can then create a SpeechRecognizer, give it a RecognitionListener and then call its startListening method. You will get callbacks to the listener when the speech recognizer is ready to begin listening for speech and as it receives speech and converts it to text.
GAST has a handy abstract class you can use to use the SpeechRecognizer class with very little new code. There is also an example of running the SpeechRecognizer as a background service using this and this
Thanks for posting this! I found it helpful to define the onclick listener in oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.textView1);
MyRecognitionListener listener = new MyRecognitionListener();
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(listener);
findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
sr.startListening(intent);
}
});
}
I end up making Github project to convert Text to speech and speech to text without annoying dialog,
https://github.com/hiteshsahu/Android-TTS-STT/tree/master/app/src/main/java/com/hiteshsahu/stt_tts/translation_engine
//SPEECH TO TEXT DEMO
speechToText.setOnClickListener({ view ->
Snackbar.make(view, "Speak now, App is listening", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
TranslatorFactory
.instance
.with(TranslatorFactory.TRANSLATORS.SPEECH_TO_TEXT,
object : ConversionCallback {
override fun onSuccess(result: String) {
sttOutput.text = result
}
override fun onCompletion() {
}
override fun onErrorOccurred(errorMessage: String) {
erroConsole.text = "Speech2Text Error: $errorMessage"
}
}).initialize("Speak Now !!", this#HomeActivity)
})
//TEXT TO SPEECH DEMO
textToSpeech.setOnClickListener({ view ->
val stringToSpeak :String = ttsInput.text.toString()
if (null!=stringToSpeak && stringToSpeak.isNotEmpty()) {
TranslatorFactory
.instance
.with(TranslatorFactory.TRANSLATORS.TEXT_TO_SPEECH,
object : ConversionCallback {
override fun onSuccess(result: String) {
}
override fun onCompletion() {
}
override fun onErrorOccurred(errorMessage: String) {
erroConsole.text = "Text2Speech Error: $errorMessage"
}
})
.initialize(stringToSpeak, this)
} else {
ttsInput.setText("Invalid input")
Snackbar.make(view, "Please enter some text to speak", Snackbar.LENGTH_LONG).show()
}
})

ProgressDialog not updating after Configuration Change (orientation turns to horizontal)

ProgressDialog quits updating when orientation of screen changes. I have put into place a fix that salvages the asynctask and sets the activity of the asynctask to the new activity after it is destroyed and rebuilt. The percentage complete on the progressdialog stays at the percentage it was at before the orientation change.
What am I missing?
package net.daleroy.fungifieldguide.activities;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Toast;
import net.daleroy.fungifieldguide.R;
import net.daleroy.fungifieldguide.fungifieldguideapplication;
public class FungiFieldGuide extends Activity {
//static final int PROGRESS_DIALOG = 0;
//ProgressThread progressThread;
private final static String LOG_TAG = FungiFieldGuide.class.getSimpleName();
fungifieldguideapplication appState;
private DownloadFile mTask;
public boolean mShownDialog;
ProgressDialog progressDialog;
private final static int DIALOG_ID = 1;
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if ( id == DIALOG_ID ) {
mShownDialog = true;
}
}
private void onTaskCompleted() {
Log.i(LOG_TAG, "Activity " + this + " has been notified the task is complete.");
//Check added because dismissDialog throws an exception if the current
//activity hasn't shown it. This Happens if task finishes early enough
//before an orientation change that the dialog is already gone when
//the previous activity bundles up the dialogs to reshow.
if ( mShownDialog ) {
dismissDialog(DIALOG_ID);
Toast.makeText(this, "Finished..", Toast.LENGTH_LONG).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_ID:
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading Database (only first run)...");
return progressDialog;
default:
return super.onCreateDialog(id);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
appState = ((fungifieldguideapplication)this.getApplication());
Object retained = getLastNonConfigurationInstance();
if ( retained instanceof DownloadFile ) {
Log.i(LOG_TAG, "Reclaiming previous background task.");
mTask = (DownloadFile) retained;
mTask.setActivity(this);
//showDialog(DIALOG_ID);
}
else {
if(!appState.service.createDataBase())
{
Log.i(LOG_TAG, "Creating new background task.");
//showDialog(DIALOG_ID);
mTask = new DownloadFile(this);
mTask.execute("http://www.codemarshall.com/Home/Download");
}
}
//showDialog(PROGRESS_DIALOG);
View btn_Catalog = findViewById(R.id.btn_Catalog);
btn_Catalog.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Cat_Genus.class);//new Intent(this, Total.class);
startActivity(i);
}
});
View btn_Search = findViewById(R.id.btn_Search);
btn_Search.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(getBaseContext(), Search.class);//new Intent(this, Total.class);
startActivity(i);
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
mTask.setActivity(null);
return mTask;
}
#Override
public void onDestroy()
{
super.onDestroy();
//progressDialog.dismiss();
//progressDialog = null;
appState.service.ClearSearchParameters();
}
private class DownloadFile extends AsyncTask<String, Integer, Boolean>{
private FungiFieldGuide activity;
private boolean completed;
private String Error = null;
private String Content;
private DownloadFile(FungiFieldGuide activity) {
this.activity = activity;
}
#Override
protected void onPreExecute()
{
showDialog(DIALOG_ID);
}
#Override
protected Boolean doInBackground(String... urlarg) {
int count;
try {
URL url = new URL(urlarg[0]);
URLConnection conexion = url.openConnection();
conexion.setDoInput(true);
conexion.setUseCaches(false);
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(conexion.getInputStream());
OutputStream output = new FileOutputStream("/data/data/net.daleroy.fungifieldguide/databases/Mushrooms.db");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)total*100/lenghtOfFile);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.i(LOG_TAG, e.getMessage());
}
return null;
}
#Override
public void onProgressUpdate(Integer... args){
progressDialog.setProgress(args[0]);
}
#Override
protected void onPostExecute(Boolean result)
{
completed = true;
notifyActivityTaskCompleted();
}
private void notifyActivityTaskCompleted() {
if ( null != activity ) {
activity.onTaskCompleted();
}
}
private void setActivity(FungiFieldGuide activity) {
this.activity = activity;
if ( completed ) {
notifyActivityTaskCompleted();
}
}
}
}
This is not a real solution but to prevent this I just disabled orientation changes during the life of the AsyncTask with adding first:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
and when the job is done:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
Hope this helps.

Categories