I am getting the following exception when I run the texter application in android.
STACK_TRACE :
java.lang.NullPointerException at
com.texter.messenger.SmsReceiverService$ServiceHandler.handleMessage(SmsReceiverService.java:116)
at android.os.Handler.dispatchMessage(Handler.java:99) at
android.os.Looper.loop(Looper.java:123) at
android.os.HandlerThread.run(HandlerThread.java:60) , PHONE_MODEL :
GT-I9000 , ANDROID_VERSION : 2.2 , APP_VERSION_CODE : 10
30.Nov.2011 00:33:50 AM , CUSTOM_DATA : , STACK_TRACE : java.lang.IllegalArgumentException: Receiver not registered:
android.widget.ViewFlipper$1#40597cc0 at
android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:634) at
android.app.ContextImpl.unregisterReceiver(ContextImpl.java:881) at
android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:331)
at
android.widget.ViewFlipper.onDetachedFromWindow(ViewFlipper.java:104)
at android.view.View.dispatchDetachedFromWindow(View.java:6235) at
android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1250)
at
android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1248)
at
android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1248)
at
android.view.ViewGroup.dispatchDetachedFromWindow(ViewGroup.java:1248)
at
android.view.ViewRoot.dispatchDetachedFromWindow(ViewRoot.java:1838)
at android.view.ViewRoot.doDie(ViewRoot.java:2916) at
android.view.ViewRoot.die(ViewRoot.java:2886) at
android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:254)
at
android.view.Window$LocalWindowManager.removeViewImmediate(Window.java:445)
at
android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3182)
at
android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3287)
at android.app.ActivityThread.access$1600(ActivityThread.java:132)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1042)
at android.os.Handler.dispatchMessage(Handler.java:99) at
android.os.Looper.loop(Looper.java:150) at
android.app.ActivityThread.main(ActivityThread.java:4293) at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:507) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at
dalvik.system.NativeStart.main(Native Method).
I am new to these errors. How to solve these errors.
package com.texter.messenger;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.Process;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.SmsMessage.MessageClass;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.texter.common.TexterConstants;
import com.texter.common.TexterNotification;
import com.texter.common.Utils;
import com.texter.data.TexterDB;
import com.texter.data.TexterDB.Schedule;
import com.texter.preferences.TexterPreferenceManager;
import com.texterpro.app.ConversationList;
import com.texterpro.app.R;
import com.texterpro.app.SmsPopupView;
public class SmsReceiverService extends Service {
private static final String LOG_TAG = TexterConstants.COMMON_TAG;
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String ACTION_MMS_RECEIVED = "android.provider.Telephony.WAP_PUSH_RECEIVED";
private static final String ACTION_MESSAGE_RECEIVED = "net.everythingandroid.smspopup.MESSAGE_RECEIVED";
private static final String MMS_DATA_TYPE = "application/vnd.wap.mms-message";
// https://android.googlesource.com/platform/packages/apps/Mms/+/master/src/com/android/mms/transaction/SmsReceiverService.java
public static final String MESSAGE_SENT_ACTION = "com.android.mms.transaction.MESSAGE_SENT";
/*
* This is the number of retries and pause between retries that we will keep
* checking the system message database for the latest incoming message
*/
private static final int MESSAGE_RETRY = 8;
private static final int MESSAGE_RETRY_PAUSE = 1000;
private Context context;
private ServiceHandler mServiceHandler;
private Looper mServiceLooper;
private int mResultCode;
private static final Object mStartingServiceSync = new Object();
private static PowerManager.WakeLock mStartingService;
private static final int TOAST_HANDLER_MESSAGE_SENT = 0;
private static final int TOAST_HANDLER_MESSAGE_SEND_LATER = 1;
private static final int TOAST_HANDLER_MESSAGE_FAILED = 2;
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("Log.LOGTAG",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
context = getApplicationContext();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
Log.v(LOG_TAG, "Oncreate");
}
#Override
public void onStart(Intent intent, int startId) {
Log.v(LOG_TAG, "OnStart");
mResultCode = intent != null ? intent.getIntExtra("result", 0) : 0;
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
#Override
public void onDestroy() {
mServiceLooper.quit();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
Log.v(LOG_TAG, "handlemessage:");
Log.v(LOG_TAG, msg.toString());
int serviceId = msg.arg1;
Intent intent = (Intent) msg.obj;
String action = intent.getAction();
String dataType = intent.getType();
if (ACTION_SMS_RECEIVED.equals(action)) {
handleSmsReceived(intent);
} else if (ACTION_MMS_RECEIVED.equals(action)
&& MMS_DATA_TYPE.equals(dataType)) {
handleMmsReceived(intent);
} else if (MESSAGE_SENT_ACTION.equals(action)) {
handleSmsSent(intent);
} else if (ACTION_MESSAGE_RECEIVED.equals(action)) {
handleMessageReceived(intent);
}
// NOTE: We MUST not call stopSelf() directly, since we need to
// make sure the wake lock acquired by AlertReceiver is released.
finishStartingService(SmsReceiverService.this, serviceId);
}
}
/**
* Handle receiving a SMS message
*/
private void handleSmsReceived(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] messages = Utils.getMessagesFromIntent(intent);
if (messages != null) {
notifyMessageReceived(new SmsMmsMessage(context, messages,
System.currentTimeMillis()));
}
}
}
private void notifyMessageReceived(SmsMmsMessage message) {
// Class 0 SMS, let the system handle this
if (message.getMessageType() == SmsMmsMessage.MESSAGE_TYPE_SMS
&& message.getMessageClass() == MessageClass.CLASS_0) {
return;
}
TelephonyManager mTM = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
boolean callStateIdle = mTM.getCallState() == TelephonyManager.CALL_STATE_IDLE;
/*
* If popup is enabled for this user -AND- the user is not in a call
* -AND- -AND- phone is not docked -AND- (screen is locked -OR- (setting
* is OFF to only show on keyguard -AND- user is not in messaging app:
* then show the popup activity, otherwise check if notifications are on
* and just use the standard notification))
*/
boolean isApp = TexterPreferenceManager.getInstance(this)
.isAppEnabled();
boolean showPop = TexterPreferenceManager.getInstance(this)
.isPopupEnabled();
boolean showNotify = TexterPreferenceManager.getInstance(this)
.isNotifyEnabled();
// Log.v(LOG_TAG," App = "+ isApp );
// Log.v(LOG_TAG," pop = "+showPop );
// Log.v(LOG_TAG," notify = "+showNotify );
// if conversationList is visible then do not show pop
if (!ConversationList.isVisible()) {
if (isApp && callStateIdle && showPop) {
// Log.v(LOG_TAG," showing popup = " );
if (!SmsPopupView.isPopupVisible())
context.startActivity(message.getPopupIntent());
}
}
if (isApp && showNotify) {
TexterNotification.ShowMessageNotification(this, message);
}
}
/**
* Handle receiving a MMS message
*/
private void handleMmsReceived(Intent intent) {
}
/**
* Handle receiving an arbitrary message (potentially coming from a 3rd
* party app)
*/
private void handleMessageReceived(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
}
}
/*
* Handler to deal with showing Toast messages for message sent status
*/
public Handler mToastHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg != null) {
switch (msg.what) {
case TOAST_HANDLER_MESSAGE_SENT:
// TexterNotification.showToast(SmsReceiverService.this,R.string.quickreply_sent_toast);
break;
case TOAST_HANDLER_MESSAGE_SEND_LATER:
TexterNotification.showToast(SmsReceiverService.this,
R.string.quickreply_failed_send_later);
break;
case TOAST_HANDLER_MESSAGE_FAILED:
TexterNotification.showToast(SmsReceiverService.this,
R.string.quickreply_failed);
break;
}
}
}
};
/*
* Handle the result of a sms being sent
*/
private void handleSmsSent(Intent intent) {
Log.v(LOG_TAG, "HandleSMSSent called");
PackageManager pm = getPackageManager();
Intent sysIntent = null;
Intent tempIntent;
List<ResolveInfo> receiverList;
boolean forwardToSystemApp = true;
// Search for system messaging app that will receive our
// "message sent complete" type intent
tempIntent = intent.setClassName(
SmsMessageSender.MESSAGING_PACKAGE_NAME,
SmsMessageSender.MESSAGING_RECEIVER_CLASS_NAME);
tempIntent.setAction(SmsReceiverService.MESSAGE_SENT_ACTION);
receiverList = pm.queryBroadcastReceivers(tempIntent, 0);
if (receiverList.size() > 0) {
sysIntent = tempIntent;
}
Bundle b = intent.getExtras();
long rowid = 0;
rowid = b == null ? 0 : b.getLong("ROWID");
/*
* No system messaging app was found to forward this intent to,
* therefore we will need to do the final piece of this ourselves which
* is basically moving the message to the correct folder depending on
* the result.
*/
// TexterNotification.showToast(SmsReceiverService.this,
// "before moving folder");
if (sysIntent == null) {
forwardToSystemApp = false;
Uri uri = intent.getData();
Log.v(LOG_TAG, "id = " + rowid);
if (mResultCode == Activity.RESULT_OK) {
SmsMessageSender.moveMessageToFolder(this, uri,
SmsMessageSender.MESSAGE_TYPE_SENT);
} else if ((mResultCode == SmsManager.RESULT_ERROR_RADIO_OFF)
|| (mResultCode == SmsManager.RESULT_ERROR_NO_SERVICE)) {
SmsMessageSender.moveMessageToFolder(this, uri,
SmsMessageSender.MESSAGE_TYPE_QUEUED);
} else {
SmsMessageSender.moveMessageToFolder(this, uri,
SmsMessageSender.MESSAGE_TYPE_FAILED);
}
}
// Check the result and notify the user using a toast
if (mResultCode == Activity.RESULT_OK) {
mToastHandler.sendEmptyMessage(TOAST_HANDLER_MESSAGE_SENT);
TexterDB.getInstance().updateStatus(rowid,
Schedule.STATUS_SCHEDULED_SENT, 0);
} else if ((mResultCode == SmsManager.RESULT_ERROR_RADIO_OFF)
|| (mResultCode == SmsManager.RESULT_ERROR_NO_SERVICE)) {
TexterDB.getInstance().updateStatus(rowid,
Schedule.STATUS_NOT_SENT, -1);
} else {
mToastHandler.sendEmptyMessage(TOAST_HANDLER_MESSAGE_FAILED);
TexterDB.getInstance().updateStatus(rowid,
Schedule.STATUS_NOT_SENT, mResultCode);
}
if (forwardToSystemApp) {
try {
PendingIntent.getBroadcast(this, 0, sysIntent, 0).send(
mResultCode);
} catch (CanceledException e) {
e.printStackTrace();
}
}
}
/**
* Start the service to process the current event notifications, acquiring
* the wake lock before returning to ensure that the service will run.
*/
public static void beginStartingService(Context context, Intent intent) {
synchronized (mStartingServiceSync) {
if (mStartingService == null) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
mStartingService = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"Texter.SmsReceiverService");
mStartingService.setReferenceCounted(false);
}
mStartingService.acquire();
context.startService(intent);
Log.v(LOG_TAG, "service started");
}
}
/**
* Called back by the service when it has finished processing notifications,
* releasing the wake lock if the service is now stopping.
*/
public static void finishStartingService(Service service, int startId) {
synchronized (mStartingServiceSync) {
if (mStartingService != null) {
if (service.stopSelfResult(startId)) {
mStartingService.release();
}
}
}
}
}
Look at the top of the trace... look at the code at:
com.texter.messenger.SmsReceiverService$ServiceHandler.handleMessage(SmsReceiverService.java:116)
Looking at the code... check that the variable intent is not null before you call handleSmsReceived
I had the same bug, still looking for the correct solution but temporarily I just comment out the onDetachFromWindow() method. In my case it was for testing purpose so commenting it out didn't affect me but not sure what's in your case but give it a try.
In general, this question/answer gives an introduction to reading these errors:
What is a stack trace, and how can I use it to debug my application errors?
Looking at the code, intent should not be null, after all intent.getAction() executes without error.
It seems more likely that you have a problem with ViewFlipper, getting some "Receiver not registered" exception in the nested stack trace:
java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$1#40597cc0
Maybe this question can point you in the right direction:
ViewFlipper : Receiver not registered
Related
I would like to write applications for android, which is designed to send data from sensors such as accelerometer, gyroscope, etc.
via bluetooth to another device.
I download from github Bluetooth Chat on Android and wrote a class that gets data from the accelerometer, but I can not connect it.
Here is a the link to github I downloaded:
https://github.com/googlesamples/android-BluetoothChat
Here is the class from this github which I tried to change:
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context.*;
import com.example.android.common.logger.Log;
/**
* This fragment controls Bluetooth to communicate with other devices.
*/
public class BluetoothChatFragment extends Fragment{
private static final String TAG = "BluetoothChatFragment";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private Sensor mySensor;
private SensorManager SM;
private float x, y, z;
private SensorEvent event;
/**
* Name of the connected device
*/
private String mConnectedDeviceName = null;
/**
* Array adapter for the conversation thread
*/
private ArrayAdapter<String> mConversationArrayAdapter;
/**
* String buffer for outgoing messages
*/
private StringBuffer mOutStringBuffer;
/**
* Local Bluetooth adapter
*/
private BluetoothAdapter mBluetoothAdapter = null;
/**
* Member object for the chat services
*/
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) {
mChatService.stop();
}
}
#Override
public void onResume() {
super.onResume();
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
mConversationView = (ListView) view.findViewById(R.id.in);
mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
mSendButton = (Button) view.findViewById(R.id.button_send);
}
/**
* Set up the UI and background operations for chat.
*/
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.message);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
View view = getView();
// if (null != view) {
TextView textView = (TextView) view.findViewById(R.id.edit_text_out);
String message = textView.getText().toString();
sendMessage(message);
// }
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(getActivity(), mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
/**
* Makes this device discoverable for 300 seconds (5 minutes).
*/
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
*
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() >= 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
/**
* The action listener for the EditText widget, to listen for the return key
*/
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
/**
* Updates the status on the action bar.
*
* #param resId a string resource ID
*/
private void setStatus(int resId) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(resId);
}
/**
* Updates the status on the action bar.
*
* #param subTitle status
*/
private void setStatus(CharSequence subTitle) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
/**
* The Handler that gets information back from the BluetoothChatService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " );
break;
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName + ": " + readMessage);
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
/**
* Establish connection with other device
*
* #param data An {#link Intent} with {#link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* #param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}
case R.id.discoverable: {
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
}
return false;
}
public void setX(float x)
{
this.x = x;
}
public void setY(float y)
{
this.y = y;
}
public void setZ(float z)
{
this.z = z;
}
}
And here is Accelerometer Class:
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.support.v7.app.AppCompatActivity;
public class AkcelerometrActivity extends AppCompatActivity implements SensorEventListener {
private Sensor mySensor;
private SensorManager SM;
private float x, y, z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akcelerometr);
SM = (SensorManager)getSystemService(SENSOR_SERVICE);
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
public void onSensorChanged(SensorEvent event)
{
x = event.values[0];
y = event.values[1];
z = event.values[2];
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public float getZ()
{
return z;
}
}
Any ideas?
Thank you in advance.
package com.example.trynot;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;
import com.example.trynot.MainActivity;
import com.example.trynot.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.sax.StartElementListener;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
public class MainActivity extends Activity {
private static final int MY_DATA_CHECK_CODE = 1234;
public static Context c,b;
public TextToSpeech tts;
public static Intent serviceIntent;
private static int myNotificationId;
public static class ReadMailSample extends AsyncTask<String,String,Void> implements TextToSpeech.OnInitListener{
Message message;
private TextToSpeech tts;
static String command, phoneNumber, type, priority, name, time_stamp, imei, opt1, opt2, opt3, fromSubString;
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
String userName="avarote1994#gmail.com" ; // PROVIDE RECEPIENT EMAIL ID
String password="amul11111994" ; // PROVIDE RECEPIENT PASSWORD
static SQLiteDatabase db;
boolean flag=false;
Context acn;
//private Bundle savedInstanceState;
protected Void doInBackground(String...params){ // SEPARATE THREAD TO RUN IN THE BACKGROUND
try{
readMails();
}
catch(Exception e){
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.INFO, "an exception was thrown", e);
}
return null;
}
ReadMailSample(SQLiteDatabase db){
this.db = db;
}
ReadMailSample(){
}
ReadMailSample(Context cn){
acn=cn;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
tts = new TextToSpeech(c,ReadMailSample.this);
}
#Override
protected void onProgressUpdate(String... values) {
try {
System.out.println("---------------------adasd-----------" + time_stamp);
showNotification();
speakOut();
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.speak(command, TextToSpeech.QUEUE_FLUSH, null);
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut() {
tts.speak("hello hi", TextToSpeech.QUEUE_FLUSH, null);
}
public void showNotification() {
PendingIntent notificationIntent = preparePendingIntent();
Notification notification = createBasicNotification(notificationIntent);
displayNotification(notification);
}
#SuppressLint("InlinedApi")
private PendingIntent preparePendingIntent() {
Intent intent=new Intent(c,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
c,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
private Notification createBasicNotification(PendingIntent notificationIntent) {
NotificationCompat.Builder builder = new Builder(c);
long[] vibrationPattern = {0, 200, 800, 200, 600, 200, 400, 200, 200, 200, 100, 200, 50, 200, 50, 200, 50, 200, 50, 200};
Notification notification = builder
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Medication Reminder")
.setContentText(command)
.setAutoCancel(true)
.setContentIntent(notificationIntent)
.setWhen(Calendar.getInstance().getTimeInMillis() + 1000*60+60)
.setVibrate(vibrationPattern)
.build();
return notification;
}
private void displayNotification(Notification notification) {
NotificationManager notificationManager = (NotificationManager)c.getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationId=(int) System.currentTimeMillis();
notificationManager.notify(myNotificationId , notification);
}
public void readMails() throws IOException{
System.out.println("READMAIL hi");
properties = new Properties();
// SETTING UP AN IMAP SERVER TO ACCESS THE RECEPIENT'S EMAIL
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
while(true){// CONTINUOUSLY MONITOR INCOMING MAIL'S
//String cq = "select * from Login4";
//Cursor c = db.rawQuery(cq, null);
// c.moveToFirst();
//final String userName = c.getString(0);
//final String password = c.getString(1);
//String cloud = "avarote1994#gmail.com";
// AUTHENTICATE AND GET AN INSTANCE OF THE SESSION FROM THE SERVER
session = Session.getInstance(properties,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX"); // ACCESS THE INBOX OF THE RECEPIENT'S EMAIL ID
inbox.open(Folder.READ_WRITE); // OPEN THE INBOX IN READ-WRITE MODE
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false)); //SEARCH INBOX FOR ANY UNREAD MAILS
System.out.println("Number of mails = " + messages.length);
for (int i = 0; i < messages.length; i++) { // PROCESS ALL THE UNREAD MAILS
message = messages[i];
Address[] from = message.getFrom();
String from1 = from[0].toString();
System.out.println(from1);
if(from1.contains("<")){
int start = from1.indexOf("<");
int end = from1.indexOf(">");
fromSubString = from1.substring(start+1,end); // RETRIEVE THE SENDER'S EMAIL ID
} else{
fromSubString = from1;
}
System.out.println(fromSubString);
//if(fromSubString.equals(cloud)){ // CHECK WHETHER THE MAIL IS FROM THE CLOUD
String[] subject = message.getSubject().split(","); // SPLIT THE SUBJECT
System.out.println("hi");
type = subject[0]; // STORE THE DETAILS IN RESPECTIVE VARIABLES
phoneNumber =subject[1];
name = subject[2];
System.out.println(type);
System.out.println(phoneNumber);
System.out.println(name);
//String body=message.getContentType().toString();
// System.out.print(body);
processMessageBody(message);
//System.out.println("--------------------------------");
// }
}
inbox.close(true);
store.close();
}
catch (NoSuchProviderException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
String msg=content.toString();
System.out.println(msg);
if (content instanceof Multipart) { // IF MAIL HAS MULTIPART MESSAGE
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
}
else{
System.out.println("Content = "+content);
processSinglepart(content.toString());
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
}
public void processSinglepart(String content){
String[] body = content.split(","); // SPLIT THE CONTENTS OF THE BODY
System.out.println('1');
time_stamp = body[0]; // STORE THE DETAILS IN RESPECTIVE VARIABLES
command = body[3];
System.out.println(time_stamp);
//tts.speak(time_stamp, TextToSpeech.QUEUE_FLUSH, null);
publishProgress(command);
}
public void procesMultiPart(Multipart content) {
System.out.println("amulya");
try {
BodyPart bodyPart = content.getBodyPart(0); // RETRIEVE THE CONTENTS FROM THE BODY
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Content Multipart= "+o.toString());
processSinglepart(o.toString());
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
c = this.getApplicationContext();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadMailSample rd=new ReadMailSample(getApplicationContext());
System.out.println("hello");
rd.execute();
System.out.println("------xvsdfsdfsd---------aefaefa-----------------");
}
#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
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am trying to implement texttospeech functionality. I am getting the above error. The functionality runs in async thread. The async thread reads mail. I want to convert the read mail to speech.
Logcat:
02-08 21:45:26.009: I/System.out(12947): TESTING
02-08 21:45:26.709: I/System.out(12947): javax.mail.internet.MimeMultipart#21cdab10
02-08 21:45:26.709: I/System.out(12947): amulya
02-08 21:45:27.279: I/System.out(12947): Content Multipart= 1221235487821,ad:af:12:2a:d5:c8,High,IT IS THURSDAY TAKE TABLETS,future
02-08 21:45:27.279: I/System.out(12947): use,future use,future use
02-08 21:45:27.279: I/System.out(12947): 1
02-08 21:45:27.279: I/System.out(12947): 1221235487821
02-08 21:45:27.279: I/System.out(12947): ---------------------adasd-----------1221235487821
02-08 21:45:27.299: W/TextToSpeech(12947): speak failed: TTS engine connection not fully set up
02-08 21:45:29.689: D/dalvikvm(12947): GC_FOR_ALLOC freed 455K, 19% free 5727K/7068K, paused 7ms, total 7ms
02-08 21:45:30.499: I/System.out(12947): Number of mails = 0
02-08 21:45:36.029: I/System.out(12947): Number of mails = 0
I have solved this issue with audible speech
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.HashMap;
import java.util.Locale;
public class Speecher implements TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechController";
private TextToSpeech myTTS;
private String textToSpeak;
private Context context;
private static Speecher singleton;
public static Speecher getInstance(Context ctx) {
if (singleton == null)
singleton = new Speecher(ctx);
return singleton;
}
private Speecher(Context ctx) {
context = ctx;
}
public void speak(String text) {
textToSpeak = text;
if (myTTS == null) {
// currently can\'t change Locale until speech ends
try {
// Initialize text-to-speech. This is an asynchronous operation.
// The OnInitListener (second argument) is called after
// initialization completes.
myTTS = new TextToSpeech(context, this);
} catch (Exception e) {
e.printStackTrace();
}
}
sayText();
}
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.UK) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.UK);
myTTS.setPitch((float) 0.9);
}
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (initStatus == TextToSpeech.SUCCESS) {
int result = myTTS.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "TTS missing or not supported (" + result + ")");
// Language data is missing or the language is not supported.
// showError(R.string.tts_lang_not_available);
} else {
// Initialization failed.
Log.e(TAG, "Error occured");
}
}
}
private void sayText() {
HashMap<String, String> myHash = new HashMap<String, String>();
myHash.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "done");
String[] splitspeech = this.textToSpeak.split("\\\\");
for (int i = 0; i < splitspeech.length; i++) {
if (i == 0) { // Use for the first splited text to flush on audio stream
myTTS.speak(splitspeech[i].toString().trim(), TextToSpeech.QUEUE_FLUSH, myHash);
} else { // add the new test on previous then play the TTS
myTTS.speak(splitspeech[i].toString().trim(), TextToSpeech.QUEUE_ADD, myHash);
}
myTTS.playSilence(100, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void stopTTS() {
if (myTTS != null) {
myTTS.shutdown();
myTTS.stop();
myTTS = null;
}
}
}
Calling method from any where...
Speecher.getInstance(getApplicationContext()).speak(YOUR_TTS_MESSAGE_HERE);
From the Api Docs we see that your implementation of OnInitListener is necessesary to receive a notification that the TTS initialization is complete. This is described in the TextToSpeech docs as well where it is stated that the speech will fail until initialized. In the following, I will not attempt to fix all of your code so that it works, but I will point out how you're mis-using the TTS framework currently and nudge you in the right direction.
Though you have implemented onInitListener, you aren't doing anything useful with that implementation. Below, I show something more useful in which one captures the result of onInitListener's onInit callback, in order to remain aware of the initialization state of TTS.
...
private boolean mIsTTSInited = false; // member indicating TTS initialization state
...
// Receives notification of initialization
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.i("TTS", "Initilization Succeeded!");
// save the state indicating success of TTS initialization
mIsTTSInited = true;
...
} else {
Log.e("TTS", "Initilization Failed!");
mIsTTSInited = false;
}
}
...
...
#Override
protected void onProgressUpdate(String... values) {
// A trivial example to show how you can check the state of initialization for TTS
if (mIsTTSInited) {
showNotification();
speakOut();
} else {
// code to deal with TTS not init'ed case
}
}
Additionally, I wouldn't run the TextToSpeech initialization as part of the AsyncTask. If I were you, I'd move
tts = new TextToSpeech(c,ReadMailSample.this);
into onCreate rather than onPreExecute. I see this used in the tutorials seen here, and here
I got this code from the Internet and I modified it to upload a specific file automatically to Google Drive when starting the activity.
It is always ask me to select my Google account when I start this activity!
I want it ask about Google account once only when started for the first time after install it, How to do that?
package com.example.googledrive;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Arrays;
import java.io.IOException;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int REQUEST_DOWNLOAD_FILE = 3;
static final int RESULT_STORE_FILE = 4;
private static Uri mFileUri;
private static Drive mService;
private GoogleAccountCredential mCredential;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setup for credentials for connecting to the Google Drive account
mCredential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE));
// start activity that prompts the user for their google drive account
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
// mContext = getApplicationContext();
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
{
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
mService = getDriveService(mCredential);
}
saveFileToDrive();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
//account already picked
} else {
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
break;
}
}
private Drive getDriveService(GoogleAccountCredential credential)
{
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
private void saveFileToDrive()
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// Create URI from real path
String path;
path = "/sdcard/DCIM/Camera/a.png";
mFileUri = Uri.fromFile(new java.io.File(path));
ContentResolver cR = MainActivity.this.getContentResolver();
// File's binary content
java.io.File fileContent = new java.io.File(mFileUri.getPath());
FileContent mediaContent = new FileContent(cR.getType(mFileUri), fileContent);
showToast("Selected " + mFileUri.getPath() + "to upload");
// File's meta data.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType(cR.getType(mFileUri));
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.Insert i1 = f1.insert(body, mediaContent);
File file = i1.execute();
if (file != null)
{
showToast("Uploaded: " + file.getTitle());
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
showToast("Transfer ERROR: " + e.toString());
}
}
});
t.start();
}
public void showToast(final String toast)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
}
It's been a while, so you probably managed to do this by now, but I was just looking for the same thing and it's fairly easy. In the code you use and how it's used on several sites you get an Intent after calling a static method on GoogleAccountCredential.
You can also create your own, by calling a static method on AccountPicker and define a params that it's only required to pick once.
Intent accountPicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(accountPicker, GOOGLE_ACCOUNT_PICKED);
The fourth param is what you want and you can read more about it here:
https://developers.google.com/android/reference/com/google/android/gms/common/AccountPicker?hl=en
I'm trying to get user location in the background.
Everything works great on my phone (htc one m7), but from some reason it's not working on two devices I tested:
Samsung galaxy s3
Sony Xperia Z1
btw: I added everything to the manifest as it should be.
this is my code:
**BackgroundLocationService **
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;
public class BackgroundLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
IBinder mBinder = new LocalBinder();
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
public class LocalBinder extends Binder {
public BackgroundLocationService getServerInstance() {
return BackgroundLocationService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
mInProgress = false;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(0);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(1);
servicesAvailable = servicesConnected();
/*
* Create a new location client, using the enclosing class to
* handle callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
if(!servicesAvailable || mLocationClient.isConnected() || mInProgress)
return START_STICKY;
setUpLocationClientIfNeeded();
if(!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress)
{
mInProgress = true;
mLocationClient.connect();
}
return START_STICKY;
}
/*
* Create a new location client, using the enclosing class to
* handle callbacks.
*/
private void setUpLocationClientIfNeeded()
{
if(mLocationClient == null)
mLocationClient = new LocationClient(this, this, this);
}
// Define the callback method that receives location updates
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void appendLog(String text, String filename)
{
File logFile = new File(filename);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDestroy(){
// Turn off the request flag
mInProgress = false;
if(servicesAvailable && mLocationClient != null) {
//mLocationClient.removeLocationUpdates(callbackIntent);
// Destroy the current location client
mLocationClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
Intent intent = new Intent(this, LocationReceiver.class);
PendingIntent locationIntent = PendingIntent.getBroadcast(getApplicationContext(), 14872, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mLocationClient.requestLocationUpdates(mLocationRequest, locationIntent);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mLocationClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
}
**LocationReceiver **
import java.util.List;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.LocationClient;
public class LocationReceiver extends BroadcastReceiver {
public static double lat;
public static double alt;
public static String address;
#Override
public void onReceive(Context context, Intent intent) {
Location location = (Location) intent.getExtras().get(LocationClient.KEY_LOCATION_CHANGED);
Log.d("New Location Reciver", "location "+location.toString());
lat = location.getLatitude();
alt = location.getAltitude();
address = getAddressByCord(lat, alt, context);
}
public static String getAddressByCord(double lat, double longi, Context context) {
try {
Geocoder geo = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geo.getFromLocation(lat, longi, 1);
if (addresses.isEmpty()) {
return "Waiting for Location";
} else {
if (addresses.size() > 0) {
String s = "";
if (addresses.get(0).getFeatureName() != null)
s += addresses.get(0).getFeatureName();
if (addresses.get(0).getThoroughfare() != null)
s += "," + addresses.get(0).getThoroughfare();
if (addresses.get(0).getLocality() != null)
s += "," + addresses.get(0).getLocality();
if (addresses.get(0).getAdminArea() != null)
s += "," + addresses.get(0).getAdminArea();
if (addresses.get(0).getCountryName() != null)
s += "," + addresses.get(0).getCountryName();
return s;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
if someone has any idea, Thank you!
code to check for google play services.
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 94378;
private boolean isGooglePlay() {
int mIsGooglePlayServicesAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
switch (mIsGooglePlayServicesAvailable) {
case ConnectionResult.SUCCESS:
return true;
default:
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
mIsGooglePlayServicesAvailable, this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
"Location Updates");
}
// case ConnectionResult.SERVICE_MISSING:
// case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
// case ConnectionResult.SERVICE_DISABLED:
// case ConnectionResult.SERVICE_INVALID:
// case ConnectionResult.DATE_INVALID:
}
return false;
}
/*
* This is a class used to resolve errors with google play services It is
* copied code that doesn't run durring normal operation.
*/
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
I found the answer.
It was the devices own definitions.
The device was not enabling apps to use location .
thank you anyway!
I am very new to Android developing, so hopefully this is an easy one to answer. I have done lots of searching but cannot find an answer - possibly I am going about it the wrong way.
I have two class files, one is to get the battery level info (class A below) and the other uses TelephonyManager to get the device IMEI and display that (class B below).
I cannot work out how you can get the values of these two classes to appear on the same layout.
This is class A:
package com.XXXXXX.XXXXXX;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class AboutScreen extends ListActivity {
/** Called when the activity is first created. */
private String[] strText = new String[] {"Battery Level", "Voltage", "Status"};
private int voltage = 0;
private boolean trun = true;
private Handler myHandler = new Handler();
private Runnable myRun = new Runnable() {
public void run() {
updateNow();
}
};
// using Thread to keep the process running
private Thread myThread = new Thread() {
public void run () {
do {
batteryLevelUpdate();
myHandler.post(myRun);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (trun);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "email", 2000).show();
startMonitor();
}
#Override
public void onDestroy() {
trun = false;
super.onDestroy();
}
private void startMonitor() {
myThread.start();
}
private void updateNow() {
ListView thisListView = getListView();
thisListView.setEnabled(false);
ArrayAdapter<String> myList = new ArrayAdapter<String>(this, R.layout.about_screen, strText);
thisListView.setAdapter(myList);
}
private void batteryLevelUpdate() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int onplug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
boolean onUSB = onplug == BatteryManager.BATTERY_PLUGGED_USB;
boolean onAC = onplug == BatteryManager.BATTERY_PLUGGED_AC;
String strStatus = "Charging on ";
if (isCharging && onUSB)
strStatus += "USB";
else if (isCharging && onAC)
strStatus += "AC Power";
else
strStatus = "Battery Discharging";
strText[0] = "Battery Level: " + Integer.toString(level) + "%";
strText[1] = "Voltage: " + Integer.toString(voltage) + "mV";
strText[2] = strStatus;
//strText[3] = "test";
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
}
This is class B:
package com.XXXXXX.XXXXXX;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class AndroidTelephonyManager extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phone);
TextView textDeviceID = (TextView)findViewById(R.id.deviceid);
//retrieve a reference to an instance of TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
textDeviceID.setText(getDeviceID(telephonyManager));
}
String getDeviceID(TelephonyManager phonyManager){
String id = phonyManager.getDeviceId();
if (id == null){
id = "not available";
}
int phoneType = phonyManager.getPhoneType();
switch(phoneType){
case TelephonyManager.PHONE_TYPE_NONE:
return "NONE: " + id;
case TelephonyManager.PHONE_TYPE_GSM:
return "GSM: IMEI=" + id;
case TelephonyManager.PHONE_TYPE_CDMA:
return "CDMA: MEID/ESN=" + id;
/*
* for API Level 11 or above
* case TelephonyManager.PHONE_TYPE_SIP:
* return "SIP";
*/
default:
return "UNKNOWN: ID=" + id;
}
}
}
This is the layout file which displays the battery level info just fine:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="12sp"
android:clickable="false" />
However I have no idea how you can get the IMEI info from the class B to show as well. Ideally it would be another list row underneath the battery level items. Any advice on how you can combine different activities into one layout would be really useful.
Apologies if my explanation isn't great, but my java understanding is novice at the moment.
Many thanks
Use static method, for example
static String getDeviceID(TelephonyManager phonyManager)
then call the methods with class name,
classB.getDeviceID(phonyManager);
I think you might have got some basic concept wrong here. Activity is only for UI. Its not required that you need one Activity for one particular functionality. So you can have both the functionalities in one single activity, and update its layout.
You can write these values into Sharedpreferences....
getSharedPreferences("sp", MODE_PRIVATE).
edit().
putString("login", ed_login.getText().toString()).
commit();
So then you can get it anywhere by ...
getSharedPreferences("sp", MODE_PRIVATE).getString("login", "");