Unable to use Aidl in Android - android

First time to use AIDL. I want to test it.
Below is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "CalculateClient";
private Button btnCalculate;
private EditText etNum1;
private EditText etNum2;
private TextView tvResult;
private CalculateInterface mService;
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
logE("disconnect service");
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
logE("connect service");
mService = CalculateInterface.Stub.asInterface(service);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle args = new Bundle();
Intent intent = new Intent("com.example.calculate.CalculateService");
intent.putExtras(args);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
etNum1 = (EditText) findViewById(R.id.editText);
etNum2 = (EditText) findViewById(R.id.editText2);
tvResult = (TextView) findViewById(R.id.textView);
btnCalculate = (Button) findViewById(R.id.button);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
logE("Start..");
try {
double num1 = Double.parseDouble(etNum1.getText().toString());
double num2 = Double.parseDouble(etNum2.getText().toString());
logE(Double.toString(num1));
logE(Double.toString(num2));
String answer = "Result:" + mService.doCalculate(num1, num2); //this line BUG
tvResult.setTextColor(Color.BLUE);
tvResult.setText(answer);
} catch (RemoteException ignored) {
}
}
});
}
private void logE(String str) {
Log.e(TAG, "--------" + str + "--------");
}
}
MyTestService:
package com.radio.miao.aidltest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyTestService extends Service {
private static final String TAG = "CalculateService";
private final CalculateInterface.Stub mBinder = new CalculateInterface.Stub() {
#Override
public double doCalculate(double a, double b) throws RemoteException {
// TODO Auto-generated method stub
Log.e("Calculate", "remote");
return b + a;
}
};
private static void logE(String str) {
Log.e(TAG, "--------" + str + "--------");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
logE("onBind()");
return mBinder;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
logE("onCreate()");
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
logE("onStart()");
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
logE("onUnbind()");
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
logE("onDestroy()");
super.onDestroy();
}
}
<service android:name="com.radio.miao.aidltest.MyTestService">
<intent-filter>
<action android:name="com.radio.miao.aidltest.MyTestService" />
</intent-filter>
package com.radio.miao.aidltest;
// Declare any non-default types here with import statements
interface CalculateInterface {
double doCalculate(double a, double b);
}
The error is
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.radio.miao.aidltest.MainActivity$2.onClick(MainActivity.java:79)

The following line creates an intent for an invalid service:
Intent intent = new Intent("com.example.calculate.CalculateService");
The correct should be:
Intent intent = new Intent(this,MyTestService.class);

Related

Using a Speech Recognizer and TTS manager class

I'm trying to have this central manager class that handles the speech recognition and output voice data. So far, I have failed. This is what the class looks like but my app crashes when I try implementing it in other classes. Can someone please help me out?
Cheers!
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
public class speechEngineR extends Activity {
SpeechRecognizer ears;
TextToSpeech tts;
Intent i;
Context mCon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ears = SpeechRecognizer.createSpeechRecognizer(mCon);
i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, mCon.getPackageName());
tts = new TextToSpeech(mCon, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
ears.setRecognitionListener(new RecognitionListener() {
#Override
public void onRmsChanged(float rmsdB) {
// TODO Auto-generated method stub
}
#Override
public void onResults(Bundle results) {
// TODO Auto-generated method stub
}
#Override
public void onReadyForSpeech(Bundle params) {
// TODO Auto-generated method stub
}
#Override
public void onPartialResults(Bundle partialResults) {
// TODO Auto-generated method stub
}
#Override
public void onEvent(int eventType, Bundle params) {
// TODO Auto-generated method stub
}
#Override
public void onError(int error) {
// TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
#Override
public void onBufferReceived(byte[] buffer) {
// TODO Auto-generated method stub
}
#Override
public void onBeginningOfSpeech() {
// TODO Auto-generated method stub
}
});
}
public speechEngineR(Context c){
mCon = c;
}
public void outSpeech(String out){
tts.speak(out, TextToSpeech.QUEUE_FLUSH, null);
}
}
And yes, I have I added the following permission in the Manifest.xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Your question and code does not help.
In your code it seems you are trying to use Speech to Text(Audio recorder), and you are calling it using TTS (Text to Speech) which does exactly the opposite of what you are trying to accomplish i.e. speech to text.
Can you make it a bit more clear what you are trying to do??

