I had some errors on "" class when I was handling the GCM .
the error appeared here :
onHandleIntent(Intent intent)
"Cannot override the final method from GCMBaseIntentService"
handleRegistration
"The method handleRegistration(Context, Intent) in the type
GCMBaseIntentService is not applicable for the arguments (Intent)"
handleMessage
"The method handleMessage(Intent) is undefined for the type
GCMIntenetService"
public final void onHandleIntent(Intent intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
} finally {
synchronized (LOCK) {
sWakeLock.release();
}
}
}
class
package com.example.elarabygroup;
import com.google.android.gcm.GCMBaseIntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
public class GCMIntenetService extends GCMBaseIntentService {
public static String TAG = "GCMIntentService";
private static PowerManager.WakeLock sWakeLock;
private static final Object LOCK = GCMIntenetService.class;
/*Handling Intents sent by GCM*/
static void runIntentInService(Context context, Intent intent) {
synchronized (LOCK) {
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, GCMIntenetService.class.getName());
context.startService(intent);
}
public GCMIntenetService(String senderId) {
super(senderId);
// TODO Auto-generated constructor stub
Log.d(TAG, "[GCMIntentService] start - sender Id : " + senderId);
}
#Override
protected void onError(Context arg0, String arg1) {
Log.d("onError", arg1);
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.d("onRecoverableError", errorId);
return false;
}
#Override
/*
* protected void onMessage(Context arg0, Intent arg1) { Log.d("onMessage",
* String.valueOf(arg1)); }
*/
protected void onMessage(Context arg0, Intent arg1) {
Log.d("GCM", "RECIEVED A MESSAGE");
// Get the data from intent and send to notificaion bar
generateNotification(arg0, arg1.getStringExtra("**notificaion**"));
}
private void generateNotification(Context arg0, String stringExtra) {
// TODO Auto-generated method stub
}
#Override
protected void onRegistered(intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
} finally {
synchronized (LOCK) {
sWakeLock.release();
}
}
}
#Override
protected void onUnregistered(Context arg0, String arg1) {
Log.d("onUnregistered", arg1);
}
}
You shouldn't override final methods of GCMBaseIntentService. You need ovveride only callback methods of this base class. Here is an example:
public class GCMIntentService extends GCMBaseIntentService {
private static final String GCM_SENDER_ID = "your_sender_id";
public GCMIntentService() {
super();
}
#Override
protected void onRegistered(Context context, String gcmDeviceToken) {
// remember and save somewhere "gcmDeviceToken"
}
#Override
protected void onUnregistered(Context context, String s) {
// Push unregistered processing
}
#Override
protected void onError(Context context, String errorId) {
// push error processing
}
#Override
protected void onMessage(Context context, Intent intent) {
// process Push message
}
public static void registerInGCMService(Context context) {
if (!checkIsGCMServiceAvailable(context)) {
return;
}
final String regId = GCMRegistrar.getRegistrationId(context);
if (regId.equals("")) {
try {
GCMRegistrar.register(context, GCM_SENDER_ID);
} catch (Exception ex) {
}
} else {
// Already registered
}
}
public static boolean checkIsGCMServiceAvailable(Context context) {
try {
GCMRegistrar.checkDevice(context);
GCMRegistrar.checkManifest(context);
return true;
} catch (Throwable th) {
return false;
}
}
}
UPDATE: please note - you should change value of GCM_SENDER_ID constant with your own, it should be numeric value, something like "1234567890123"
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
GCMRegistrar.setRegisteredOnServer(context, true);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
Log.i(TAG, "EXTRAS" + intent.getExtras());
String message = getString(R.string.gcm_message);
// notifies user about message
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
if (GCMRegistrar.isRegisteredOnServer(context)) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
GCMRegistrar.setRegisteredOnServer(context, false);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Log.i(TAG, "Ignoring unregister callback");
}
}
See GCM google tutorial http://developer.android.com/guide/google/gcm/gs.html
Related
I want to create a voice recognition app in android and run it in service so i can use it even without in the app. So i looked for reference and i found in GitHub a demo app.
This is the site https://github.com/ihrupin/SpeechRecognitionService
I download the app and also i read the documentation, Yes it running well to me it also running in service, but i really want is for example if i said (open Facebook) it will open the installed Facebook app.
I'm newbie in using the PocketSphinx.
This is the MainActivity
public class MainActivity extends AppCompatActivity {
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
private static final String LOG_TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button)findViewById(R.id.btn)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "onClick");
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
startService(new Intent(MainActivity.this, VoiceService.class));
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startService(new Intent(MainActivity.this, VoiceService.class));
} else {
finish();
}
}
}
}
This is my Service
public class VoiceService extends Service implements
RecognitionListener {
private static final String LOG_TAG = VoiceService.class.getSimpleName();
private static final String KWS_SEARCH = "wakeup";
private static final String KEYPHRASE = "lisa";
private SpeechRecognizer recognizer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
runRecognizerSetup();
}
return super.onStartCommand(intent, flags, startId);
}
private void runRecognizerSetup() {
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(VoiceService.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
Log.i(LOG_TAG, "Failed to init recognizer ");
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onDestroy() {
super.onDestroy();
if (recognizer != null) {
recognizer.cancel();
recognizer.shutdown();
}
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
if (text.contains(KEYPHRASE)) {
Toast.makeText(this, "onPartialResult text=" + text, Toast.LENGTH_SHORT).show();
switchSearch(KWS_SEARCH);
}
Log.i(LOG_TAG, "onPartialResult text=" +text);
}
#Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis != null) {
String text = hypothesis.getHypstr();
Log.i(LOG_TAG, "onResult text=" +text);
}
}
#Override
public void onBeginningOfSpeech() {
Log.i(LOG_TAG, "onBeginningOfSpeech");
}
#Override
public void onEndOfSpeech() {
if (!recognizer.getSearchName().contains(KWS_SEARCH))
switchSearch(KWS_SEARCH);
Log.i(LOG_TAG, "onEndOfSpeech");
}
private void switchSearch(String searchName) {
Log.i(LOG_TAG, "switchSearch searchName = " + searchName);
recognizer.stop();
recognizer.startListening(searchName, 10000);
}
private void setupRecognizer(File assetsDir) throws IOException {
recognizer = SpeechRecognizerSetup.defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
.setRawLogDir(assetsDir)
.setKeywordThreshold(1e-45f)
.setBoolean("-allphone_ci", true)
.getRecognizer();
recognizer.addListener(this);
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
}
#Override
public void onError(Exception error) {
Log.i(LOG_TAG, "onError " + error.getMessage());
}
#Override
public void onTimeout() {
switchSearch(KWS_SEARCH);
Log.i(LOG_TAG, "onTimeout");
}
}
This is BootReceiver
public class BootReceiver extends BroadcastReceiver {
private static final String LOG_TAG = BootReceiver.class.getSimpleName();
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LOG_TAG, "onReceive");
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
Log.i(LOG_TAG, "onReceive onBoot");
context.startService(new Intent(context, VoiceService.class));
}
}
}
I've researched about this topic and i found out that i must modify the grammar and the dictionary but i don't know how to do that. Any ideas?
If you want to modify the existing grammer and want to add your own words you have to modify it a little bit.
write this line in your recognizer setup method.
recognizer.addKeyphraseSearch("facebookPhrase", "Open Facebook");
To edit this example you can read about on official website here
https://cmusphinx.github.io/wiki/tutoriallm/
Whenever i am running my application I am getting "Service connected" message but after that the BroadcastReceiver are no responding.
what is the problem ?
Can anyone tell me what should i do?
public class BumpTest extends Activity
{
private IBumpAPI api;
private final ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.i("BumpTest", "onServiceConnected");
api = IBumpAPI.Stub.asInterface(binder);
try {
api.configure("8836a26d3545410c9905d90528b2153a",
"ram");//8836a26d3545410c9905d90528b2153a,3826a0e77b284c05960d4513e87c4a88
} catch (RemoteException e) {
Log.w("BumpTest", e);
}
Log.d("Bump Test", "Service connected");
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d("Bump Test", "Service disconnected");
}
};
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
try {
Log.i("Bump Test", "In Receive " );
if (action.equals(BumpAPIIntents.DATA_RECEIVED)) {
Log.i("Bump Test", "Received data from: " + api.userIDForChannelID(intent.getLongExtra("channelID", 0)));
Log.i("Bump Test", "Data: " + new String(intent.getByteArrayExtra("data")));
} else if (action.equals(BumpAPIIntents.MATCHED)) {
long channelID = intent.getLongExtra("proposedChannelID", 0);
Log.i("Bump Test", "Matched with: " + api.userIDForChannelID(channelID));
api.confirm(channelID, true);
Log.i("Bump Test", "Confirm sent");
} else if (action.equals(BumpAPIIntents.CHANNEL_CONFIRMED)) {
long channelID = intent.getLongExtra("channelID", 0);
Log.i("Bump Test", "Channel confirmed with " + api.userIDForChannelID(channelID));
api.send(channelID, "Hello, world!".getBytes());
} else if (action.equals(BumpAPIIntents.NOT_MATCHED)) {
Log.i("Bump Test", "Not matched.");
} else if (action.equals(BumpAPIIntents.CONNECTED)) {
Log.i("Bump Test", "Connected to Bump...");
api.enableBumping();
}else{
System.out.println("inn broadcast rcvr ::: "+api.toString());
}
} catch (RemoteException e) {}
}
};
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent(IBumpAPI.class.getName()),
connection, Context.BIND_AUTO_CREATE);
Log.i("BumpTest", "boot");
IntentFilter filter = new IntentFilter();
filter.addAction(BumpAPIIntents.CHANNEL_CONFIRMED);
filter.addAction(BumpAPIIntents.DATA_RECEIVED);
filter.addAction(BumpAPIIntents.NOT_MATCHED);
filter.addAction(BumpAPIIntents.MATCHED);
filter.addAction(BumpAPIIntents.CONNECTED);
registerReceiver(receiver, filter);
//txtReceived=(TextView)findViewById(R.id.txtReceived);
//bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
new BindService().execute();
}
#SuppressLint("NewApi")
class BindService extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bindService(new Intent(IBumpAPI.class.getName()), connection, Context.BIND_AUTO_CREATE);
return null;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println("done");
}
}
public void onStart() {
Log.i("BumpTest", "onStart");
super.onStart();
}
public void onRestart() {
Log.i("BumpTest", "onRestart");
super.onRestart();
}
public void onResume() {
Log.i("BumpTest", "onResume");
super.onResume();
}
public void onPause() {
Log.i("BumpTest", "onPause");
super.onPause();
}
public void onStop() {
Log.i("BumpTest", "onStop");
super.onStop();
}
public void onDestroy() {
Log.i("BumpTest", "onDestroy");
super.onDestroy();
try {
unbindService(connection);
unregisterReceiver(receiver);
} catch (Exception e) {
// TODO: handle exception
}
}
}
I had this error :
Cannot make a static reference to the non-static method
getApplicationContext() from the type ContextWrapper
please find the method that have the error registerInGCMService(Context context)
class:
package com.example.elarabygroup;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.provider.Settings.Secure;
import android.util.Log;
public class GCMIntenetService extends GCMBaseIntentService {
private static final String GCM_SENDER_ID = "1111111111";
public GCMIntenetService() {
super();
}
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
GCMRegistrar.setRegisteredOnServer(context, true);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
if (GCMRegistrar.isRegisteredOnServer(context)) {
String regId = "";
Log.i(TAG, "unregistering device (regId = " + regId + ")");
GCMRegistrar.setRegisteredOnServer(context, false);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Log.i(TAG, "Ignoring unregister callback");
}
}
#Override
protected void onError(Context context, String errorId) {
// push error processing
}
#Override
protected void onMessage(Context arg0, Intent arg1) {
Log.i(TAG, "Received message");
Log.i(TAG, "EXTRAS" + arg1.getExtras());
// String message = getString(R.string.gcm_message);
generateNotification(arg0,
arg1.getStringExtra("Please download our new updates"));
// notifies user about message
}
private void generateNotification(Context arg0, String stringExtra) {
// TODO Auto-generated method stub
}
public static void registerInGCMService(Context context) {
GCM_SENDER_ID = Secure.getString(context.getApplicationContext().getContentResolver(),
Secure.ANDROID_ID);
if (!checkIsGCMServiceAvailable(context)) {
return;
}
final String regId = GCMRegistrar.getRegistrationId(context);
if (regId.equals("")) {
try {
GCMRegistrar.register(context, GCM_SENDER_ID);
} catch (Exception ex) {
}
} else {
// Already registered
}
}
public static boolean checkIsGCMServiceAvailable(Context context) {
try {
GCMRegistrar.checkDevice(context);
GCMRegistrar.checkManifest(context);
return true;
} catch (Throwable th) {
return false;
}
}
}
What you probably meant is :
context.getApplicationContext()
instead of
getApplicationContext()
Or you can try like this -
GCM_SENDER_ID = Secure.getString(context.getContentResolver(),
Secure.ANDROID_ID);
Sometime this error comes, when we are using "getConTentResolver()" in static method
like:
public static void Mthd()
{
Cursor cursor =getContentResolver().query(uri, null, null, null, null);
//ur next code
}
So, in this case it will give an error, Therefore we have to make the function non-static.
In my application I want to call service from Receiver.
This is my NotificationReceiver.java
public class NotificationReceiver extends BroadcastReceiver {
NotificationReceiver _this = this;
private static Context _context;
public static final String ACTION_REFRESH_SCHEDULE_ALARM = "com.example.receiver.ACTION_REFRESH_SCHEDULE_ALARM";
String SERVER_URL = "http://192.168.1.7:8080";
#Override
public void onReceive(final Context context, Intent intent) {
_context = context;
initClient();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(_context);
if (settings.getString("userId",null) != null){
gotNotification(new ClientListener(){
#Override
public void onSuccess(String response) {
try {
JSONObject object = new JSONObject(response);
System.out.println("Service object = "+ object);
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void onFail(int error) {
}
#Override
public void onCancel() {
}
},settings.getString("userId",null));
}
}
private void initClient(){
NotifierRestClient.init(SERVER_URL + "/api");
}
private void gotNotification (final ClientListener clientListener, final String uId) {
new Thread() {
#Override
public void run() {
try {
final String responseText = NotifierRestClient.getUserNotifications(uId,null);
if (clientListener != null) {
clientListener.onSuccess(responseText);
}
} catch (final Exception e) {
e.printStackTrace();
if (clientListener != null) {
clientListener.onFail(505);
}
}
}
}.start();
}
}
And this is my NotifiactionService.java
public class NotificationService extends Service {
private AlarmManager alarmManagerPositioning;
private PendingIntent pendingIntent;
#Override
public void onCreate() {
super.onCreate();
alarmManagerPositioning = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final Intent intentToNotificate = new Intent(NotificationReceiver.ACTION_REFRESH_SCHEDULE_ALARM);
pendingIntent = PendingIntent.getBroadcast(this, 0, intentToNotificate, 0);
}
#Override
public void onStart(Intent intent, int startId) {
try {
long notificationInterval = 5002;
alarmManagerPositioning.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), notificationInterval, pendingIntent);
} catch (NumberFormatException e) {
Toast.makeText(this, "error running services: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "error running services: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
this.alarmManagerPositioning.cancel(pendingIntent);
}
}
My question is how to call NotificationService in NotificationReceiver and change interval? Any help will be useful Thanks
Start Service in your receiver using
Intent in = new Intent(context,NotificationService.class);
in.putExtra("interval",5001);
context.startService(in);
In your service code,
long notificationInterval = intent.getLongExtra("interval", defaultValue)
to get Data from your receiver, Please use onStartCommand(Intent intent, int flags, int startId), onStart has been deprecated.
I am trying to make an Activity run a certain service.
I followed the tutorial here but adapted to my code, and I can't make it work, because when I am invoking the service after starting and binding it to the activity, my Interface (IMyRemoteCallsLoggingService) object does not seem to have the connection properly created.
I have been trying to make this work for several days but I can't seem to get rid of a NullPointException.
Not sure if I made myself clear, in which case here's the code:
public class MtprojectActivity extends Activity {
[...]
private boolean started = false;
private RemoteSmsLoggingServiceConnection SmsLoggingConn = null;
private RemoteCallsLoggingServiceConnection CallsLoggingConn = null;
private IMyRemoteCallsLoggingService callsLoggingService;
private IMyRemoteSmsLoggingService smsLoggingService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
retrievePreferences();
Button prefBtn = (Button) findViewById(R.id.prefsBtn);
prefBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Explicit intent to call the preferences
Intent preferencesActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(preferencesActivity);
}
});
}
private void retrievePreferences() {
// Get the xml/preferences.xml preferences
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
callsCheckbox = prefs.getBoolean("callsLogChk", false);
smsCheckbox = prefs.getBoolean("smsLogChk", false);
locationCheckbox = prefs.getBoolean("locationLogChk", false);
if (callsCheckbox) {
startCallsService();
bindCallsService();
try {
invokeCallsService();
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
}
private void startCallsService() {
if (started) {
Toast.makeText(MtprojectActivity.this, "Service already started",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent();
i.setClassName("app.mtproject", "app.mtproject.CallsLoggingService");
startService(i);
started = true;
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "startService()");
}
}
private void bindCallsService() {
if (CallsLoggingConn == null) {
CallsLoggingConn = new RemoteCallsLoggingServiceConnection();
Intent i = new Intent();
i.setClassName("app.mtproject", "app.mtproject.CallsLoggingService");
bindService(i, CallsLoggingConn, Context.BIND_AUTO_CREATE);
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "bindService()");
} else {
Toast.makeText(MtprojectActivity.this,
"Cannot bind - service already bound", Toast.LENGTH_SHORT)
.show();
}
}
private void invokeCallsService() throws RemoteException {
if (CallsLoggingConn == null) {
Toast.makeText(MtprojectActivity.this,
"Cannot invoke - service not bound", Toast.LENGTH_SHORT)
.show();
} else {
callsLoggingService.dumpCallsLog();
TextView t = (TextView) findViewById(R.id.notApplicable);
t.setText("It worked!");
Log.d(getClass().getSimpleName(), "invokeService()");
}
}
class RemoteCallsLoggingServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService) {
callsLoggingService = IMyRemoteCallsLoggingService.Stub
.asInterface((IBinder) boundService);
Log.d(getClass().getSimpleName(), "onServiceConnected()");
}
public void onServiceDisconnected(ComponentName className) {
callsLoggingService = null;
updateCallsServiceStatus();
Log.d(getClass().getSimpleName(), "onServiceDisconnected");
}
};
I get a NullPointerException right on callsLoggingService.dumpCallsLog() in the invokeCallsService() method, and I'm not sure what's the problem!
Here's the code of the service:
public class CallsLoggingService extends Service {
String date, duration, type;
private Handler serviceHandler;
private Task myTask = new Task();
#Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return myRemoteCallsServiceStub;
}
private IMyRemoteCallsLoggingService.Stub myRemoteCallsServiceStub = new IMyRemoteCallsLoggingService.Stub() {
public void dumpCallsLog() throws RemoteException {
CallsLoggingService.this.dumpCallsLog();
}
};
#Override
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(), "onCreate()");
}
#Override
public void onDestroy() {
super.onDestroy();
serviceHandler.removeCallbacks(myTask);
serviceHandler = null;
Log.d(getClass().getSimpleName(), "onDestroy()");
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
serviceHandler = new Handler();
serviceHandler.postDelayed(myTask, 10L);
Log.d(getClass().getSimpleName(), "onStart()");
}
class Task implements Runnable {
public void run() {
try {
myRemoteCallsServiceStub.dumpCallsLog();
} catch (RemoteException e) {
e.printStackTrace();
}
serviceHandler.postDelayed(this, 86400000L);
Log.i(getClass().getSimpleName(), "Calling the dumpCallsLog");
}
}
private synchronized void dumpCallsLog() {
ContentResolver cr = getContentResolver();
String columns[] = new String[] { CallLog.Calls.DATE,
CallLog.Calls.DURATION, CallLog.Calls.TYPE };
Uri mContacts = CallLog.Calls.CONTENT_URI;
Cursor c = cr.query(mContacts, columns, // Which columns to return
null, // WHERE clause; which rows to return(all rows)
null, // WHERE clause selection arguments (none)
CallLog.Calls.DEFAULT_SORT_ORDER // Order-by clause
// (ascending
// by name)
);
if (c.moveToFirst()) {
do {
// Get the field values
date = c.getString(c.getColumnIndex(CallLog.Calls.DATE));
duration = c
.getString(c.getColumnIndex(CallLog.Calls.DURATION));
type = c.getString(c.getColumnIndex(CallLog.Calls.TYPE));
} while (c.moveToNext());
}
}
}
Thanks a lot everybody for the help!
bindService() is asynchronous. You cannot use callsLoggingService until onServiceConnected() is called.