javaDelegate implementation in activiti - alfresco

I am testing service task in activiti with a simple Hello world example.I created this process which will display hello world in the console,but once i run the main i got nothing.
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
<process id="myProcess" name="My process" isExecutable="true">
<serviceTask id="servicetask1" name="Service Task" activiti:class="org.activiti.Test3"></serviceTask>
<startEvent id="startevent1" name="Start"></startEvent>
<endEvent id="endevent1" name="End"></endEvent>
<sequenceFlow id="flow1" sourceRef="startevent1" targetRef="servicetask1"></sequenceFlow>
<sequenceFlow id="flow2" sourceRef="servicetask1" targetRef="endevent1"></sequenceFlow>
</process>
<bpmndi:BPMNDiagram id="BPMNDiagram_myProcess">
<bpmndi:BPMNPlane bpmnElement="myProcess" id="BPMNPlane_myProcess">
<bpmndi:BPMNShape bpmnElement="servicetask1" id="BPMNShape_servicetask1">
<omgdc:Bounds height="55.0" width="105.0" x="370.0" y="130.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="startevent1" id="BPMNShape_startevent1">
<omgdc:Bounds height="35.0" width="35.0" x="210.0" y="140.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape bpmnElement="endevent1" id="BPMNShape_endevent1">
<omgdc:Bounds height="35.0" width="35.0" x="660.0" y="140.0"></omgdc:Bounds>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge bpmnElement="flow1" id="BPMNEdge_flow1">
<omgdi:waypoint x="245.0" y="157.0"></omgdi:waypoint>
<omgdi:waypoint x="370.0" y="157.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge bpmnElement="flow2" id="BPMNEdge_flow2">
<omgdi:waypoint x="475.0" y="157.0"></omgdi:waypoint>
<omgdi:waypoint x="660.0" y="157.0"></omgdi:waypoint>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</definitions>
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
RepositoryService repositoryService = processEngine.getRepositoryService();
repositoryService.createDeployment()
.addClasspathResource("org/activiti/test/yz.bpmn")
.deploy();
//starting it
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("employeeName", "Kermit");
variables.put("numberOfDays", new Integer(4));
variables.put("vacationMotivation", "I'm really tired!");
RuntimeService runtimeService = processEngine.getRuntimeService();
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myProcess");
// Fetch all tasks for the management group
TaskService taskService = processEngine.getTaskService();
java.util.List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery().taskCandidateGroup("management").list();
for (org.activiti.engine.task.Task task : tasks) {
System.out.println("Task available: " + task.getName());
}
}
}
public class Test3 implements JavaDelegate{
public void execute(DelegateExecution arg0) throws Exception {
System.out.println("tessssssssssssst");
}
}

You can use something like below,
public class Test3Delegate extends BaseJavaDelegate{
#Override
public void execute(DelegateExecution delegate) throws Exception
{
System.out.println("tessssssssssssst");
}
}
And in the bpmn file, you can refer as delegateExpression,
<serviceTask id="servicetask1" name="Service Task" activiti:delegateExpression="${Test3Delegate}"></serviceTask>
In the module context file, register this like below,
<bean id="Test3Delegate" parent="BaseJavaDelegate" class="package.name.Test3Delegate"></bean>
Hope this helps you.

the problem was in the process engine configuration

Related

Screen flickers between black and white before freezing on startup after idling

