Search Results

Search found 97 results on 4 pages for 'broadcastreceiver'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • Questions Regarding Handling of Received SMS

    - by Edwin
    Hi, i have managed to successfully write a little test app that can receive and send SMS, but got a couple of questions. (That's 'cos part of the code i copied from elsewhere and i would like to understand better). In my AndroidManifest as well as the sub-class of BroadcastReceiver, there is reference to the string literal "android.provider.Telephony.SMS_RECEIVED". However, i couldn't find any reference in the API that mentions this. Could someone point me to some reference that lists/explains these? As part of getting the message from the Intent, i did this: Object[] pdus = (Object[]) intent.getExtras().get("pdus"); Again this question is related to the use of hardcoded string literal. Where is the string "pdus" listed and described? Thanks in advance!

    Read the article

  • BroadCast Receiver calling intent after some time android

    - by khushi
    public class myReceiver extends BroadcastReceiver { public static boolean wasScreenOn = true; @Override public void onReceive(final Context context, Intent recievedIntent) { if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { wasScreenOn = false; Intent intent = new Intent(context, myActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); context.startActivity(intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } else if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_ON)) { wasScreenOn = true; } } } The activity display after when action screen on is call.

    Read the article

  • Is it possible to creating a Service without starting it?

    - by ThaMe90
    Hello all, I wonder, is it possible to create a Service, set some data, and then start it? I haven't come across a thread specific to this problem, so I would like to know if it is possible (if it is known of course). My problem is that I have a Service which listens to a DatagramSocket, but the socket in question needs to be set after creation, but before the start of the Service. The setting of the socket happens through the use of a Broadcast (I broadcast 2 Strings which hold the IP-Address & Port and the BroadcastReceiver then constructs a socket for me). When the Service is started, a Thread will start to run and listen to the supposedly created socket. This, sadly, doesn't happen. The socket will remain null and I can't set it when the Thread is running (This is another issue I hope to tackle in the future, if anybody got any ideas about this, please notify me). So, is what I want possible, or should I come up with another construct for achieving this goal?

    Read the article

  • Android how to call a method of MainActivity in SmsReceiver Class

    - by GeneticSmart
    I'm very new to Android Programming, It would be really great if someone can help me in this.My project contains two JAVA files. MainActivity.java extends Activity SMSReceiver.java extends Broadcastreceiver The SMSreceiver.java has the code which displays any incoming SMS in toast. Can you please tell me how to call a function in MainActivity whenever a particular SMS is received. For eg: when I receive sms called as starttemp it should call a function starttemp. I have searched a lot and found that intents are a way to do this and we cannot call these methods directly. Please can anyone help me in this? And it would be really great if someone can send me working code.

    Read the article

  • Android: how to start a service at boot based on user-settings?

    - by Cicerone Cojocaru
    Hey everyone, I'm trying to write an app that consists of an activity that manages a background service. However, I want to implement a user setting for automatically starting the service up at boot time. I have user settings implemented with SharedPreferences and I have the services starting up at boot by using a BroadcastReceiver and listening for BOOT_COMPLETED. However, I can't figure out a good way to implement a setting so that the service is only started at boot if said setting is enabled. I can think of a few cheap ways to do this (such as messing with onCreate() in the service, or creating/checking for a file on SD card) but I want to follow good practice. There must be a good way to do this because there's tons of apps out there that do it, I just can't find anything online about how to do it. Thanks

    Read the article

  • How to remove icon programatically (Android)

    - by user1865039
    By remove the below intent-filter in AndroidManifest.xml, it can remove the icon after install. <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> But i have try the below when on Boot than remove the Icon, but the icon still remain after reboot. I have add the permission, and this reboot receiver is work. public class BootBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { PackageManager p = context.getApplicationContext().getPackageManager(); ComponentName componentName = new ComponentName("com.example.remove_icon","com.example.remove_icon.LauncherActivity"); p.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } }

    Read the article

  • RemoteViewsService never gets called whenever we update app widget

    - by user3689160
    I am making one task widget application. This is a simple widget application which can be used to add new tasks by clicking on "+New Task". So ideally what I have done is, I've added a widget first, then when we click on "+New Task" a new activity opens up from where we can type in a new task and it should get updated in the ListView inside the home screen widget. Problem: Now whenever I add a new task, the ListView does not get updated. The data gets inside the database a new is created as well. My onUpdate(...) method gets called as well. There is a WidgetService.java which is a RemoteViewService that is being used to call the RemoteViewFactory but WidgetService.java gets called only when we create the widget, never after that. WidgetService.java never gets called again. I have the following setup MyWidgetProvider.java AppWidgetProvider class for updating the widget and filling its remote views. public class MyWidgetProvider extends AppWidgetProvider { public static int randomNumber=132; static RemoteViews remoteViews = null; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { updateList(context,appWidgetManager,appWidgetIds); } public static void updateList(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ final int N = appWidgetIds.length; Log.d("MyWidgetProvider", "length="+appWidgetIds.length+""); for (int i = 0; i<N; ++i) { Log.d("MyWidgetProvider", "value"+ i + "="+appWidgetIds[i]); // Calling updateWidgetListView(context, appWidgetIds[i]); to load the listview with data remoteViews = updateWidgetListView(context, appWidgetIds[i]); // Updating the Widget with the new data filled remoteviews appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.lv_tasks); } } private static RemoteViews updateWidgetListView(Context context, int appWidgetId) { Intent svcIntent = null; remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_demo); //RemoteViews Service needed to provide adapter for ListView svcIntent = new Intent(context, WidgetService.class); //passing app widget id to that RemoteViews Service svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); //setting a unique Uri to the intent //binding the data from the WidgetService to the svcIntent svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME))); //setting adapter to listview of the widget remoteViews.setRemoteAdapter(R.id.lv_tasks, svcIntent); //setting click listner on the "New Task" (TextView) of the widget remoteViews.setOnClickPendingIntent(R.id.tv_add_task, buildButtonPendingIntent(context)); return remoteViews; } // Just to create PendingIntent, this will be broadcasted everytime textview containing "New Task" is clicked and OnReceive method of MyWidgetIntentReceiver.java will run public static PendingIntent buildButtonPendingIntent(Context context) { Intent intent = new Intent(); intent.putExtra("TASK_DONE_VALUE_VALID", false); intent.setAction("com.ommzi.intent.action.CLEARTASK"); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } // This method is defined here so that we can update the remoteviews from other classes as well, like we'll do it in MyWidgetIntentReceiver.java public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) { ComponentName myWidget = new ComponentName(context, MyWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(myWidget, remoteViews); } } WidgetService.java A RemoteViewsService class for creating a RemoteViewsFactory. public class WidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID); return (new ListProvider(this.getApplicationContext(), intent)); } } ListProvider.java A RemoteViewsFactory class for filling the ListView inside the widget. public class ListProvider implements RemoteViewsFactory { private List<TemplateTaskData> tasks; private Context context = null; private int appWidgetId; int increment=0; public ListProvider(Context context, Intent intent) { this.context = context; appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID); //appWidgetId = Integer.valueOf(intent.getData().getSchemeSpecificPart())- MyWidgetProvider.randomNumber; populateListItem(); } private void populateListItem() { tasks = new ArrayList<TemplateTaskData>(); com.ommzi.database.sqliteDataBase letStartDB = new com.ommzi.database.sqliteDataBase(context); letStartDB.open(); tasks=letStartDB.getData(); letStartDB.close(); } public int getCount() { return tasks.size(); } public long getItemId(int position) { return position; } public RemoteViews getViewAt(int position) { // We are only showing the text view field here as there is limitation on using Checkbox within the widget // We prefer to on an activity for the user to make comprehensive changes as changes inside the widget is always limited. // To view the supported list of views for the widget you can visit http://developer.android.com/guide/topics/appwidgets/index.html final RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.screen_wcitem); TemplateTaskData taskDTO = tasks.get(position); Log.d("My ListProvider", "1"); remoteView.setTextViewText(R.id.wc_add_task, taskDTO.getTaskName()); if(taskDTO.getTaskDone()){ remoteView.setImageViewResource(R.id.imageView1, R.drawable.checked); }else{ remoteView.setImageViewResource(R.id.imageView1, R.drawable.unchecked); } Intent intent = new Intent(); intent.setAction("com.ommzi.intent.action.GETTASK"); intent.putExtra("TASK_DONE_VALUE_VALID", true); intent.putExtra("ROWID", taskDTO.getRowId()); intent.putExtra("TASK_NAME", taskDTO.getTaskName()); intent.putExtra("TASK_DONE_VALUE", taskDTO.getTaskDone()); remoteView.setOnClickPendingIntent(R.id.imageView1, PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); Log.d("My ListProvider, Inside getView", "Value of Incrementor=" + increment + "\n ROWID=" + taskDTO.getRowId() + "\n TASK_NAME=" + taskDTO.getTaskName() + "\n TASK_DONE_VALUE=" +taskDTO.getTaskDone() + "\n Total Database Size=" + tasks.size()); return remoteView; } public RemoteViews getLoadingView() { // TODO Auto-generated method stub return null; } public int getViewTypeCount() { // TODO Auto-generated method stub return 1; } public boolean hasStableIds() { // TODO Auto-generated method stub return false; } public void onCreate() { // TODO Auto-generated method stub } public void onDataSetChanged() { // TODO Auto-generated method stub } public void onDestroy() { // TODO Auto-generated method stub } } GetTaskActivity.java This is another activity that is fired from a BroadcastReceiver(MyWidgetIntentReceiver.java). Purpose of this is to get a new task added to the list of task. MyWidgetIntentReceiver.java BroadcastReceiver fired using a pending intent that starts an activity GetTaskActivity.java. Please help me out with this problem. I am seen all the posts here and on other websites no body is having any solution. But I am sure a solution exist to this. Thanks for your help!

    Read the article

  • Android Scan for Wifi networks

    - by Nils
    Hello, I'm trying to scan for wireless networks and found this helpful source on the net. Unfortunately it's not working and I have no idea why. My problem is that I can't wait 10 minutes for the result - I need them within a few seconds and thought about setting the boolean variable waiting on false as soon as I get a result.... well, it runs forever ... looks like nothing is received. Any idea ? Thanks. // -- Sample WiFi implementation - http://groups.google.com/group/android-developers/browse_thread/thread/f722d5f90cfae69 IntentFilter i = new IntentFilter(); i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); registerReceiver(new BroadcastReceiver(){ @Override public void onReceive(Context c, Intent i){ // Code to execute when SCAN_RESULTS_AVAILABLE_ACTION event occurs mWifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE); wireless = mWifiManager.getScanResults(); // Returns a <list> of scanResults waiting = false; } } ,i); // -- End Wifi Sample mWifiManager.startScan(); while (waiting) { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("PROJECT1","Wifi WAITING"); }

    Read the article

  • How to add share menu item to Gallery by code

    - by Anthony
    I know how to implement this issue by Menuifest.xml, see also: Google Android Developer Group related issue But my question is how to add share menu of Gallery by java code not Menuifest.xml. My code is as below: public class MyActivity extends Activity { private static final String TAG = "MyActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_SEND); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); try { intentFilter.addDataType("image/*"); } catch (MalformedMimeTypeException e) { Log.e(TAG, e.toString()); } Intent x = registerReceiver(new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { Log.d(TAG, "Received intent "+intent); intent.setComponent(new ComponentName(context, Uploader.class)); startActivity(intent); } }, intentFilter); if (x==null) Log.i(TAG, "failed to regist a receiver"); else Log.i(TAG, "registed a receiver successfully"); // ... But registerReceiver always return null, and there is no menu added to Gallery's Share. Thank you. Anthony Xu

    Read the article

  • [android] Is it possible to receive SMS message on appWidget?

    - by cappuccino
    [Android] Hi, everyone. Is it possible to receive SMS message on appWidget? I saw android sample soucrce(API Demos). In API Demos, ExampleAppWidgetProvider class extends AppWidgetProvider, not Activity. So, I guess it is impossible to regist SMS Receiver like this, rcvIncoming = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("telephony", "SMS received"); Bundle data = intent.getExtras(); if (data != null) { // SMS uses a data format known as a PDU Object pdus[] = (Object[]) data.get("pdus"); String message = "New message:\n"; String sender = null; for (Object pdu : pdus) { SmsMessage part = SmsMessage.createFromPdu((byte[])pdu); message += part.getDisplayMessageBody(); if (sender == null) { sender = part.getDisplayOriginatingAddress(); } } Log.i(sender, message); } } }; registerReceiver(rcvIncoming, new IntentFilter("android.provider.Telephony.SMS_RECEIVED")); My goal is to receive SMS message on my custom appWidget. any help would be appreciated!!

    Read the article

  • Is it possible to receive SMS message on appWidget?

    - by cappuccino
    Is it possible to receive SMS message on appWidget? I saw android sample source(API Demos). In API Demos, ExampleAppWidgetProvider class extends AppWidgetProvider, not Activity. So, I guess it is impossible to regist SMS Receiver like this, rcvIncoming = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("telephony", "SMS received"); Bundle data = intent.getExtras(); if (data != null) { // SMS uses a data format known as a PDU Object pdus[] = (Object[]) data.get("pdus"); String message = "New message:\n"; String sender = null; for (Object pdu : pdus) { SmsMessage part = SmsMessage.createFromPdu((byte[])pdu); message += part.getDisplayMessageBody(); if (sender == null) { sender = part.getDisplayOriginatingAddress(); } } Log.i(sender, message); } } }; registerReceiver(rcvIncoming, new IntentFilter("android.provider.Telephony.SMS_RECEIVED")); My goal is to receive SMS message on my custom appWidget. Any help would be appreciated!!

    Read the article

  • Any guidelines for handling the Headset and Bluetooth AVRC transport controls in Android 2.2

    - by StefanK
    I am trying to figure out what is the correct (new) approach for handling the Intent.ACTION_MEDIA_BUTTON in Froyo. In pre 2.2 days we had to register a BroadcastReceiver (either permanently or at run-time) and the Media Button events would arrive, as long as no other application intercepts them and aborts the broadcast. Froyo seems to still somewhat support that model (at least for the wired headset), but it also introduces the registerMediaButtonEventReceiver, and unregisterMediaButtonEventReceiver methods that seem to control the "transport focus" between applications. During my experiments, using registerMediaButtonEventReceiver does cause both the bluetooth and the wired headset button presses to be routed to the application's broadcast receiver (the app gets the "transport focus"), but it looks like any change in the audio routing (for example unplugging the headset) shits the focus back to the default media player. What is the logic behind the implementation in Android 2.2? What is correct way to handle transport controls? Do we have to detect the change in the audio routing and try to re-gain the focus? This is an issue that any 3rd party media player on the Android platform has to deal with, so I hope that somebody (probably a Google Engineer) can provide some guidelines that we can all follow. Having a standard approach may make headset button controls a bit more predictable for the end users. Stefan

    Read the article

  • Get Object from memory using memory adresse

    - by Hamza Karmouda
    I want to know how to get an Object from memory, in my case a MediaRecorder. Here's my class: Mymic class: public class MyMic { MediaRecorder recorder2; File file; private Context c; public MyMic(Context context){ this.c=context; } private void stopRecord() throws IOException { recorder2.stop(); recorder2.reset(); recorder2.release(); } private void startRecord() { recorder2= new MediaRecorder(); recorder2.setAudioSource(MediaRecorder.AudioSource.MIC); recorder2.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder2.setOutputFile(file.getPath()); try { recorder2.prepare(); recorder2.start(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } my Receiver Class: public class MyReceiver extends BroadcastReceiver { private Context c; private MyMic myMic; @Override public void onReceive(Context context, Intent intent) { this.c=context; myMic = new MyMic(c); if(my condition = true){ myMic.startRecord(); }else myMic.stopRecord(); } } So when I'm calling startRecord() it create a new MediaRecorder but when i instantiate my class a second time i can't retrieve my Object. Can i retrieve my MediaRecorder with his addresse

    Read the article

  • Dynamically adding custom view to RemoteViews

    - by Naidu
    Could any help me to do this?My code is like: public CustomClass extends View { //uses ondraw() to do something } For displaying my custom view on HomeScreen i created a class to extend Broadcast Receiver public class customAppWidgetProvider extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main); //Here i want to create my custom view class object and i want to add this view to linear layout in main.xml CustomClass object = new CustomClass(context) ; LinearLayout layout = new LinearLayout(context) ; layout.setLayoutParameters(new LayoutParameters(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); layout.addView(object); views.addview(R.id.linearlayout, (ViewGroup) layout) ; views.setOnClickPendingIntent(R.id.analog_appwidget, PendingIntent.getActivity(context, 0, new Intent(context, AlarmClock.class), PendingIntent.FLAG_CANCEL_CURRENT)); int[] appWidgetIds = intent.getIntArrayExtra( AppWidgetManager.EXTRA_APPWIDGET_IDS); AppWidgetManager gm = AppWidgetManager.getInstance(context); gm.updateAppWidget(appWidgetIds, views); } } } But adding viewgroup to RemoteView reference is not working... above main.xml contains only LinearLayout.I want to add custom view object to it.But after running this not showing anything on screen.. please help me to do this.Thanks in Advance.

    Read the article

  • using IntentExatras with Alarm Manager

    - by Ashwin
    I want to know if this code will work(I cannot try it out right now. Moreover, I have a few doubts that have to be cleared). Intent intent = new Intent(context, AlarmReceiver.class); intent.putExtra("user",global.getUsername()); intent.puExtra("password",global.getPassword); PendingIntent sender = PendingIntent.getBroadcast(context, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Get the AlarmManager service Log.v("inside log_run", "new service started"); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.RTC_WAKEUP, IMMEDIATELY,60000,sender); finish(); As you can see, this code starts an AlarmManager with setRepeating(). If you see the intent(actually the pending intent) passed on to the BroadcastReceiver, there are two extras that are passed on. These are global variables that live as long as the Application is running. But this AlarmManager is meant to be run in the background (that is application will be alive only for the first few calls of the o fthe alrmamanager to the broadcast recevier) My Question Will AlarmManager make a copy of the global variables(the username and password) and maintain this copy to be passed along with the intent? Because, these values will be used in the broadcast receiver.

    Read the article

  • More efficient way of updating UI from Service than intents?

    - by Donal Rafferty
    I currently have a Service in Android that is a sample VOIP client so it listens out for SIP messages and if it recieves one it starts up an Activity screen with UI components. Then the following SIP messages determine what the Activity is to display on the screen. For example if its an incoming call it will display Answer or Reject or an outgoing call it will show a dialling screen. At the minute I use Intents to let the Activity know what state it should display. An example is as follows: Intent i = new Intent(); i.setAction(SIPEngine.SIP_TRYING_INTENT); i.putExtra("com.net.INCOMING", true); sendBroadcast(i); Intent x = new Intent(); x.setAction(CallManager.SIP_INCOMING_CALL_INTENT); sendBroadcast(x); Log.d("INTENT SENT", "INTENT SENT INCOMING CALL AFTER PROCESSINVITE"); So the activity will have a broadcast reciever registered for these intents and will switch its state according to the last intent it received. Sample code as follows: SipCallListener = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(SIPEngine.SIP_RINGING_INTENT.equals(action)){ Log.d("cda ", "Got RINGING action SIPENGINE"); ringingSetup(); } if(CallManager.SIP_INCOMING_CALL_INTENT.equals(action)){ Log.d("cda ", "Got PHONE RINGING action"); incomingCallSetup(); } } }; IntentFilter filter = new IntentFilter(CallManager.SIP_INCOMING_CALL_INTENT); filter.addAction(CallManager.SIP_RINGING_CALL_INTENT); registerReceiver(SipCallListener, filter); This works however it seems like it is not very efficient, the Intents will get broadcast system wide and Intents having to fire for different states seems like it could become inefficient the more I have to include as well as adding complexity. So I was wondering if there is a different more efficient and cleaner way to do this? Is there a way to keep Intents broadcasting only inside an application? Would callbacks be a better idea? If so why and in what way should they be implemented?

    Read the article

  • Android Bluetooth Fails to Pair

    - by CaseyB
    I am having a problem getting my devices to pair in Android. If I go into the settings and pair them manually I can get them to connect using the following code: Server // Make sure the device it discoverable mServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("Moo Productions Bluetooth Server", mUUID); mState = State.ACCEPTING; BluetoothSocket socket = mServerSocket.accept(); mServerSocket.close(); connected(socket); Client Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices(); BluetoothSocket socket = null; // Search the list of paired devices for the right one for(BluetoothDevice device : pairedDevices) { try { mState = State.SEARCHING; socket = device.createRfcommSocketToServiceRecord(mUUID); mState = State.CONNECTING; socket.connect(); connected(socket); break; } catch (IOException e) { socket = null; continue; } } But if the devices hadn't already been paired it gets out of the foreach without connecting to a valid socket. In that case I start discovering. // If that didn't work, discover if(socket == null) { mState = State.SEARCHING; mReceiver = new SocketReceiver(); mContext.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); mAdapter.startDiscovery(); } // ... Later ... private class SocketReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(BluetoothDevice.ACTION_FOUND.equals(intent.getAction())) { try { // Get the device and try to open a socket BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(mUUID); mState = State.CONNECTING; socket.connect(); // This is our boy, so stop looking mAdapter.cancelDiscovery(); mContext.unregisterReceiver(mReceiver); connected(socket); } catch (IOException ioe) { ioe.printStackTrace(); } } } } But it will never find the other device. I never get a pairing dialog and when I step through I see that it discovers the correct device, but it fails to connect with this exception java.io.IOException: Service discovery failed. Any ideas as to what I'm missing?

    Read the article

  • Android Notification with AlarmManager, Broadcast and Service

    - by user2435829
    this is my code for menage a single notification: myActivity.java public class myActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); cal = Calendar.getInstance(); // it is set to 10.30 cal.set(Calendar.HOUR, 10); cal.set(Calendar.MINUTE, 30); cal.set(Calendar.SECOND, 0); long start = cal.getTimeInMillis(); if(cal.before(Calendar.getInstance())) { start += AlarmManager.INTERVAL_FIFTEEN_MINUTES; } Intent mainIntent = new Intent(this, myReceiver.class); pIntent = PendingIntent.getBroadcast(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager myAlarm = (AlarmManager)getSystemService(ALARM_SERVICE); myAlarm.setRepeating(AlarmManager.RTC_WAKEUP, start, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent); } } myReceiver.java public class myReceiver extends BroadcastReceiver { @Override public void onReceive(Context c, Intent i) { Intent myService1 = new Intent(c, myAlarmService.class); c.startService(myService1); } } myAlarmService.java public class myAlarmService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); } @SuppressWarnings("deprecation") @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); displayNotification(); } @Override public void onDestroy() { super.onDestroy(); } public void displayNotification() { Intent mainIntent = new Intent(this, myActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(this); builder.setContentIntent(pIntent) .setAutoCancel(true) .setSmallIcon(R.drawable.ic_noti) .setTicker(getString(R.string.notifmsg)) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.notifmsg)); nm.notify(0, builder.build()); } } AndroidManifest.xml <uses-permission android:name="android.permission.WAKE_LOCK" /> ... ... ... <service android:name=".myAlarmService" android:enabled="true" /> <receiver android:name=".myReceiver"/> IF the time has NOT past yet everything works perfectly. The notification appears when it must appear. BUT if the time HAS past (let's assume it is 10.31 AM) the notification fires every time... when I close and re-open the app, when I click on the notification... it has a really strange behavior. I can't figure out what's wrong in it. Can you help me please (and explain why, if you find a solution), thanks in advance :)

    Read the article

  • Create and Share a File (Also a mysterious error)

    - by Kirk
    My goal is to create a XML file and then send it through the share Intent. I'm able to create a XML file using this code FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE); PrintStream printStream = new PrintStream(outputStream); String xml = this.writeXml(); // get XML here printStream.println(xml); printStream.close(); I'm stuck trying to retrieve a Uri to the output file in order to share it. I first tried to access the file by converting the file to a Uri File outFile = context.getFileStreamPath(fileName); return Uri.fromFile(outFile); This returns file:///data/data/com.my.package/files/myfile.xml but I cannot appear to attach this to an email, upload, etc. If I manually check the file length, it's proper and shows there is a reasonable file size. Next I created a content provider and tried to reference the file and it isn't a valid handle to the file. The ContentProvider doesn't ever seem to be called a any point. Uri uri = Uri.parse("content://" + CachedFileProvider.AUTHORITY + "/" + fileName); return uri; This returns content://com.my.package.provider/myfile.xml but I check the file and it's zero length. How do I access files properly? Do I need to create the file with the content provider? If so, how? Update Here is the code I'm using to share. If I select Gmail, it does show as an attachment but when I send it gives an error Couldn't show attachment and the email that arrives has no attachment. public void onClick(View view) { Log.d(TAG, "onClick " + view.getId()); switch (view.getId()) { case R.id.share_cancel: setResult(RESULT_CANCELED, getIntent()); finish(); break; case R.id.share_share: MyXml xml = new MyXml(); Uri uri; try { uri = xml.writeXmlToFile(getApplicationContext(), "myfile.xml"); //uri is "file:///data/data/com.my.package/files/myfile.xml" Log.d(TAG, "Share URI: " + uri.toString() + " path: " + uri.getPath()); File f = new File(uri.getPath()); Log.d(TAG, "File length: " + f.length()); // shows a valid file size Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Share")); } catch (FileNotFoundException e) { e.printStackTrace(); } break; } } I noticed that there is an Exception thrown here from inside createChooser(...), but I can't figure out why it's thrown. E/ActivityThread(572): Activity com.android.internal.app.ChooserActivity has leaked IntentReceiver com.android.internal.app.ResolverActivity$1@4148d658 that was originally registered here. Are you missing a call to unregisterReceiver()? I've researched this error and can't find anything obvious. Both of these links suggest that I need to unregister a receiver. Chooser Activity Leak - Android Why does Intent.createChooser() need a BroadcastReceiver and how to implement? I have a receiver setup, but it's for an AlarmManager that is set elsewhere and doesn't require the app to register / unregister. Code for openFile(...) In case it's needed, here is the content provider I've created. public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { String fileLocation = getContext().getCacheDir() + "/" + uri.getLastPathSegment(); ParcelFileDescriptor pfd = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY); return pfd; }

    Read the article

  • why is my intent not useful?

    - by user1634887
    This is my first to ask here. I write the code for a Broadcast A start another Broadcast B. But the Broadcast B didn't get the intent's value. Broadcast A:get the sms contain message and start B public void onReceive(Context context, Intent intent) { Object[] pdus=(Object[])intent.getExtras().get("pdus"); for(Object pdu:pdus) { byte[] date=(byte[])pdu; SmsMessage message=SmsMessage.createFromPdu(date); String sender=message.getOriginatingAddress(); String body=message.getMessageBody(); if(sender.equals(AppUtil.herPhone)&&body.regionMatches(0, AppUtil.herSmsText, 0, 18)) { Toast.makeText(context, body, Toast.LENGTH_LONG).show(); String [] bodyArray=body.split(" "); String longitude=bodyArray[1]; String latitude=bodyArray[2]; **Intent uiIntent=new Intent(); Bundle bundle=new Bundle(); bundle.putString("longitude", longitude); bundle.putString("latitude", latitude); uiIntent.putExtras(bundle); uiIntent.setAction("android.janmac.location"); context.sendBroadcast(uiIntent);** abortBroadcast(); } } } Boardcast B: it nest in an Activity. register: button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AppUtil.SendMessage(MainActivity.this); uiReceiver=new UIReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction("android.janmac.location"); registerReceiver(uiReceiver, filter); } }); extend: private class UIReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.v("location","uireceiver????!"); **Bundle bundle=new Bundle(); bundle=intent.getExtras(); herLongitude=Double.valueOf(bundle.getString("longitude")); herLatitude=Double.valueOf(bundle.getString("latitude"));** } } but the bundle couldn't get any values. here is log: 08-30 11:17:40.494: D/AndroidRuntime(2359): Shutting down VM 08-30 11:17:40.514: W/dalvikvm(2359): threadid=1: thread exiting with uncaught exception (group=0x40018560) 08-30 11:17:40.544: E/AndroidRuntime(2359): FATAL EXCEPTION: main 08-30 11:17:40.544: E/AndroidRuntime(2359): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.janmac.location (has extras) } in com.example.locationclient.MainActivity$UIReceiver@40513690 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:722) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.os.Handler.handleCallback(Handler.java:587) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.os.Handler.dispatchMessage(Handler.java:92) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.os.Looper.loop(Looper.java:130) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.app.ActivityThread.main(ActivityThread.java:3835) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.reflect.Method.invokeNative(Native Method) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.reflect.Method.invoke(Method.java:507) 08-30 11:17:40.544: E/AndroidRuntime(2359): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864) 08-30 11:17:40.544: E/AndroidRuntime(2359): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622) 08-30 11:17:40.544: E/AndroidRuntime(2359): at dalvik.system.NativeStart.main(Native Method) 08-30 11:17:40.544: E/AndroidRuntime(2359): Caused by: java.lang.NumberFormatException 08-30 11:17:40.544: E/AndroidRuntime(2359): at org.apache.harmony.luni.util.FloatingPointParser.parseDblImpl(Native Method) 08-30 11:17:40.544: E/AndroidRuntime(2359): at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:283) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.Double.parseDouble(Double.java:318) 08-30 11:17:40.544: E/AndroidRuntime(2359): at java.lang.Double.valueOf(Double.java:356) 08-30 11:17:40.544: E/AndroidRuntime(2359): at com.example.locationclient.MainActivity$UIReceiver.onReceive(MainActivity.java:231) 08-30 11:17:40.544: E/AndroidRuntime(2359): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709) 08-30 11:17:40.544: E/AndroidRuntime(2359): ... 9 more enter code here

    Read the article

  • Log call information whenever there is a call.

    - by linuxdoniv
    Hi, I have written the android application and I want the application to send the call information whenever there is an incoming call and it ends. This way I would be sending all calls to the server irrespective of size of the call log. Here is the code public class PhoneInfo extends BroadcastReceiver { private int incoming_call = 0; private Cursor c; Context context; public void onReceive(Context con, Intent intent) { c = con.getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE+ " DESC"); context = con; IncomingCallListener phoneListener=new IncomingCallListener(); TelephonyManager telephony = (TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE); } public class IncomingCallListener extends PhoneStateListener { public void onCallStateChanged(int state,String incomingNumber){ switch(state){ case TelephonyManager.CALL_STATE_IDLE: if(incoming_call == 1){ CollectSendCallInfo(); incoming_call = 0; } break; case TelephonyManager.CALL_STATE_OFFHOOK: break; case TelephonyManager.CALL_STATE_RINGING: incoming_call = 1; break; } } } private void CollectSendCallInfo() { int numberColumn = c.getColumnIndex( android.provider.CallLog.Calls.NUMBER); int dateColumn = c.getColumnIndex( android.provider.CallLog.Calls.DATE); int typeColumn = c.getColumnIndex( android.provider.CallLog.Calls.TYPE); int durationColumn=c.getColumnIndex( android.provider.CallLog.Calls.DURATION); ArrayList<String> callList = new ArrayList<String>(); try{ boolean moveToFirst=c.moveToFirst(); } catch(Exception e) { ; // could not move to the first row. return; } int row_count = c.getCount(); int loop_index = 0; int is_latest_call_read = 0; String callerPhonenumber = c.getString(numberColumn); int callDate = c.getInt(dateColumn); int callType = c.getInt(typeColumn); int duration=c.getInt(durationColumn); while((loop_index <row_count) && (is_latest_call_read != 1)){ switch(callType){ case android.provider.CallLog.Calls.INCOMING_TYPE: is_latest_call_read = 1; break; case android.provider.CallLog.Calls.MISSED_TYPE: break; case android.provider.CallLog.Calls.OUTGOING_TYPE: break; } loop_index++; c.moveToNext(); } SendCallInfo(callerPhonenumber, Integer.toString(duration), Integer.toString(callDate)); } private void SendCallInfo(String callerPhonenumber, String callDuration, String callDate) { JSONObject j = new JSONObject(); try { j.put("Caller", callerPhonenumber); j.put("Duration", callDuration); j.put("CallDate", callDate); } catch (JSONException e) { Toast.makeText(context, "Json object failure!", Toast.LENGTH_LONG).show(); } String url = "http://xxxxxx.xxx.xx/xxxx/xxx.php"; Map<String, String> kvPairs = new HashMap<String, String>(); kvPairs.put("phonecall", j.toString()); HttpResponse re; try { re = doPost(url, kvPairs); String temp; try { temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS") == 0) { ; } else ; } catch (ParseException e1) { Toast.makeText(context, "Parse Exception in response!", Toast.LENGTH_LONG) .show(); e1.printStackTrace(); } catch (IOException e1) { Toast.makeText(context, "Io exception in response!", Toast.LENGTH_LONG).show(); e1.printStackTrace(); } } catch (ClientProtocolException e1) { Toast.makeText(context, "Client Protocol Exception!", Toast.LENGTH_LONG).show(); e1.printStackTrace(); } catch (IOException e1) { Toast.makeText(context, "Client Protocol Io exception!", Toast.LENGTH_LONG).show(); e1.printStackTrace(); } } and here is the manifest file <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission> <uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"></uses-permission> <uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.READ_SMS"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Friend" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginInfo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.DEFAULT" /> </intent-filter> </activity> <service android:exported="true" android:enabled="true" android:name=".GeoUpdateService" > </service> <receiver android:name=".SmsInfo" > <intent-filter> <action android:name= "android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> <receiver android:name=".PhoneInfo" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE"></action> </intent-filter> </receiver> </application> The application just crashes when there is an incoming call.. i have been able to log the information about incoming SMS, but this call info logging is failing. Thanks for any help.

    Read the article

  • Log call information whenever there is a phone call.

    - by linuxdoniv
    Hi, I have written the android application and I want the application to send the call information whenever there is an incoming call and it ends. This way I would be sending all calls to the server irrespective of size of the call log. Here is the code public class PhoneInfo extends BroadcastReceiver { private int incoming_call = 0; private Cursor c; Context context; public void onReceive(Context con, Intent intent) { c = con.getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE+ " DESC"); context = con; IncomingCallListener phoneListener=new IncomingCallListener(); TelephonyManager telephony = (TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE); telephony.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE); } public class IncomingCallListener extends PhoneStateListener { public void onCallStateChanged(int state,String incomingNumber){ switch(state){ case TelephonyManager.CALL_STATE_IDLE: if(incoming_call == 1){ CollectSendCallInfo(); incoming_call = 0; } break; case TelephonyManager.CALL_STATE_OFFHOOK: break; case TelephonyManager.CALL_STATE_RINGING: incoming_call = 1; break; } } } private void CollectSendCallInfo() { int numberColumn = c.getColumnIndex( android.provider.CallLog.Calls.NUMBER); int dateColumn = c.getColumnIndex( android.provider.CallLog.Calls.DATE); int typeColumn = c.getColumnIndex( android.provider.CallLog.Calls.TYPE); int durationColumn=c.getColumnIndex( android.provider.CallLog.Calls.DURATION); ArrayList<String> callList = new ArrayList<String>(); try{ boolean moveToFirst=c.moveToFirst(); } catch(Exception e) { ; // could not move to the first row. return; } int row_count = c.getCount(); int loop_index = 0; int is_latest_call_read = 0; String callerPhonenumber = c.getString(numberColumn); int callDate = c.getInt(dateColumn); int callType = c.getInt(typeColumn); int duration=c.getInt(durationColumn); while((loop_index <row_count) && (is_latest_call_read != 1)){ switch(callType){ case android.provider.CallLog.Calls.INCOMING_TYPE: is_latest_call_read = 1; break; case android.provider.CallLog.Calls.MISSED_TYPE: break; case android.provider.CallLog.Calls.OUTGOING_TYPE: break; } loop_index++; c.moveToNext(); } SendCallInfo(callerPhonenumber, Integer.toString(duration), Integer.toString(callDate)); } private void SendCallInfo(String callerPhonenumber, String callDuration, String callDate) { JSONObject j = new JSONObject(); try { j.put("Caller", callerPhonenumber); j.put("Duration", callDuration); j.put("CallDate", callDate); } catch (JSONException e) { Toast.makeText(context, "Json object failure!", Toast.LENGTH_LONG).show(); } String url = "http://xxxxxx.xxx.xx/xxxx/xxx.php"; Map<String, String> kvPairs = new HashMap<String, String>(); kvPairs.put("phonecall", j.toString()); HttpResponse re; try { re = doPost(url, kvPairs); String temp; try { temp = EntityUtils.toString(re.getEntity()); if (temp.compareTo("SUCCESS") == 0) { ; } else ; } catch (ParseException e1) { Toast.makeText(context, "Parse Exception in response!", Toast.LENGTH_LONG) .show(); e1.printStackTrace(); } catch (IOException e1) { Toast.makeText(context, "Io exception in response!", Toast.LENGTH_LONG).show(); e1.printStackTrace(); } } catch (ClientProtocolException e1) { Toast.makeText(context, "Client Protocol Exception!", Toast.LENGTH_LONG).show(); e1.printStackTrace(); } catch (IOException e1) { Toast.makeText(context, "Client Protocol Io exception!", Toast.LENGTH_LONG).show(); e1.printStackTrace(); } } and here is the manifest file <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission> <uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"></uses-permission> <uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> <uses-permission android:name="android.permission.READ_SMS"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Friend" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginInfo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.DEFAULT" /> </intent-filter> </activity> <service android:exported="true" android:enabled="true" android:name=".GeoUpdateService" > </service> <receiver android:name=".SmsInfo" > <intent-filter> <action android:name= "android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> <receiver android:name=".PhoneInfo" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE"></action> </intent-filter> </receiver> </application> The application just crashes when there is an incoming call.. i have been able to log the information about incoming SMS, but this call info logging is failing. Thanks for any help.

    Read the article

< Previous Page | 1 2 3 4