Android Accessibility service real time audio processing - accessibility

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.

Related

Xamarin Gets WiFi List from Android

###################################
# MainActivity.cs
###################################
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Content;
using System.Collections.Generic;
using Android.Net.Wifi;
using System.Text;
using Java.Lang;
using Xamarin.Forms;
using StringBuilder = System.Text.StringBuilder;
using Menu = Android.Views.Menu;
using System.Threading.Tasks;
using System.Threading;
[assembly: Xamarin.Forms.Dependency(typeof(App1.Droid.Wifi))]
namespace App1.Droid
{
[Activity(Label = "App1", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public class Wifi : IWifi
{
private Context context = null;
public Wifi()
{
this.context = Android.App.Application.Context;
}
public async Task<IEnumerable<string>> GetAvailableNetworksAsync()
{
IEnumerable<string> availableNetworks = null;
// Get a handle to the Wifi
var wifiMgr = (WifiManager)context.GetSystemService(Context.WifiService);
var wifiReceiver = new WifiReceiver(wifiMgr);
await Task.Run(() =>
{
// Start a scan and register the Broadcast receiver to get the list of Wifi Networks
context.RegisterReceiver(wifiReceiver, new IntentFilter(WifiManager.ScanResultsAvailableAction));
availableNetworks = wifiReceiver.Scan();
});
return availableNetworks;
}
[BroadcastReceiver(Enabled = true, Exported = false)]
class WifiReceiver : BroadcastReceiver
{
private WifiManager wifi;
private List<string> wifiNetworks;
private AutoResetEvent receiverARE;
private Timer tmr;
private const int TIMEOUT_MILLIS = 10000; // 20 seconds timeout
public WifiReceiver()
{
}
public WifiReceiver(WifiManager wifi)
{
this.wifi = wifi;
wifiNetworks = new List<string>();
receiverARE = new AutoResetEvent(false);
}
public IEnumerable<string> Scan()
{
tmr = new Timer(Timeout, null, TIMEOUT_MILLIS, System.Threading.Timeout.Infinite);
wifi.StartScan();
receiverARE.WaitOne();
return wifiNetworks;
}
public override void OnReceive(Context context, Intent intent)
{
IList<ScanResult> scanwifinetworks = wifi.ScanResults;
foreach (ScanResult wifinetwork in scanwifinetworks)
{
wifiNetworks.Add(wifinetwork.Ssid);
}
receiverARE.Set();
}
private void Timeout(object sender)
{
// NOTE release scan, which we are using now, or we throw an error?
receiverARE.Set();
}
}
}
}
###################################
# MainPage.xaml.cs
###################################
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App1
{
public interface IWifi
{
Task<IEnumerable<string>> GetAvailableNetworksAsync();
}
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void btn1_Clicked(object sender, EventArgs e)
{
IEnumerable<string> _wifiService = null;
_wifiService = await DependencyService.Get<IWifi>().GetAvailableNetworksAsync();
txtlog.Text = _wifiService.Count().ToString();
wifilist.ItemsSource = _wifiService;
//Device.StartTimer(new TimeSpan(0, 0, 60), () =>
//{
// // do something every 60 seconds
// Device.BeginInvokeOnMainThread(async () =>
// {
// IEnumerable<string> _wifiService = null;
// _wifiService = await DependencyService.Get<IWifi>().GetAvailableNetworksAsync();
// wifilist.ItemsSource = _wifiService;
// //txtlog.Text = _wifiService.Count<int>();
// //editLog.add
// });
// return true; // runs again, or false to stop
//});
//IEnumerable<string> test1 = new IEnumerable<string>;
//wifilist.
//ListView listview = FindViewByID<ListView>(Resources.Id)
//listview.setAdapter(adapter);
//List<string> lstItems;
//for (int i = 0; i < 10; i ++)
//{
//}
//wifilist.ItemsSource = lstItems;
}
}
}
###################################
# MainPage.xaml.cs
###################################
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.app1" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="30" />
<application android:label="App1.Android" android:theme="#style/MainTheme"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>
I tried following the example, but I can't get the wifi list. What am I doing wrong?
Here is a link to the example I referenced.
referenced example
I plan to use Android 10 or higher.
And I'm going to test it by putting Android OS on the Raspberry Pi board in the development environment.
From the code, I understood that you are trying to get the list of available wifi connections.
I have tried your code and I am able to get the wifi list.
Please check whether you have done below things, if not please do
enable device location
allow location permission for your app (either from your code or from device settings)
Hope this helps!

java.lang.IllegalStateException: no current navigation node in Kotlin NavigationComponent App

I was developing an Kotin App which make use of Navigation component to moves between the diferents screen of the App.
My problems comes when I try to separate the root_navigation.xml of the main_navigation.xml
The main structure of my app is a splashScreen which send you to LoginScreen, where you can authenticated which firebase via Googe Provider or email/password provider.
The HGoogle Authentication works fine, and send you to the HomeFragment of the App, but the Authentication with email/password rise the above title error.
The code of my navigation files are the following
mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="#+id/mobile_navigation"
app:startDestination="#+id/nav_login">
<fragment
android:id="#+id/nav_login"
android:name="com.example.appadoskotlin2.ui.login.LoginFragment"
android:label="Login"
tools:layout="#layout/fragment_login">
<action
android:id="#+id/navigation_login_to_navigation_home"
app:destination="#id/nav_home"/>
</fragment>
<fragment
android:id="#+id/nav_home"
android:name="com.example.appadoskotlin2.ui.home.HomeFragment"
android:label="#string/menu_home"
tools:layout="#layout/fragment_home">
<action
android:id="#+id/navigation_home_to_navigation_item_home"
app:destination="#id/navigation_item_home"/>
</fragment>
<fragment
android:id="#+id/navigation_item_home"
android:name="com.example.appadoskotlin2.ui.home.ItemServiceFragment"
android:label="Servicios"
tools:layout="#layout/item_list">
<argument
android:name="item"
app:argType="com.example.appadoskotlin2.data.Service"/>
</fragment>
<fragment
android:id="#+id/nav_contract"
android:name="com.example.appadoskotlin2.ui.contract.ContractFragment"
android:label="#string/menu_contract"
tools:layout="#layout/fragment_contract">
<action
android:id="#+id/navigation_contract_to_navigation_item_contract"
app:destination="#id/navigation_item_contract"/>
</fragment>
<fragment
android:id="#+id/navigation_item_contract"
android:name="com.example.appadoskotlin2.ui.home.ItemServiceFragment"
android:label="Servicios"
tools:layout="#layout/item_list">
</fragment>
<fragment
android:id="#+id/nav_publish"
android:name="com.example.appadoskotlin2.ui.publish.PublishFragment"
android:label="#string/menu_publish"
tools:layout="#layout/fragment_publish">
<action
android:id="#+id/navigation_publish_to_navigation_item_publish"
app:destination="#id/navigation_item_publish"/>
</fragment>
<fragment
android:id="#+id/navigation_item_publish"
android:name="com.example.appadoskotlin2.ui.publish.ItemPublishFragment"
android:label="Servicios"
tools:layout="#layout/item_list">
</fragment>
</navigation>
root_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="#+id/root_navigation"
app:startDestination="#+id/navigation_splash">
<activity
android:id="#+id/navigation_splash"
android:name="com.example.appadoskotlin2.SplashActivity"
android:label="activity_splash"
tools:layout="#layout/activity_splash" >
<action
android:id="#+id/action_navigation_splash_to_navigation_login"
app:destination="#id/navigation_login" />
</activity>
<activity
android:id="#+id/navigation_login"
android:name="com.example.appadoskotlin2.MainActivity"
android:label="activity_login"
tools:layout="#layout/activity_main" >
<action
android:id="#+id/action_navigation_login_to_navigation_main"
app:destination="#id/navigation_main" />
</activity>
<activity
android:id="#+id/navigation_main"
android:name="com.example.appadoskotlin2.MainActivity"
android:label="MainActivity"
tools:layout="#layout/activity_main"/>
</navigation>
And the code of my LoginFragment and MainActivty of the App are these:
MainActivity.kt
package com.example.appadoskotlin2
import android.os.Bundle
import android.view.Menu
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.navigation.NavigationView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import com.example.appadoskotlin2.databinding.ActivityMainBinding
import com.example.appadoskotlin2.ui.home.HomeFragment
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.appBarMain.toolbar)
binding.appBarMain.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawerLayout: DrawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_content_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(setOf(R.id.nav_login,
R.id.nav_home, R.id.nav_contract, R.id.nav_publish), drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
LoginFragment.kt
package com.example.appadoskotlin2.ui.login
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.appadoskotlin2.R
import com.example.appadoskotlin2.databinding.FragmentLoginBinding
import com.example.appadoskotlin2.ui.diologs.LoginDialog
import com.example.appadoskotlin2.ui.diologs.RegisterDialog
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.material.button.MaterialButton
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth
class LoginFragment: Fragment() {
private val RC_SIGN_IN = 123
private lateinit var navController : NavController
private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!!
private var firebaseAuth: FirebaseAuth? = null
private var mGoogleSignIn: GoogleSignInClient? = null
private var btn_google: MaterialButton? = null
private var btn_register: MaterialButton? = null
private var btn_login: MaterialButton? = null
private var diolog_register: RegisterDialog? = null
private var diolog_login: LoginDialog? = null
//TODO("Configurar firebase y linkear la vista")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
_binding = FragmentLoginBinding.inflate(inflater, container, false)
val root: View = binding.root
initView(root)
initListeners()
return root
}
private fun initListeners() {
val loginActivity: LoginFragment = this
btn_google?.setOnClickListener(View.OnClickListener {
createRequest()
signIn()
})
btn_register?.setOnClickListener(View.OnClickListener {
diolog_register = RegisterDialog(firebaseAuth, loginActivity)
fragmentManager?.let { it1 -> diolog_register!!.show(it1, "RegisterDiolog") }
})
btn_login?.setOnClickListener(View.OnClickListener {
diolog_login = LoginDialog(firebaseAuth, this.context)
fragmentManager?.let { it1 -> diolog_login!!.show(it1, "LoginDiolog") }
})
}
fun initView(root: View){
btn_google = root.findViewById(R.id.btn_google)
btn_register = root.findViewById(R.id.btn_register)
btn_login = root.findViewById(R.id.btn_login)
context?.let { FirebaseApp.initializeApp(it) }
firebaseAuth = FirebaseAuth.getInstance()
}
private fun signIn() {
val signInIntent = mGoogleSignIn!!.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
showHome()
}
private fun showHome() {
navController = Navigation.findNavController(this.requireView())
navController.navigate(R.id.navigation_login_to_navigation_home)
Toast.makeText(context, "Login completed successfully", Toast.LENGTH_SHORT).show()
}
private fun createRequest() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("786240463795-o92gljk39cmdd0pra162arebskntkdu5.apps.googleusercontent.com")
.requestEmail()
.build()
mGoogleSignIn = GoogleSignIn.getClient(this.activity, gso)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
As I say everythings works fine until I try to separate the navigation in those two files, in order to differentiate between the LoginNavigation, and the Naviation inside the App once the user is logged.
I don't know if the fact of the LoginScreen be a fragment have something related which the problem.
I hope you can help, and if it's like this take thanks in advance !
[EDIT]
Added the navigation.xml as I changed it after several tips:
Still through the same error.
mobile_navigation.xml
root_navigation.xml
Make sure you implement the navigation graph right way. use fragments.
root_navigation.xml
mobile_navigation.xml
add here your desired fragments you want to navigate from login.
(I suggest use login fragment in splash screen for your app launch. and other fragments implement through main activity)

Start IntentService from other App

I´m trying to start a IntentService from other App, now I have an Activity with an AsyncTask where I download a file. This works fine but I want download the file in a IntentService and don´t have to show the activity, just a Notification. Is this possible? I have read that IntentService starts when a Activity calls it through startService(Intent), but when I try nothing happens :(
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bajar);
intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
if("text/plain".equals(type)){
String todo = intent.getStringExtra(Intent.EXTRA_TEXT);
if(todo != null){
id = new Descarga(todo);
EditText textNombre = (EditText) findViewById(R.id.TextNombre);
textNombre.setText(id.nombre);
/*
This works
d = new Download();
d.execute();
/*
startService(intent); //This don´t work
}
}
}
}
This is the Activity xml file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="es.esy.palmaseca.descargayt.Bajar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/nombre"
android:id="#+id/txtNombre"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/TextNombre"
android:layout_below="#+id/txtNombre"
android:layout_centerHorizontal="true"
android:editable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/txtActual"
android:layout_marginTop="44dp"
android:layout_below="#+id/TextNombre"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/txtFinal"
android:layout_below="#+id/txtActual"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/barra"
android:layout_below="#+id/txtFinal"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp" />
My Class IntentService:
public class Descargar extends IntentService {
NotificationManager nm;
Notification notification;
static String ns = Context.NOTIFICATION_SERVICE;
int icono = R.drawable.icono;
public Descargar() {
super("Descargar");
Log.d("Serivicio", "Star");
}
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
if("text/plain".equals(type)){
String todo = intent.getStringExtra(Intent.EXTRA_TEXT);
if(todo != null){
Descarga d = new Descarga(todo);
bajar(d);
}
}
}
}
The function bajar is the same as Download AsynTask.
And finally the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.esy.palmaseca.descarga" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/icono"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
<service
android:enabled="true"
android:name=".Descargar"
android:exported="true" >
</service>
<activity
android:name=".Bajar"
android:label="#string/bajar" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
I have tried to start the IntentService but I can´t find out where is the mistake, and throws 0 errors
Sorry my english 🙏
An easy solution is to create a BroadcastReceiver, register it in your manifest for some intent action and then have it start the intentservice.
public class Descargar extends IntentService {
NotificationManager nm;
Notification notification;
static String ns = Context.NOTIFICATION_SERVICE;
int icono = R.drawable.icono;
public static class DescargarReceiver implements BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), Descargar.class.getName());
context.startService(intent.setComponent(comp));
}
}
public Descargar() {
super("Descargar");
Log.d("Serivicio", "Star");
}
#Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
if("text/plain".equals(type)){
String todo = intent.getStringExtra(Intent.EXTRA_TEXT);
if(todo != null){
Descarga d = new Descarga(todo);
bajar(d);
}
}
}
}
and in the manifest:
<receiver
android:name=".Descargar$DescargarReceiver"
android:exported="true>
<intent-filter>
<action
android:name="com.mycompany.action.START_DESCARGAR_SERVICE" />
</intent-filter>
</receiver>
<service
android:enabled="true"
android:name=".Descargar"
android:exported="true" >
</service>
and then you can just broadcast the intent from any app:
Intent intent = new Intent("com.mycompany.action.START_DESCARGAR_SERVICE");
intent.putExtra(.....)
sendBroadcast(intent);

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