I have an issue with my Xamarin Forms Android app where after idling (a number of hours), when the app resumes there will be a blank screen and then it rapidly flickers black and white for a few seconds and then goes blank and freezes up. I don't think it's getting as far as the PCL, and I get no crash logs for it. This happens on debug and release builds and on a number of real devices, including Android 13.
The only remedy is to close the app and reopen and then it works without an issue.
It may coincide with the device theme changing from light to dark and vice versa and a long idle period. If the device theme is changed on demand and the app closed and reopened, it doesn't suffer from the flicker.
Epilepsy warning
I have a video of it: https://drive.google.com/file/d/1baXvGLYpDoM9DUo5Y9L03HovCNfDOKSV/view?usp=share_link
I am really struggling to find where the offending code is, and I can't debug it because it doesn't happen for hours or days.
As for the app, there are two activities:
Splash activity
[Activity(MainLauncher = true, NoHistory = true)]
public class SplashActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
}
catch (Exception ex)
{
//Attempted error handling
}
}
protected override void OnStart()
{
try
{
base.OnStart();
StartActivity(new Intent(Application.Context, typeof(MainActivity)).PutExtras(Intent));
}
catch (Exception ex)
{
//Attempted error handling
}
finally
{
Finish();
}
}
public override void OnBackPressed() { }
}
And
Main activity
[Activity(Icon = "#mipmap/ic_launcher", Theme = "#style/MainTheme", MainLauncher = false, LaunchMode = LaunchMode.SingleTask, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize, ResizeableActivity = false, NoHistory = false, Exported = true)]
//auth0 intent filter
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IOnSuccessListener
{
INotificationActionService _notificationActionService;
IDeviceInstallationService _deviceInstallationService;
INotificationActionService NotificationActionService => _notificationActionService ??= ServiceContainer.Resolve<INotificationActionService>();
IDeviceInstallationService DeviceInstallationService => _deviceInstallationService ??= ServiceContainer.Resolve<IDeviceInstallationService>();
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Bootstrap.Begin(() => new DeviceInstallationService());
if (DeviceInstallationService.NotificationsSupported)
{
FirebaseMessaging.Instance.GetToken().AddOnSuccessListener(this, this);
}
Rg.Plugins.Popup.Popup.Init(this);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
CrossCurrentActivity.Current.Init(this, savedInstanceState);
Forms.Init(this, savedInstanceState);
InitFontScale();
CachedImageRenderer.Init(true);
_ = typeof(SvgCachedImage);
UserDialogs.Init(this);
LoadApplication(new App());
ProcessNotificationActions(Intent);
}
catch (Exception ex)
{
//Attempted error handling
}
}
public override void OnBackPressed() => Rg.Plugins.Popup.Popup.SendBackPressed(base.OnBackPressed);
public void OnSuccess(Java.Lang.Object result) => DeviceInstallationService.Token = result.ToString();
private void InitFontScale()
{
var configuration = Resources.Configuration;
configuration.FontScale = Math.Min(1f, configuration.FontScale);
//0.85 small, 1 standard, 1.15 big,1.3 more bigger ,1.45 super big
var metrics = new DisplayMetrics();
#pragma warning disable CS0618 // Type or member is obsolete
WindowManager.DefaultDisplay.GetMetrics(metrics);
#pragma warning restore CS0618 // Type or member is obsolete
metrics.ScaledDensity = configuration.FontScale * metrics.Density;
BaseContext.ApplicationContext.CreateConfigurationContext(configuration);
BaseContext.Resources.DisplayMetrics.SetTo(metrics);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected override void OnResume()
{
try
{
var culture = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentCulture = culture;
Thread.CurrentThread.CurrentCulture = culture;
InitFontScale();
base.OnResume();
}
catch (Exception ex)
{
//Attempted error handling
}
}
protected override void OnNewIntent(Intent intent)
{
try
{
base.OnNewIntent(intent);
Auth0.OidcClient.ActivityMediator.Instance.Send(intent.DataString);
ProcessNotificationActions(intent);
}
catch (Exception ex)
{
//Attempted error handling
}
}
private void ProcessNotificationActions(Intent intent)
{
try
{
if (intent?.HasExtra("action") == true)
{
var bundle = intent.Extras;
var dict = bundle.KeySet().ToDictionary(key => key, key => bundle.Get(key).ToString());
var action = intent.GetStringExtra("action");
if (!string.IsNullOrEmpty(action))
{
NotificationActionService.TriggerAction(action, dict);
}
}
}
catch (Exception ex)
{
//Attempted error handling
}
}
}
And
some styles
values styles.xml
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
<item name="colorAccent">#3E94FF</item>
<item name="android:datePickerDialogTheme">#style/CustomDatePickerDialog</item>
</style>
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowIsTranslucent">true</item>
</style>
<style name="CustomDatePickerDialog" parent="ThemeOverlay.AppCompat.Dialog">
<!--header background-->
<item name="colorAccent">#3E94FF</item>
<!--selected day-->
<item name="android:colorControlActivated">#3E94FF</item>
<!--cancel&ok-->
<item name="android:textColor">#000000</item>
</style>
</resources>
values-night styles.xml
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
<item name="colorAccent">#3E94FF</item>
<item name="android:datePickerDialogTheme">#style/CustomDatePickerDialog</item>
</style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/splash</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowIsTranslucent">true</item>
</style>
<style name="CustomDatePickerDialog" parent="ThemeOverlay.AppCompat.Dialog">
<!--selected day-->
<item name="android:colorControlActivated">#3E94FF</item>
<!--cancel&ok-->
<item name="android:textColor">#ffffff</item>
<!--body background-->
<item name="android:windowBackground">#2F343C</item>
<!--days of the month-->
<item name="android:textColorPrimary">#9BA3B1</item>
<!--days of the week-->
<item name="android:textColorSecondary">#ffffff</item>
</style>
</resources>
The application tag in the manifest has the splash theme as the style
android:theme="#style/SplashTheme"
Any help with pinpointing the cause would be very much appreciated.
Thank you.
I have tried combining it into one activity to see if it was the transition from the splash to the main activity.
I have also changed it to the splash activity explicitly starting the main activity and finishing itself, but it made no difference.
As I thought it may be the main activity not getting closed properly, I have also used a timer to finish the activity after 5 minutes in the background, but it still occurred.
Well to start with Android 12 and above doesn't support a separate SplashScreen Activity, so you would need to get rid of that. See https://developer.android.com/develop/ui/views/launch/splash-screen for the full details.
If you want to see how it should be done in Xamarin.Android take a look at https://github.com/gmck/XamarinBasicSplashScreen. Works from API 21 - 33.

