Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How to solve "'catch' or 'finally' expected" error in android studio..?
a screenshot of the error
public class FragmentRecent extends Fragment {
View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterChannel adapterChannel;
private SwipeRefreshLayout swipeRefreshLayout;
private Call<CallbackChannel> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
private OfflineDatabase databaseHelper;
int counter = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_recent, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_home);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterChannel = new AdapterChannel(getActivity(), recyclerView, new ArrayList<Channel>());
recyclerView.setAdapter(adapterChannel);
// on item list clicked
adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() {
#Override
public void onItemClick(View v, Channel obj, int position) {
Intent intent = new Intent(getActivity(), ActivityDetailChannel.class);
intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name);
intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id);
intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name);
intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image);
intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url);
intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description);
startActivity(intent);
showInterstitialAd();
}
});
// detect when scroll reach bottom
adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > adapterChannel.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
adapterChannel.setLoaded();
}
}
});
// on swipe list
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
adapterChannel.resetListData();
requestAction(1);
}
});
requestAction(1);
return root_view;
}
private void displayApiResult(final List<Channel> channels) {
adapterChannel.insertData(channels);
swipeProgress(false);
if (channels.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getPostByPage(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackChannel>() {
#Override
public void onResponse(Call<CallbackChannel> call, Response<CallbackChannel> response) {
CallbackChannel resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackChannel> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
adapterChannel.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
} else {
//showToast("Internet Not");
if (databaseHelper.getOfflineData("FragmentCategory").length() != 0) {
setJson(databaseHelper.getOfflineData("FragmentCategory"), false);
}
}
}
//databaseHelper.removeAll();
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
adapterChannel.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_post_found);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
return;
}
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(show);
}
});
}
public void setJson(String result, Boolean isOnline) {
try {
//inseting result to database
if(isOnline) {
ContentValues offline_data = new ContentValues();
offline_data.put(OfflineDatabase.KEY_OFFLINE_DATA, result);
if(databaseHelper.getOfflineData("FragmentCategory").length()!=0) {
databaseHelper.update("FragmentCategory",offline_data);
} else {
offline_data.put(OfflineDatabase.KEY_ACTIVITY_NAME, "FragmentCategory");
databaseHelper.addOfflineData(offline_data, null);
//handle both exceptions
}
}}}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
} else {
Log.d("AdMob", "AdMob Interstitial is Enabled");
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
} else {
Log.d("AdMob", "Interstitial Ad is Disabled");
}
} else {
Log.d("AdMob", "AdMob Interstitial is Disabled");
}
}}
there you start with try:
public void setJson(String result, Boolean isOnline) {
try {
...
}
...
}
which has to continue with:
try {
...
} catch(Exception e) {
} finally {
}
where either catch or finally are optional (depending where the Exception shall be handled).
Related
i am making an app that records a video and then displays this video on another activity.
the problem is that this video cannot be played right away, i would have to record the video, and then restart the android app for it to show. otherwise it shows me a message that
says: "can't play this video".
Moreover the thing that i really dont understand is that i tried it on an older phone of android version 11 and it works perfectly, but for some reason on the new phone it doesn't
i have made some research and i think it has something to do with the storage permissions but i am not sure since i tried fixing it with no luck.
what can i do to fix this?
public class MainActivity extends AppCompatActivity {
CameraManager CamMan;
boolean flag = false;
public static boolean FirstDirectoryCreated;
CameraSource cameraSource;
Button seeVideos;
public static File LeakedVids;
public static boolean isDirectoryCreated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1);
}
seeVideos = findViewById(R.id.seeVideos);
init();
createFiles();
CamMan = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
seeVideos.setOnClickListener(v -> goToVideos());
}
private void goToVideos() {
Intent intent = new Intent(this, ShowVideo.class);
startActivity(intent);
}
#Override
public void onBackPressed(){
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
private void createFiles () {
File EyeTracker = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "Eye Tracker");
FirstDirectoryCreated = EyeTracker.exists() || EyeTracker.mkdirs();
if (FirstDirectoryCreated) {
LeakedVids = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + File.separator
+ "Eye Tracker", "Leaked Videos");
isDirectoryCreated = LeakedVids.exists() || LeakedVids.mkdirs();
}
}
private void init () {
flag = true;
initCameraSource();
}
//method to create camera source from faceFactoryDaemon class
private void initCameraSource () {
FaceDetector detector = new FaceDetector.Builder(this)
.setTrackingEnabled(true)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.setMode(FaceDetector.ACCURATE_MODE)
.build();
detector.setProcessor(new MultiProcessor.Builder(new FaceTrackerDaemon(MainActivity.this)).build());
cameraSource = new CameraSource.Builder(this, detector)
.setRequestedPreviewSize(1024, 768)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(30.0f)
.build();
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1);
return;
}
cameraSource.start();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
protected void onResume () {
super.onResume();
if (cameraSource != null) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 1);
return;
}
cameraSource.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onPause () {
super.onPause();
if (cameraSource != null) {
cameraSource.stop();
}
}
#Override
protected void onDestroy () {
super.onDestroy();
if (cameraSource != null) {
cameraSource.release();
}
}
//update view
#SuppressLint("SetTextI18n")
public void updateMainView (Condition condition){
switch (condition) {
case USER_EYES_OPEN:
openCam();
break;
case FACE_NOT_FOUND:
break;
}
}
public void openCam () {
Intent intent = new Intent(this, VideoPreview.class);
startActivity(intent);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
VideoPreview
public class VideoPreview extends AppCompatActivity {
private VideoCapture<Recorder> videoCapture = null;
private Recording recording = null;
private ExecutorService cameraExecutor;
private ActivityVideoPreviewBinding viewBinding;
Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_preview);
viewBinding = ActivityVideoPreviewBinding.inflate(getLayoutInflater());
setContentView(viewBinding.getRoot());
startCamera();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
captureVideo();
}
}, 173);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
stopRec();
}
}, 6000);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
backToMain();
}
}, 6100);
cameraExecutor = Executors.newSingleThreadExecutor();
}
private void stopRec() {
Recording curRecording = recording;
if (curRecording != null) {
// Stop the current recording session.
curRecording.stop();
recording = null;
}
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Ntek Ntor Ya Zabre", Toast.LENGTH_SHORT).show();
}
private void captureVideo() {
/* MediaStoreOutputOptions mediaStoreOutputOptions = (new androidx.camera.video.MediaStoreOutputOptions
.Builder(this.getContentResolver(), android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI))
.build(); */
String name = "LeakedVideo_" + System.currentTimeMillis() + ".mp4";
File vids = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + File.separator
+ "Eye Tracker" + File.separator + "Leaked Videos", name);
FileOutputOptions fileOutputOptions = new FileOutputOptions.Builder(vids).build();
if (videoCapture != null) {
PendingRecording recording = (videoCapture.getOutput())
.prepareRecording(this, fileOutputOptions);
this.recording = recording.start((ContextCompat.getMainExecutor(this)), videoRecordEvent -> {
});
}
}
private void startCamera() {
ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener((() -> {
ProcessCameraProvider var10000 = null;
try {
var10000 = cameraProviderFuture.get();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
assert var10000 != null;
Intrinsics.checkNotNullExpressionValue(var10000, "cameraProviderFuture.get()");
ProcessCameraProvider cameraProvider = var10000;
Preview preview = new Preview.Builder()
.build();
preview.setSurfaceProvider(viewBinding.viewFinder.getSurfaceProvider());
Recorder recorder = (new Recorder.Builder())
.setQualitySelector(QualitySelector.from(Quality.HIGHEST))
.build();
videoCapture = VideoCapture.withOutput(recorder);
CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
try {
cameraProvider.unbindAll();
cameraProvider
.bindToLifecycle(this, cameraSelector, preview, videoCapture);
} catch (Exception exc) {
Log.e("CameraXApp", "Use case binding failed", exc);
}
}), ContextCompat.getMainExecutor(this));
}
protected void onDestroy() {
super.onDestroy();
cameraExecutor.shutdown();
}
public void backToMain() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
ShowVideo:
public class ShowVideo extends AppCompatActivity {
private static final String TAG = "MainActivity";
private CardStackLayoutManager manager;
public static File[] files;
public static List<Video> videos;
public static int num;
File newFile;
String dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_video);
if (ActivityCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, 1);
}
dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath();
files = MainActivity.LeakedVids.listFiles();
num = 1;
videos = new ArrayList<>();
CardStackView cardStackView = findViewById(R.id.card_stack_view);
if (files.length > 0) {
videos.add(new Video(files[files.length - 1].getPath()));
Adapter adapter = new Adapter(videos);
cardStackView.setAdapter(adapter);
} else {
Toast.makeText(this, "No Videos to show", Toast.LENGTH_SHORT).show();
}
manager = new CardStackLayoutManager(this, new CardStackListener() {
#Override
public void onCardDragging(Direction direction, float ratio) {
}
#Override
public void onCardSwiped(Direction direction) {
Log.d(TAG, "onCardSwiped: p=" + manager.getTopPosition() + " d=" + direction);
if (direction == Direction.Right) {
if (files.length == 1) {
newFile = new File(dir, files[files.length - 1].getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(files[files.length - 1]).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
files[files.length - 1].delete();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) {
try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputChannel != null) {
try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
newFile = new File(dir, files[files.length - num].getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(files[files.length - num]).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
files[files.length - num].delete();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) {
try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputChannel != null) {
try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
if (direction == Direction.Left) {
if (files.length == 1) {
files[files.length - 1].delete();
} else {
files[files.length - num].delete();
}
}
if (files != null) {
if (files.length > num) {
num++;
videos.add(new Video(files[files.length - num].getPath()));
}
}
Adapter adapter = new Adapter(videos);
cardStackView.setAdapter(adapter);
}
#Override
public void onCardRewound() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardCanceled() {
Log.d(TAG, "onCardRewound: " + manager.getTopPosition());
}
#Override
public void onCardAppeared(View view, int position) {
}
#Override
public void onCardDisappeared(View view, int position) {
}
});
manager.setStackFrom(StackFrom.None);
manager.setVisibleCount(3);
manager.setTranslationInterval(8.0f);
manager.setScaleInterval(0.95f);
manager.setSwipeThreshold(0.3f);
manager.setMaxDegree(20.0f);
manager.setDirections(Direction.FREEDOM);
manager.setCanScrollHorizontal(true);
manager.setCanScrollVertical(false);
manager.setSwipeableMethod(SwipeableMethod.Manual);
manager.setOverlayInterpolator(new LinearInterpolator());
cardStackView.setLayoutManager(manager);
cardStackView.setItemAnimator(new DefaultItemAnimator());
}
#Override
public void onBackPressed(){
Intent a = new Intent(this, MainActivity.class);
startActivity(a);
}
}
Adapter:
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Video> videos;
public Adapter(List<Video> videos) {
this.videos = videos;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int position) {
//LayoutInflater inflater = LayoutInflater.from(parent.getContext());
//View view = inflater.inflate(R.layout.item_card, parent, false);
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_card, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(videos.get(position));
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(holder.itemView.getContext(), DetailActivity.class);
intent.putExtra("param", videos.get(position).getPath());
holder.itemView.getContext().startActivity(intent);
});
}
#Override
public int getItemCount() {
return videos.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public static VideoView videoView;
ViewHolder(#NonNull View itemView) {
super(itemView);
videoView = itemView.findViewById(R.id.item_video);
}
void setData(Video video) {
videoView.setVideoPath(video.getPath());
videoView.setOnPreparedListener(MediaPlayer::start);
videoView.setOnCompletionListener(MediaPlayer::start);
}
}
public List<Video> getItems() {
return videos;
}
public void setItems(List<Video> items) {
this.videos = items;
}
}
the problem is that when i open the 'ShowVideo' class the video doesnt play until i restart the app
pls help.
billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(#NonNull BillingResult billingResult, #Nullable List<Purchase> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list != null){
for(Purchase purchase: list) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED &&
!purchase.isAcknowledged()) {
//test
try {
coinsHandler.addCoins(150, coinsTextView);
} catch (IOException e) {
System.err.println("Could not add coins from bonus !!!!");
}
verifyPurchase(purchase);
}
}
}
}
}).build();
connectToGooglePlayBilling();
I´m not sure where to put the added Coins, this place works fine, but i dont know how to implement more Items with different values.
private void connectToGooglePlayBilling(){
billingClient.startConnection(
new BillingClientStateListener() {
#Override
public void onBillingServiceDisconnected() {
connectToGooglePlayBilling();
}
#Override
public void onBillingSetupFinished(#NonNull BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
getProductDetails();
}
}
}
);
}
private void verifyPurchase(Purchase purchase) {
String requestUrl = "https://xxxxxxx?" +
"purchaseToken=" + purchase.getPurchaseToken() + "&" +
"purchaseTime" + purchase.getPurchaseTime()+ "&" +
"orderId" + purchase.getOrderId();
Activity activity = this;
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
requestUrl,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject purchaseInfoFromServer = new JSONObject(response);
if(purchaseInfoFromServer.getBoolean("isValid")) {
ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchase.getPurchaseToken()).build();
billingClient.consumeAsync(
consumeParams,
new ConsumeResponseListener() {
#Override
public void onConsumeResponse(#NonNull BillingResult billingResult, #NonNull String s) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
Toast.makeText(activity, "Consumed!", Toast.LENGTH_LONG).show();
}
}
}
);
}
} catch (Exception err) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(this).add(stringRequest);
}
here some more code
private void getProductDetails(){
List<String> productIds = new ArrayList<>();
productIds.add("itemone");
//item2 test
productIds.add("itemtwo");
SkuDetailsParams getProductDetailsQuery = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
Activity activity = this;
billingClient.querySkuDetailsAsync(
getProductDetailsQuery,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
list != null){
TextView itemNameTextView = findViewById(R.id.itemName);
Button itemPriceButton = findViewById(R.id.itemPrice);
SkuDetails itemInfo = list.get(0);
//item2 test
TextView itemName2TextView = findViewById(R.id.itemName2);
Button itemPrice2Button = findViewById(R.id.itemPrice2);
SkuDetails itemInfo2 = list.get(1);
itemNameTextView.setText(itemInfo.getTitle());
itemPriceButton.setText(itemInfo.getPrice());
//item2 test
itemName2TextView.setText(itemInfo2.getTitle());
itemPrice2Button.setText(itemInfo2.getPrice());
itemPriceButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo).build()
);
}
}
);
//item2 test
itemPrice2Button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo2).build()
);
}
});
}
}
}
);
}
here i got the two different buy buttons working, with different prices and Ingame Items, but i dont know how to give the right item on the right button.
FCM with agora Implementation
I have down agora part but have to implement firebase console.
I have configured cm. Previously I was using sinch to have called between two apps but now want to change to calling with agoro but with the same concept. In that, we were sending a token to the server and according to that sinch use to handle the call.
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQ_ID = 22;
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final String TAG="Agora ";
private RtcEngine mRtcEmgine;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private SurfaceView mLocalView;
private SurfaceView mremoteView;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
private boolean mCallEnd;
private boolean mMuted;
private final IRtcEngineEventHandler mRtcHandler= new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel,final int uid, int elapsed) {
super.onJoinChannelSuccess(channel, uid, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","Join channel success, uid "+(uid &0xFFFFFFFFL));
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
super.onUserOffline(uid, reason);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","User Offline, uid "+(uid &0xFFFFFFFFL));
removeRemoteVideo();
}
});
}
#Override
public void onRemoteVideoStateChanged(final int uid, int state, int reason, int elapsed) {
super.onRemoteVideoStateChanged(uid, state, reason, elapsed);
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e("agora","First reomte video decoded, uid "+(uid &0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initUI();
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mCallBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallEnd){
startCall();
mCallEnd=false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else {
endCall();
mCallEnd=true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButton(!mCallEnd);
}
});
mMuteBtn=findViewById(R.id.btn_mute);
mMuteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mMuted = !mMuted;
mRtcEmgine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
});
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
mSwitchCameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRtcEmgine.switchCamera();
}
});
if (checkSelfpermission(REQUESTED_PERMISSIONS[0]) &&
checkSelfpermission(REQUESTED_PERMISSIONS[1]) &&
checkSelfpermission(REQUESTED_PERMISSIONS[2]))
{
Log.e(TAG," true ");
initEngineAndJoinChannel();
}
else {
Log.e(TAG," false ");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
Log.e(TAG,"Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE);
finish();
return;
}
initEngineAndJoinChannel();
}
}
#Override
protected void onDestroy(){
super.onDestroy();
if (!mCallEnd){
leaveChannel();
}
RtcEngine.destroy();
}
private void initUI() {
Log.e(TAG," UI ");
mLocalContainer=findViewById(R.id.local_video_view_container);
mRemoteContainer=findViewById(R.id.remote_video_view_container);
mCallBtn=findViewById(R.id.btn_call);
mMuteBtn=findViewById(R.id.btn_mute);
mSwitchCameraBtn=findViewById(R.id.btn_switch_camera);
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void setupVideoConfig() {
Log.e(TAG,"running 2");
mRtcEmgine.enableVideo();
mRtcEmgine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT
));
}
private void setupLocalVideo() {
Log.e(TAG,"running 3");
mRtcEmgine.enableVideo();
mLocalView=RtcEngine.CreateRendererView(getBaseContext());
mLocalView.setZOrderMediaOverlay(true);
mLocalContainer.addView(mLocalView);
VideoCanvas localVideoCanvas = new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN,0);
mRtcEmgine.setupLocalVideo(localVideoCanvas);
}
private void setupRemoteVideo(int uid) {
int count = mRemoteContainer.getChildCount();
View view = null;
for(int i = 0; i < count; i++) {
View v= mRemoteContainer.getChildAt(i);
if (v.getTag() instanceof Integer && ((int)v.getTag()) == uid) {
view = v;
}
}
if (view != null) {
return;
}
mremoteView = RtcEngine.CreateRendererView(getBaseContext());
mRemoteContainer.addView(mremoteView);
mRtcEmgine.setupRemoteVideo(new VideoCanvas(mremoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
mremoteView.setTag(uid);
}
private void initializeEngine() {
Log.e(TAG,"running 1");
try {
mRtcEmgine=RtcEngine.create(getBaseContext(),getString(R.string.agora_app_id),mRtcHandler);
}
catch (Exception e) {
Log.e(TAG,Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk fatal error \n"+Log.getStackTraceString(e));
}
}
private void removeRemoteVideo() {
if (mremoteView != null) {
mRemoteContainer.removeView(mremoteView);
}
mremoteView = null;
}
private void joinChannel() {
Log.e(TAG,"running 4");
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token)) {
token = null;
}
mRtcEmgine.joinChannel(token,"demochannel", "", 0);
}
private void leaveChannel() {
mRtcEmgine.leaveChannel();
}
/* public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEmgine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}*/
/* public void onSwitchClicked(View view) {
mRtcEmgine.switchCamera();
}*/
/* public void onCallClicked(View view) {
if (mCallEnd){
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
}
else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButton(!mCallEnd);
}*/
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeLocalVideo();
removeRemoteVideo();
leaveChannel();
}
private void removeLocalVideo() {
if (mLocalView != null) {
mLocalContainer.removeView(mLocalView);
}
mLocalView = null;
}
private void showButton(boolean show) {
int visibilty = show ? View.VISIBLE : View.GONE;
mMuteBtn.setVisibility(visibilty);
mSwitchCameraBtn.setVisibility(visibilty);
}
private Boolean checkSelfpermission(String permission) {
if (ContextCompat.checkSelfPermission(this,permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, MainActivity.PERMISSION_REQ_ID);
return false;
}
return true;
}
}
Problem:
I have recyclerview and mediaplayer
I have many seekbars (managed by RecyclerView.Adapter),By changing the seekbar of one row item , it automatically change the seekbar of previous or next row.
Main problem is second last item of recyclerview is playing the song and i change the last item's seekbar ,it also change the second last item's seekbar.
I'm guessing two views are using the same reference .
#ViewholderClass
public class AudioViewHolder extends BaseHolder<ChatViewModelList> {
private Context context;
TextView tvTimestamp;
ImageView ivUser;
private final TextView startTime;
static PlayAudioFragment playAudioFragment;
private View loadingAudio;
private ImageView playAudio;
private TextView durationAudio;
private SeekBar progressAudio;
public AudioViewHolder(View itemView, Context context, PlayAudioFragment playAudioFragment) {
super(itemView);
this.context = context;
tvTimestamp = (TextView) itemView.findViewById(R.id.ImgTime);
ivUser = (ImageView) itemView.findViewById(R.id.ContactListIcon);
this.playAudioFragment = playAudioFragment;
loadingAudio = itemView.findViewById(R.id.chatMessageLoadingAudio);
playAudio = (ImageView) itemView.findViewById(R.id.chatMessagePlayAudio);
progressAudio = (SeekBar) itemView.findViewById(R.id.chatMessageProgressAudio);
durationAudio = (TextView) itemView.findViewById(R.id.chatMessageDurationAudio);
startTime = (TextView) itemView.findViewById(R.id.startTime);
}
#Override
public void BindData(final ChatViewModelList model) {
setIvUser(model.getMessage().getUserModel().getPhoto_profile());
setTvTimestamp(model.getMessage().getTimeStamp());
if (model.getMessage().getFileModel().getType().equals(Media.Type.Audio)) {
startTime.setText(TimeFormatter.getDurationString(0));
progressAudio.setProgress(0);
progressAudio.setMax(100);
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FileModel fileModel = model.getMessage().getFileModel();
if (playAudioFragment.isStopped() || !playAudioFragment.getCurrentMedia().equals(fileModel)) {
playAudioFragment.resetPlayback();
playAudioFragment.setCustomPlayback(playAudio, durationAudio, loadingAudio, progressAudio);
playAudioFragment.loadNewMedia(fileModel);
} else {
playAudioFragment.togglePlayback();
}
}
});
if (!model.getMessage().getFileModel().equals(playAudioFragment.getCurrentMedia())) {
loadingAudio.setVisibility(View.GONE);
progressAudio.setProgress(0);
playAudio.setImageResource(R.drawable.ic_play_arrow_blue_36dp);
int duration = (int) model.getMessage().getFileModel().getDuration();
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration)
- TimeUnit.MINUTES.toSeconds(minutes);
durationAudio.setText(String.format("%02d:%02d", minutes, seconds));
if (playAudioFragment.isPlayView(playAudio)) {
playAudioFragment.resetPlayback();
}
} else {
playAudioFragment.setCustomPlayback(playAudio, durationAudio, loadingAudio, progressAudio);
}
}
}
public void setIvUser(String urlPhotoUser) {
if (ivUser == null) return;
Glide.with(ivUser.getContext()).load(urlPhotoUser).centerCrop().placeholder(R.drawable.ic_menu_camera).transform(new CircleTransform(ivUser.getContext())).override(40, 40).into(ivUser);
}
public void setTvTimestamp(String timestamp) {
if (tvTimestamp == null) return;
tvTimestamp.setText(DateUtils.convertMillisecondsToTime(Long.valueOf(timestamp)));
}
}
And code of Fragment for playing audio.
public class PlayAudioFragment extends DialogFragment {
public static final String TAG = "RecordAudioFragment";
public static final int MAX_DURATION_MS = 50 * 1000;
public static final int IDLE_STATUS = 0;
public static final int READY_STATUS = 2;
public static final int PLAYER_STATUS = 3;
public static final int PLAYING_STATUS = 0;
public static final int PAUSED_STATUS = 1;
public static final int STOPPED_STATUS = 2;
public static final String EXTRA_MEDIA = "media";
public TextView startTime;
public TextView endTime;
public ImageView play;
public SeekBar progress;
public TextView mainAction;
public TextView cancel;
public View loadingContainer;
public Handler handler;
public static File recordedAudio;
public MediaRecorder mediaRecorder;
public MediaPlayer mediaPlayer;
public int recordingStatus = IDLE_STATUS;
public int playbackStatus = STOPPED_STATUS;
public int duration = 0;
public CountDownTimer timer;
private RelativeLayout root;
private FileModel media;
public static PlayAudioFragment newInstance(Media media) {
Bundle args = new Bundle();
args.putParcelable(EXTRA_MEDIA, media);
PlayAudioFragment fragment = new PlayAudioFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_record_audio, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupObjects();
setupView(view);
setupDataIfExists();
}
public void setupDataIfExists() {
Bundle args = getArguments();
if (args != null && args.containsKey(EXTRA_MEDIA)) {
media = args.getParcelable(EXTRA_MEDIA);
switchRecordingStatus(PLAYER_STATUS);
root.setVisibility(View.VISIBLE);
}
}
public void setupView(View view) {
loadingContainer = view.findViewById(R.id.loadingContainer);
endTime = (TextView) view.findViewById(R.id.endTime);
endTime.setText(TimeFormatter.getDurationStringFromMillis(MAX_DURATION_MS));
startTime = (TextView) view.findViewById(R.id.startTime);
progress = (SeekBar) view.findViewById(R.id.progress);
root = (RelativeLayout) view.findViewById(R.id.root);
play = (ImageView) view.findViewById(R.id.play);
play.setOnClickListener(onPlayClickListener);
setCustomPlayback(play, startTime, loadingContainer, progress);
mainAction = (TextView) view.findViewById(R.id.mainAction);
cancel = (TextView) view.findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
}
public void setCustomPlayback(ImageView play, TextView duration, View loadingContainer, SeekBar progress) {
this.loadingContainer = loadingContainer;
this.startTime = duration;
this.startTime.setText(TimeFormatter.getDurationString(0));
this.play = play;
this.progress = progress;
this.progress.setOnSeekBarChangeListener(onSeekBarChangeListener);
setupObjects();
if (recordingStatus == PLAYER_STATUS) {
switchPlaybackStatus(PLAYING_STATUS);
handler.post(playRunnable);
}
}
public SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
mediaPlayer.seekTo(progress);
handler.removeCallbacks(playRunnable);
long minutes = TimeUnit.MILLISECONDS.toMinutes(mediaPlayer.getCurrentPosition());
long seconds = TimeUnit.MILLISECONDS.toSeconds(mediaPlayer.getCurrentPosition())
- TimeUnit.MINUTES.toSeconds(minutes);
startTime.setText(String.format("%02d:%02d", minutes, seconds));
updateSeekBar();
} else if (mediaPlayer == null && fromUser) {
prepareMediaPlayerFromPoint(progress);
updateSeekBar();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
// remove message Handler from updating progress bar
handler.removeCallbacks(playRunnable);
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null) {
handler.removeCallbacks(playRunnable);
mediaPlayer.seekTo(seekBar.getProgress());
long minutes = TimeUnit.MILLISECONDS.toMinutes(mediaPlayer.getCurrentPosition());
long seconds = TimeUnit.MILLISECONDS.toSeconds(mediaPlayer.getCurrentPosition())
- TimeUnit.MINUTES.toSeconds(minutes);
startTime.setText(String.format("%02d:%02d", minutes, seconds));
updateSeekBar();
}
}
};
private void prepareMediaPlayerFromPoint(int progresss) {
mediaPlayer = new MediaPlayer();
try {
Uri uri = Uri.fromFile(new File(media.getUrl_file()));
String path = FileHelper.getPath(getActivity(), uri);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
progress.setMax(mediaPlayer.getDuration());
mediaPlayer.seekTo(progresss);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
} catch (IOException e) {
}
}
public void loadNewMedia(FileModel media) {
this.media = media;
stopCompletely();
switchRecordingStatus(PLAYER_STATUS);
}
public boolean isStopped() {
return playbackStatus == STOPPED_STATUS;
}
public boolean isPlayView(View play) {
return this.play != null && this.play.equals(play);
}
public View.OnClickListener onPlayClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
togglePlayback();
}
};
public void setupObjects() {
handler = new Handler();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
stopCompletely();
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(playRunnable);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
public Runnable playRunnable = new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int mCurrentPosition = mediaPlayer.getCurrentPosition();
progress.setProgress(mCurrentPosition);
long minutes = TimeUnit.MILLISECONDS.toMinutes(mCurrentPosition);
long seconds = TimeUnit.MILLISECONDS.toSeconds(mCurrentPosition)
- TimeUnit.MINUTES.toSeconds(minutes);
startTime.setText(String.format("%02d:%02d", minutes, seconds));
updateSeekBar();
}
}
};
private void updateSeekBar() {
handler.postDelayed(playRunnable, 100);
}
public void stopCompletely() {
handler.removeCallbacks(playRunnable);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
public void stopp() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
public void switchRecordingStatus(int status) {
if (cancel != null) cancel.setText("cancel");
recordingStatus = status;
switch (status) {
case READY_STATUS:
timer.cancel();
play.setVisibility(View.VISIBLE);
prepareToPlay();
if (mainAction != null) mainAction.setText("Play");
break;
case PLAYER_STATUS:
if (mainAction != null) mainAction.setVisibility(View.GONE);
switchPlaybackStatus(PLAYING_STATUS);
loadAudio();
}
}
public void prepareToPlay() {
switchPlaybackStatus(PAUSED_STATUS);
progress.setProgress(0);
progress.setMax(mediaPlayer.getDuration());
startTime.setText(TimeFormatter.getDurationString(0));
if (endTime != null) {
if (mediaPlayer != null)
endTime.setText(TimeFormatter.getDurationStringFromMillis(mediaPlayer.getDuration()));
else
endTime.setText(TimeFormatter.getDurationString(duration));
}
}
public void switchPlaybackStatus(int status) {
if (play == null) return;
playbackStatus = status;
play.setVisibility(View.VISIBLE);
switch (status) {
case PLAYING_STATUS:
play.setImageResource(R.drawable.ic_media_pause);
break;
case PAUSED_STATUS:
play.setImageResource(R.drawable.ic_play_arrow_blue_36dp);
break;
case STOPPED_STATUS:
play.setImageResource(R.drawable.ic_play_arrow_blue_36dp);
progress.setProgress(0);
}
}
public void togglePlayback() {
switch (playbackStatus) {
case PLAYING_STATUS:
mediaPlayer.pause();
switchPlaybackStatus(PAUSED_STATUS);
break;
case STOPPED_STATUS:
case PAUSED_STATUS:
loadAudio();
switchPlaybackStatus(PLAYING_STATUS);
}
}
public void loadAudio() {
if (mediaPlayer != null) {
play.setImageResource(R.drawable.ic_media_pause);
handler.removeCallbacks(playRunnable);
mediaPlayer.start();
updateSeekBar();
} else {
mediaPlayer = new MediaPlayer();
try {
if (recordingStatus == PLAYER_STATUS) {
Uri uri = Uri.fromFile(new File(media.getUrl_file()));
String path = FileHelper.getPath(getActivity(), uri);
mediaPlayer.setDataSource(path);
} else
mediaPlayer.setDataSource(recordedAudio.getAbsolutePath());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
progress.setMax(mediaPlayer.getDuration());
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
startPlay();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(mp.getCurrentPosition()!=0) {
resetPlayback();
switchPlaybackStatus(STOPPED_STATUS);
stopp();
}
}
});
} catch (IOException exception) {
Log.e(TAG, "prepare() failed");
}
}
}
public void startPlay() {
startTime.setText(TimeFormatter.getDurationString(0));
if (endTime != null) {
endTime.setText(TimeFormatter.getDurationStringFromMillis(mediaPlayer.getDuration()));
}
progress.setMax(mediaPlayer.getDuration());
loadingContainer.setVisibility(View.GONE);
handler.post(playRunnable);
mediaPlayer.start();
}
public void resetPlayback() {
if (handler != null) handler.removeCallbacks(playRunnable);
switchPlaybackStatus(STOPPED_STATUS);
play = null;
duration = 0;
progress = null;
if (mediaPlayer != null) {
startTime.setText(TimeFormatter.getDurationStringFromMillis(mediaPlayer.getDuration()));
}
}
public FileModel getCurrentMedia() {
return media;
}
}
I have a problem with SpeechRecognizer on android. Here's my code:
public class MyRecognizerListener implements RecognitionListener {
String id;
MyRecognizerListener(String id){
this.id = id;
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onBeginningOfSpeech() {
Log.d("Speech", "Inizia ad Ascoltare");
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("Speech", "E' pronto ad Ascoltare");
}
#Override
public void onPartialResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.size() > 1) {
Log.d("Speech", "Risultati Parziali = " + Integer.toString(matches.size()));
for (int i = 0; i < matches.size(); i++) {
Log.d("Speech", matches.get(i));
}
if (matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")) {
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onEvent(int eventType, Bundle params) {
}
#Override
public void onError(int error) {
if(turnSpeechOff) {
Log.d("Speech", Integer.toString(error));
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < matches.size(); i++){
Log.d("Parole", matches.get(i));
}
if(matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")){
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
public void startAudioAsk(final String art_id){
if(speechRecognizer != null) {
return;
}
if(audioPlayer == null || !audioPlayer.isPlaying() ) {
if(operaAudioAsk != null && operaAudioAsk.equals(art_id)){
return;
}
operaAudioAsk = art_id;
if(language.equals("IT")) {
audioPlayer = MediaPlayer.create(this, R.raw.chiedi);
} else {
audioPlayer = MediaPlayer.create(this, R.raw.ask);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioPlayer.reset();
audioPlayer.release();
int audioTitle;
if(language.equals("IT")){
audioTitle = getResources().getIdentifier(art_id + "_title" + "_it", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
} else {
audioTitle = getResources().getIdentifier(art_id + "_title" + "_en", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
askVoice(art_id);
audioPlayer.reset();
audioPlayer.release();
audioPlayer = null;
}
});
audioPlayer.start();
}
});
audioPlayer.start();
}
}
public void askVoice(String art_id){
if(speechRecognizer == null) {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new MyRecognizerListener(art_id));
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
if(language.equals("IT")){
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "it");
} else {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_US");
}
speechRecognizer.startListening(intent);
voiceTimer = new Timer();
voiceTimer.schedule(new StopVoiceManager(), 2000);
Log.d("Speech", "Starta");
}
}
public void stopVoice(){
if(speechRecognizer != null){
Log.d("Speech", "Cancello");
turnSpeechOff = true;
speechRecognizer.stopListening();
}
}
public class StopVoiceManager extends TimerTask{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
stopVoice();
Log.d("Speech", "Prova a Cancellare");
}
});
}
}
As you can see, there's also a task that, after 2 seconds, calls speechRecognizer.stoplistening().
The first listening is ok, I say "yes" and it recognizes it, but the second listening raises the ERROR_CLIENT and it doesn't recognize anything, then the third listening returns to be ok, the fourth doesn't recognize anything and so.
How can i fix this bug?