I do not how stop my service

I have a problema with my service. I have 3 button, the first one call service in order to get numbers at randon and show them in a textbox every 10 second, the second button call service in order to get numbers at rand every I press that button and the last button must stop the service but I cannot when I press it and when I close the app and open again the service run automatically I do not understand!!
There is my service class
public class MyService extends Service{
public static final String NEW_DATA = "com.example.t8ej1.MyService.NEW_DATA";
private static final String stringUrl =
"http://www.imaginaformacion.com/recursos/rand.php";
private static final int updateInterval = 1000;
private Timer updateTimer;
private TimerTask doRefresh;
private String data;
public int service_id;
private IBinder binder = new MyBinder ();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}}
private void updateData() {
// Nos conectamos al servicio web y obtenemos los datos
try{
URL url = new URL(stringUrl);
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
data= reader.readLine();
in.close();
announceData();
}
}
catch( MalformedURLException e){
Log.e("Service", e.getMessage());
}catch(IOException e){
Log.e("Service", e.getMessage());
}
}
private void announceData() {
// Lanzamos el broadcast con el intent y los datos
Intent intent = new Intent(NEW_DATA);
intent.putExtra("data", data);
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
// Creamos el Timer y el TimerTask
service_id=startId;
updateTimer = new Timer();
doRefresh = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
updateData();
}
};
// Lo programamos para que se lance cada updateInterval milisegundos
updateTimer.scheduleAtFixedRate(doRefresh, 0, updateInterval);
// Queremos que el servicio esté siempre encendido
return Service.START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.e("mm", "4444");
super.onDestroy();
}
public String getData() {
return data;
}}
There is my activity class
public class Service extends Activity {
private MyServiceReceiver myReceiver;
private MyService myService;
TextView txtManual;
TextView txtAuto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
bindService(new Intent(Service.this, MyService.class),
myConnection,
Context.BIND_AUTO_CREATE);
IntentFilter filter;
filter = new IntentFilter(MyService.NEW_DATA);
myReceiver = new MyServiceReceiver();
registerReceiver(myReceiver, filter);
txtAuto = (TextView) findViewById(R.id.txtAuto);
txtManual = (TextView) findViewById(R.id.txtManual);
Button cmdStart = (Button) findViewById(R.id.cmdStart);
Button cmdRefresh = (Button) findViewById(R.id.cmdRefresh);
Button cmdStop = (Button) findViewById(R.id.cmdStop);
cmdStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
unbindService(myConnection);
stopService(new Intent(Service.this, MyService.class));
}
});
cmdRefresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
txtManual.setText(myService.getData());
}
});
cmdStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(Service.this, MyService.class));
}
});
}
private ServiceConnection myConnection = new ServiceConnection () {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
myService = ((MyService.MyBinder) service).getService();
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
myService=null;
}
};
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
txtAuto.setText(intent.getStringExtra("data"));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
//unregisterReceiver(myReceiver);
super.onPause();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}}
unbind service using unbindService() in your onStop() of MyService class (Your Service),
and then call stopService in Service class (your Activity)

Updating Activity with Latitude/Longitude values returned from a Service

I'm trying to write a simple app that updates the MainActivity with the Lat/Lng values returned by the service. But it always returns the null value. I have added permissions and added TheService.java as service in AndroidManifest.xml file...Kindly tell me where I have gone wrong.
MainActivity.java
public class MainActivity extends Activity {
TextView tv1, tv2;
IntentFilter filter;
receive rec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView1);
tv2 = (TextView)findViewById(R.id.textView2);
filter = new IntentFilter("Updated");
rec = new receive();
Intent gps_int = new Intent(this,TheService.class);
startService(gps_int);
}
#Override
public void onPause()
{
super.onPause();
unregisterReceiver(rec);
}
#Override
public void onResume()
{
super.onResume();
rec = new receive();
registerReceiver(rec, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
tv1.setText(intent.getExtras().getString("lat"));
tv2.setText(intent.getExtras().getString("lon"));
Toast.makeText(getApplicationContext(), "Toast Executed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "BR Latitude "+intent.getExtras().getString("lat"),Toast.LENGTH_SHORT).show();
}
}}
TheService.java
public class TheService extends Service implements LocationListener {
LocationManager lm;
Location loc;
double lat = 0;
double lon = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
lm=(LocationManager)getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(loc);
return START_STICKY;
}
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
updateui(location);
}
private void updateui(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent gps_intent = new Intent("Updated");
gps_intent.putExtra("lat", lat);
gps_intent.putExtra("lon", lon);
sendBroadcast(gps_intent);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}}
You should use the Google Play Services for the location, that's easier to handle.
What for do you even need a Service? Having a location listener in your Activity is totally fine.
If you want to stay with the Service, than bind the Activity to it, instead of using a Broadcast.