Overlapping of fragments when transiting on clicking on an item in RecyclerView of one fragment to another new fragment

I am new to android development. The problem is the RecyclerView populated using a firebase database is not replaced by a new fragment, rather the new fragment is on top, but clicking on another item of the recycler view still works, which I checked using a toast in the new fragment. I know that the next fragment is there because I have TextView at the bottom, which is visible on clicking on the recycler view Item.
Here is my code
adapter = new FirebaseRecyclerAdapter<Categories, CategoryViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final CategoryViewHolder holder, int position, #NonNull Categories model)
{
Picasso.get().load(model.getImage()).placeholder(R.drawable.camera).into(holder.categoryImage, new Callback() {
#Override
public void onSuccess()
{
}
#Override
public void onError(Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
holder.categoryName.setText(model.getName());
holder.categoryImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), holder.categoryName.getText().toString(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(getActivity(), ProductListActivity.class);
// startActivity(intent);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
SearchFragment fragment = SearchFragment.newInstance(holder.categoryName.getText().toString());
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, fragment, SearchFragment.class.getSimpleName());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
The fragment I am using is also used for the navigation drawer using navController.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" />
</RelativeLayout>
Edit: I have another recyclerView inside SearchFragment, which didn't show after I clicked an image in the RecyclerView(One which calls SearchFragment). But it showed after I minimized and opened the app again. I don't understand why that is happening.
I just found an easy way to move from one fragment to another without using FragmentManager. I hope this helps others, it worked for me. Initialize the NavController in the first fragment inside onCreateView
navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
And adding the following for transition
Bundle bundle = new Bundle();
bundle.putString("Category", holder.categoryName.getText().toString());
navController.navigate(R.id.nav_category_product_list, bundle);
to get the argument in the moving fragment type this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); //To get menu items at the top
if (getArguments() != null) {
Category = getArguments().getString("Category");
}
}
Also, add this transition in Navigation graph XML
.
.
.
<fragment
android:id="#+id/nav_category"
android:name="com.grocery.admin.ui.category.CategoryFragment"
android:label="#string/menu_category"
tools:layout="#layout/fragment_category" >
<action
android:id="#+id/action_nav_category_to_nav_category_product_list"
app:destination="#id/nav_category_product_list" />
</fragment>
<fragment
android:id="#+id/nav_category_product_list"
android:name="com.grocery.admin.ui.category.CategoryProductFragment"
android:label="Product List"
tools:layout="#layout/fragment_category_product">
</fragment>
.
.
.

Android Accessibility service real time audio processing

Can someone please provide me a sample code for Android Accessibility service real time audio processing. I need to process the call audio. But don't know How to achieve this. Please share your thoughts on this
Please find below Manifest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mycalltest">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<service
android:name=".MyAccessibilityService"
android:label="#string/accessibility_service_label"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibility_service_config" />
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Please find below acessibility xml:
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:description="#string/accessibility_service_description"
android:accessibilityEventTypes="typeWindowContentChanged|typeWindowStateChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:notificationTimeout="100"
android:accessibilityFlags="flagReportViewIds|flagRetrieveInteractiveWindows"
android:canRetrieveWindowContent="true"
/>
PFB the Service :
import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MyAccessibilityService extends AccessibilityService {
private static final String TAG="MyAccessibilityService";
private Context context;
public static final String CHANNEL_ID = "MyAccessibilityService";
MediaRecorder mRecorder;
private boolean isStarted;
byte buffer[] = new byte[8916];
private MediaSaver mediaSaver;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"MyAccessibilityService Salesken Started ...");
context=this;
startForegroundService();
}
private void startForegroundService() {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("recording Service")
.setContentText("Start")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Recording Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case SaleskenIntent.START_RECORDING:
Log.d(TAG,"Start Recording");
//startRecorder();
String contact = intent.getStringExtra("contact");
startRecording(contact);
break;
case SaleskenIntent.STOP_RECORDING:
Log.d(TAG,"Stop Recording");
stopRecording();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
#Override
public void onInterrupt() {
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void startRecording(String contact) {
try {
String timestamp = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss", Locale.US).format(new Date());
String fileName =timestamp+".3gp";
mediaSaver = new MediaSaver(context).setParentDirectoryName("Accessibility").
setFileNameKeepOriginalExtension(fileName).
setExternal(MediaSaver.isExternalStorageReadable());
//String selectedPath = Environment.getExternalStorageDirectory() + "/Testing";
//String selectedPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Android/data/" + packageName + "/system_sound";
mRecorder = new MediaRecorder();
mRecorder.reset();
//android.permission.MODIFY_AUDIO_SETTINGS
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); //turn on speaker
if (mAudioManager != null) {
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); //MODE_IN_COMMUNICATION | MODE_IN_CALL
// mAudioManager.setSpeakerphoneOn(true);
// mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0); // increase Volume
hasWiredHeadset(mAudioManager);
}
//android.permission.RECORD_AUDIO
String manufacturer = Build.MANUFACTURER;
Log.d(TAG, manufacturer);
/* if (manufacturer.toLowerCase().contains("samsung")) {
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
} else {
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
}*/
/*
VOICE_CALL is the actual call data being sent in a call, up and down (so your side and their side). VOICE_COMMUNICATION is just the microphone, but with codecs and echo cancellation turned on for good voice quality.
*/
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION); //MIC | VOICE_COMMUNICATION (Android 10 release) | VOICE_RECOGNITION | (VOICE_CALL = VOICE_UPLINK + VOICE_DOWNLINK)
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); //THREE_GPP | MPEG_4
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); //AMR_NB | AAC
mRecorder.setOutputFile(mediaSaver.pathFile().getAbsolutePath());
mRecorder.prepare();
mRecorder.start();
isStarted = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopRecording() {
if (isStarted && mRecorder != null) {
mRecorder.stop();
mRecorder.reset(); // You can reuse the object by going back to setAudioSource() step
mRecorder.release();
mRecorder = null;
isStarted = false;
}
}
// To detect the connected other device like headphone, wifi headphone, usb headphone etc
private boolean hasWiredHeadset(AudioManager mAudioManager) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return mAudioManager.isWiredHeadsetOn();
} else {
final AudioDeviceInfo[] devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_ALL);
for (AudioDeviceInfo device : devices) {
final int type = device.getType();
if (type == AudioDeviceInfo.TYPE_WIRED_HEADSET) {
Log.d(TAG, "hasWiredHeadset: found wired headset");
return true;
} else if (type == AudioDeviceInfo.TYPE_USB_DEVICE) {
Log.d(TAG, "hasWiredHeadset: found USB audio device");
return true;
} else if (type == AudioDeviceInfo.TYPE_TELEPHONY) {
Log.d(TAG, "hasWiredHeadset: found audio signals over the telephony network");
return true;
}
}
return false;
}
}
}
You need to change the audio source input.

Pushpin location binding in windows phone 8 app is not working

i am developing a windows phone 8 app, in which i have to display a pushpin to current location.
while running the code it is showing an exception:
"An exception of type 'System.NullReferenceException' occurred in MapTestApp.DLL but was not handled in user code"
public MainPage()
{
InitializeComponent();
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 100; // The units are meters.
geolocator.StatusChanged += geolocator_StatusChanged;
geolocator.PositionChanged += geolocator_PositionChanged;
}
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
pushpin1.DataContext = args.Position.Coordinate;
});
}
.xaml code:
<maps:Map x:Name="MyMap" Center="{Binding}" ZoomLevel="15">
<toolkit:MapExtensions.Children>
<toolkit:Pushpin x:Name="pushpin1" GeoCoordinate="{Binding}">
<toolkit:Pushpin.Template>
<ControlTemplate TargetType="toolkit:Pushpin">
<StackPanel>
<ContentPresenter x:Name="content" Content="{TemplateBinding Content}" HorizontalAlignment="Left"></ContentPresenter>
<Path Data="M0,0L1,1L2,0L2,0L1,0L0,0Z"
Fill="#00AAFF"
Stretch="Fill"
Margin="-2,0"
Height="120"
Width="30"
Visibility="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Visibility, Mode=TwoWay}"
HorizontalAlignment="Left"
/>
</StackPanel>
</ControlTemplate>
</toolkit:Pushpin.Template>
</toolkit:Pushpin>
</toolkit:MapExtensions.Children>
</maps:Map>
Here is the link to the exception screen, it shows pushpin as null object: https://docs.google.com/file/d/0By0Y-Dca1cKjYXp4T3ctV1hLUEk/edit?usp=sharing
Please try this attached property
public static class PushPinExtension
{
public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached("ItemsSource",
typeof(IEnumerable), typeof(PushPinExtension),
new PropertyMetadata(OnPushPinPropertyChanged));
private static void OnPushPinPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
var pushpin = MapExtensions.GetChildren((Map)uie).OfType<MapItemsControl>().FirstOrDefault();
if (pushpin != null) pushpin.ItemsSource = (IEnumerable)e.NewValue;
}
public static IEnumerable GetItemsSource(DependencyObject obj)
{
return (IEnumerable)obj.GetValue(ItemsSourceProperty);
}
public static void SetItemsSource(DependencyObject obj, IEnumerable value)
{
obj.SetValue(ItemsSourceProperty, value);
}
}
dp:PushPinExtension.ItemsSource="{Binding Path=PushpinCollection}"