how to send data in service based android app

I want to send data from one application A to other application B using AIDL file. My appl A is like below,
public class LibValue {
public static native int intFromJNI(int n);
static {
System.loadLibrary("hello");
System.out.println("LibValue : Loading library");
}
I am getting value from JNI file to above class. The data from above class to send another app B using AIDL service is like below.
IEventService.aidl
interface IEventService {
int intFromJNI(in int n);
}
for this I written IEventImpl.java class
public class IEventImpl extends IEventService.Stub{
int result;
#Override
public int intFromJNI(int n) throws RemoteException {
// TODO Auto-generated method stub
System.out.println("IEventImpl"+LibValue.intFromJNI(n));
return LibValue.intFromJNI(n);
}
}
To access above class I writtn service class like below
public class EventService extends Service {
public IEventImpl iservice;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Log.i("EventService", "indside onBind");
return this.iservice;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.iservice = new IEventImpl();
Log.i("EventService", "indside OncREATE");
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
this.iservice = null;
super.onDestroy();
}
All above classes are server side. The below class is Client(app) class to access data.
public class EventClient extends Activity implements OnClickListener, ServiceConnection{
public IEventService myService;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_client);
button = (Button)findViewById(R.id.button1);
this.button.setOnClickListener(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (!super.bindService(new Intent(IEventService.class.getName()),
this, BIND_AUTO_CREATE)) {
Log.w("EventClient", "Failed to bind to service");
System.out.println("inside on resume");
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
super.unbindService(this);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
this.myService = IEventService.Stub.asInterface(service);
Log.i("EventClient", "ServiceConnected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.d("EventClient", "onServiceDisconnected()'ed to " + name);
// our IFibonacciService service is no longer connected
this.myService = null;
}
I am trying to access data from service class but not able to find out the way. can anybody tell how to access data from service to client application ?
Thanks

Running Android TTS in a Service

I'm trying to get Android's TTS to run inside a service, but I have no idea why it isn't working, it compiles, doesn't crash, but it just doesn't work.
The Toast notification do work though.
package alarm.test;
import android.app.Service;
import com.google.tts.TextToSpeechBeta;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyAlarmService extends Service {
private TextToSpeechBeta myTts;
private TextToSpeechBeta.OnInitListener ttsInitListener = new TextToSpeechBeta.OnInitListener() {
public void onInit( int arg0, int arg1 ) {
myTts.speak("", 0, null);
}
};
#Override
public void onCreate() {
// TODO Auto-generated method stub
myTts = new TextToSpeechBeta( this,
ttsInitListener );
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
myTts.speak("something is working", TextToSpeechBeta.QUEUE_FLUSH, null);
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
You can do like below: It's working for me.
You have to create an activity to start this service, like this: this.startService(intent)
public class TTSService extends Service implements TextToSpeech.OnInitListener{
private String str;
private TextToSpeech mTts;
private static final String TAG="TTSService";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
mTts = new TextToSpeech(this,
this // OnInitListener
);
mTts.setSpeechRate(0.5f);
Log.v(TAG, "oncreate_service");
str ="turn left please ";
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
sayHello(str);
Log.v(TAG, "onstart_service");
super.onStart(intent, startId);
}
#Override
public void onInit(int status) {
Log.v(TAG, "oninit");
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.v(TAG, "Language is not available.");
} else {
sayHello(str);
}
} else {
Log.v(TAG, "Could not initialize TextToSpeech.");
}
}
private void sayHello(String str) {
mTts.speak(str,
TextToSpeech.QUEUE_FLUSH,
null);
}
}
https://developer.android.com/reference/android/speech/tts/TextToSpeechService.html
since API Level 14, android has added a default TextToSpeech Service class that does what you want.

Categories

Resources