Storing Accelerometer Values

I want to develop an app which
Creates a file in external storage
2.Writes accelerometer readings to the file whenever start button is clicked
3.Stops writing when stop button is clicked
4.Reads the contents of the file on the click of read button
I don't know how to create a file in external storage and store the readings of accelerometer in it and later read the values from the file.
I tried the following code in MainACtivity.java
package com.example.startstopbuttonaccelerometerreading;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2;
RelativeLayout layout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title=(TextView)findViewById(R.id.name);
tv=(TextView)findViewById(R.id.xval);
tv1=(TextView)findViewById(R.id.yval);
tv2=(TextView)findViewById(R.id.zval);
}
public void onStartClick(View view) {
final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;
try {
File myFile = new File("/sdcard/acc.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(acc);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'acc.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
// write on SD card file data in the text box
int sensorType = Sensor.TYPE_ACCELEROMETER;
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}// onClick
;
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
This is the activity_main.xml code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="#+id/relative" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="124dp"
android:text="Start"
android:onClick="onStartClick" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="37dp"
android:layout_toRightOf="#+id/button1"
android:text="Stop"
android:onClick="onStopClick" />
<TextView
android:textSize="30dp"
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:textSize="20dp"
android:layout_below="#+id/name"
android:id="#+id/xval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:textSize="20dp"
android:id="#+id/yval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/xval"
/>
<TextView
android:textSize="20dp"
android:id="#+id/zval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/yval"
/>
</RelativeLayout>
I wrote the permission in androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity is not getting compiled. The errors are acc and textview cant be resolved.
I want to know the code to create a file in external storage and write accelerometer readings to it and read data from the file.
I have rewrote your code as the following including AndroidManifest.xml, activity_main.xml and MainActivity.java.
There are three buttons in this program.
1.Start: Start to write three-axis data into acc.txt.
2.Stop: Stop writing data.
3.Read: Read all data in acc.txt
And I create a edit text to show the content in acc.txt after the Read button is clicked.
There are some delay time in this program. You can adjust it by yourself.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.so_problem"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.so_problem.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="#+id/relative" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="124dp"
android:text="Start"
android:onClick="onStartClick" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="37dp"
android:layout_toRightOf="#+id/button1"
android:text="Stop"
android:onClick="onStopClick" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/button2"
android:layout_centerVertical="true"
android:text="Read"
android:onClick="onReadClick" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp" />
<TextView
android:textSize="20dp"
android:layout_below="#+id/name"
android:id="#+id/xval"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:textSize="20dp"
android:id="#+id/yval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/xval" />
<TextView
android:textSize="20dp"
android:id="#+id/zval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/yval" />
<EditText
android:id="#+id/showval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/zval"
android:layout_alignRight="#+id/zval"
android:layout_below="#+id/button3"
android:layout_marginTop="18dp"
android:clickable="false"
android:cursorVisible="false"
android:editable="false"
android:ems="10"
android:freezesText="true"
android:inputType="none"
android:lines="8"
android:maxLines="1000"
android:scrollbars="vertical"
android:singleLine="false" />
</RelativeLayout>
MainActivity.java
package com.example.so_problem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tvx,tvy,tvz;
EditText etshowval;
RelativeLayout layout;
private String acc;
private String read_str = "";
private final String filepath = "/mnt/sdcard/acc.txt";
private BufferedWriter mBufferedWriter;
private BufferedReader mBufferedReader;
private float x;
private float y;
private float z;
public static final int MSG_DONE = 1;
public static final int MSG_ERROR = 2;
public static final int MSG_STOP = 3;
private boolean mrunning;
private Handler mHandler;
private HandlerThread mHandlerThread;
private Handler uiHandler = new Handler(){
public void handleMessage(Message msg){
String str = (String) msg.obj;
switch (msg.what)
{
case MSG_DONE:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
break;
case MSG_ERROR:
Toast.makeText(getBaseContext(),str,
Toast.LENGTH_SHORT).show();
break;
case MSG_STOP:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
default:
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title = (TextView)findViewById(R.id.name);
tvx = (TextView)findViewById(R.id.xval);
tvy = (TextView)findViewById(R.id.yval);
tvz = (TextView)findViewById(R.id.zval);
etshowval = (EditText)findViewById(R.id.showval);
title.setText("Accelerator");
mHandlerThread = new HandlerThread("Working Thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(r);
}
private Runnable r = new Runnable(){
#Override
public void run ()
{
while(true)
{
if (mrunning)
{
Message msg1 = new Message();
try
{
WriteFile(filepath,acc);
msg1.what = MSG_DONE;
msg1.obj = "Start to write to SD 'acc.txt'";
}
catch (Exception e)
{
msg1.what = MSG_ERROR;
msg1.obj = e.getMessage();
}
uiHandler.sendMessage(msg1);
}
else
{
Message msg2 = new Message();
msg2.what = MSG_STOP;
msg2.obj = "Stop to write to SD 'acc.txt'";
uiHandler.sendMessage(msg2);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
public void onStartClick(View view)
{
start();
}
public void onStopClick(View view)
{
stop();
}
public void onReadClick(View view)
{
etshowval.setText(ReadFile(filepath));
}
private synchronized void start()
{
mrunning = true;
}
private synchronized void stop()
{
mrunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
#Override
public void onSensorChanged(SensorEvent sensorEvent)
{
// TODO Auto-generated method stub
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
x = sensorEvent.values[0];
y = sensorEvent.values[1];
z = sensorEvent.values[2];
acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
tvx.setText("X = "+ String.valueOf(x));
tvy.setText("Y = "+ String.valueOf(y));
tvz.setText("Z = "+ String.valueOf(z));
}
}
public void CreateFile(String path)
{
File f = new File(path);
try {
Log.d("ACTIVITY", "Create a File.");
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ReadFile (String filepath)
{
mBufferedReader = null;
String tmp = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedReader = new BufferedReader(new FileReader(filepath));
// Read string
while ((tmp = mBufferedReader.readLine()) != null)
{
tmp += "\n";
read_str += tmp;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return read_str;
}
public void WriteFile(String filepath, String str)
{
mBufferedWriter = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
mBufferedWriter.write(str);
mBufferedWriter.newLine();
mBufferedWriter.flush();
mBufferedWriter.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean FileIsExist(String filepath)
{
File f = new File(filepath);
if (! f.exists())
{
Log.e("ACTIVITY", "File does not exist.");
return false;
}
else
return true;
}
#Override
protected void onPause()
{
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
super.onPause();
}
}
textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;
You didn't declare the "textView" or "acc" variables anywhere
Even after fixing this issue, the code sample you provided above, will end in having a file with only the most recent sensor event records only.. because it creates a new file everytime a sensor event happens, writes the measurements to it, and closes it. When a new measurement is delivered a new file will be created using the same name and so will remove the old entry.
A Good practice to perform that task might be as follows:
Store the file stream as a private variable in your activity
In the start button's click event handler, open the file or create it if not existing .. and store its stream to the private variable of your activity..Also register listener to the accelerometer sensor events.
In the onSensorChanged event, append the new measurements to the file stream
In the stop button's click event handler, unregister the lisetener, and close the file stream.

Resources