Search Results

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

Page 1/4 | 1 2 3 4  | Next Page >

  • Inform Activity from a BroadcastReceiver ONLY if it is in the foreground

    - by Zordid
    Hi there! Maybe it's easy, but I couldn't really figure this out right so far... I got a BroadcastReceiver waiting to get triggered by the AlarmMangager - this works fine. Now: because the event, if it occurs, needs to refresh some elements on screen of the main Activity, I would like to send an Intent from that background BroadcastReceiver to my Activity - but only if it is currently in the foreground, aka active. If it is not running or not visible, I don't care - and the last thing I want to do is start the Activity by my intent! I handle repainting of the views in my onResume method, so I don't care at all. Any hints on how to do that? Thanks! EDIT: my BroadcastReceiver is waiting for alarms that must be notified to the user. So, it must be there and declared in the manifest. The problem is: it will have to decide whether the mentioned Activity is currently up in front or not.

    Read the article

  • BroadcastReceiver not triggered by Alarm

    - by Ezekiel Buchheit
    I am trying to set up an alarm that will run in the background and trigger (eventually) a save event. At the moment I simply have this code attached to a button. Press the button and the alarm should start leaving Toast messages behind as an indication that it is functioning. At the moment everything runs except the onReceive in the BroadcastReceiver is never triggered. Here is my code: The class setting up the alarm: //FIXME - rename (ie BackgroundSave; more descriptive) public class AlarmReceiver extends Service{ //FIXME - make sure you kill the service public void onCreate() { super.onCreate(); Toast.makeText(getApplication().getApplicationContext(), "Service onCreate called", Toast.LENGTH_SHORT).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(getApplication().getApplicationContext(), "Service started", Toast.LENGTH_SHORT).show(); setAlarm(AlarmReceiver.this); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } public void setAlarm(Context c) { AlarmManager alarmManager = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(c, Alarm.class); PendingIntent pi = PendingIntent.getBroadcast(c, 0, i, 0); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 1000, 1000, pi); Toast.makeText(c.getApplicationContext(), "setAlarm called", Toast.LENGTH_SHORT).show(); } public void cancelAlarm(Context context) { Intent intent = new Intent(context, Alarm.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } } Here is the BroadcastReceiver: public class Alarm extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Alarm", Toast.LENGTH_SHORT).show(); } } And here is my manifest: <!-- Alarm --> <service android:name="com.xxxx.android.tools.AlarmReceiver" android:enabled="true" /> <receiver android:name="com.xxxx.android.tools.Alarm" ></receiver> The alarm onReceive is never triggered.

    Read the article

  • Android - BroadcastReceiver CONNECTIVITY ACTION

    - by Marc Ortiz
    in my project there's a service that listens for changes in the connectivity. When wifi is switched off to on then it gets called. The problem it's that i'm using a fragment and inside a fragment there's a button with the setonclicklistener(); and onclick(); SOMETIMES when i touch the button then the service receives an intent that the connectivity has changed (the method gets called without any reason...). Here's the code of my fragment activity for the viewpager layout: public static class FragmentSelection extends Fragment { int mNum; static FragmentSelection newInstance(int num) { FragmentSelection f = new FragmentSelection(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } /** * When creating, retrieve this instance's number from its arguments. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = (getArguments() != null ? getArguments().getInt("num") : 1) + 1; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.fragment_intro_contenido, container, false); Button btStart = (Button) v.findViewById(R.id.btChanged); final CheckBox cbSMS = (CheckBox) v.findViewById(R.id.checkBoxSms); final CheckBox cbCalls = (CheckBox) v .findViewById(R.id.checkBoxLlamadas); final CheckBox cbApps = (CheckBox) v .findViewById(R.id.checkBoxApps); final CheckBox cbPosition = (CheckBox) v .findViewById(R.id.checkBoxPosicion); final CheckBox cbContacts = (CheckBox) v .findViewById(R.id.checkBoxContactos); final CheckBox cbAll = (CheckBox) v.findViewById(R.id.checkBoxAll); cbSMS.setChecked(true); cbCalls.setChecked(true); cbApps.setChecked(true); cbPosition.setChecked(true); cbContacts.setChecked(true); cbAll.setChecked(true); btStart.setOnClickListener(new View.OnClickListener() { public void onClick(View c) { Intent i = new Intent(); i.setClass(v.getContext(), AnonymeActivity.class); if (!cbSMS.isChecked()) { i.putExtra("sms", 0); } else { i.putExtra("sms", 1); } if (!cbCalls.isChecked()) { i.putExtra("calls", 0); } else { i.putExtra("calls", 1); } if (cbContacts.isChecked()) { i.putExtra("contacts", 1); } else { i.putExtra("contacts", 0); } if (cbApps.isChecked()) { i.putExtra("apps", 1); } else { i.putExtra("apps", 0); } if (!cbPosition.isChecked()) { i.putExtra("gps", 0); } else { i.putExtra("gps", 1); } if (!cbAll.isChecked()) { if (cbSMS.isChecked() && cbCalls.isChecked() && cbContacts.isChecked() && cbApps.isChecked() && cbPosition.isChecked()) { i.putExtra("all", 1); } else { i.putExtra("all", 0); } } else { i.putExtra("all", 1); } startActivity(i); } }); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } } My BroadcastReceiver class: class Broadcast_Reciver extends BroadcastReceiver implements Variables { CheckConexion cc; @Override public void onReceive(Context contxt, Intent intent) { // Cuando hay un evento, lo diferenciamos y hacemos una acción. if (intent.getAction().equals(SMS_RECEIVED)) { Sms sms = new Sms(null, contxt); sms.uploadNewSms(intent); } else if (intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) { // st.batterylow(contxt); } else if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) { // st.power(1, contxt); } else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) { // st.power(0, contxt); } else if (intent.getAction().equals(Intent.ACTION_CALL_BUTTON)) { // Notify } else if (intent.getAction().equals(Intent.ACTION_CAMERA_BUTTON)) { // Notify } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) || intent.getAction().equals(Intent.ACTION_PACKAGE_CHANGED) || intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) { Database db = new Database(contxt); if (db.open().Preferences(4)) { Uri data = intent.getData(); new ListApps(contxt).import_app(intent, contxt, data, intent.getAction()); } db.close(); } else if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { cc = new CheckConexion(contxt); if (cc.isOnline()) { Database db = new Database(contxt); if (db.open().move() == 1) { new UploadOffline(contxt); } db.close(); } } } } And the errors: 9-03 23:20:37.887: E/SqliteDatabaseCpp(2715): CREATE TABLE android_metadata failed 09-03 23:20:37.887: E/SQLiteDatabase(2715): Failed to open the database. closing it. 09-03 23:20:37.887: E/SQLiteDatabase(2715): android.database.sqlite.SQLiteDatabaseLockedException: database is locked 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteDatabase.setLocale_(SQLiteDatabase.java:2211) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteDatabase.setLocale(SQLiteDatabase.java:2199) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1130) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1081) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1167) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:833) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:157) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at com.background.Database.open(Database.java:127) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at <b><b><b><h3>com.background.Broadcast_Reciver.onReceive(BroadcastService.java:100)</h3> 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.os.Handler.handleCallback(Handler.java:605) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.os.Handler.dispatchMessage(Handler.java:92) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.os.Looper.loop(Looper.java:137) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at android.app.ActivityThread.main(ActivityThread.java:4507) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at java.lang.reflect.Method.invokeNative(Native Method) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at java.lang.reflect.Method.invoke(Method.java:511) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 09-03 23:20:37.887: E/SQLiteDatabase(2715): at dalvik.system.NativeStart.main(Native Method) 09-03 23:20:37.887: D/AndroidRuntime(2715): Shutting down VM 09-03 23:20:37.887: W/dalvikvm(2715): threadid=1: thread exiting with uncaught exception (group=0x40c3b1f8) 09-03 23:20:37.902: E/AndroidRuntime(2715): FATAL EXCEPTION: main 09-03 23:20:37.902: E/AndroidRuntime(2715): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x10000010 (has extras) } in com.background.Broadcast_Reciver@415203f8 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:737) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.os.Handler.handleCallback(Handler.java:605) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.os.Handler.dispatchMessage(Handler.java:92) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.os.Looper.loop(Looper.java:137) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.app.ActivityThread.main(ActivityThread.java:4507) 09-03 23:20:37.902: E/AndroidRuntime(2715): at java.lang.reflect.Method.invokeNative(Native Method) 09-03 23:20:37.902: E/AndroidRuntime(2715): at java.lang.reflect.Method.invoke(Method.java:511) 09-03 23:20:37.902: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 09-03 23:20:37.902: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 09-03 23:20:37.902: E/AndroidRuntime(2715): at dalvik.system.NativeStart.main(Native Method) 09-03 23:20:37.902: E/AndroidRuntime(2715): Caused by: android.database.sqlite.SQLiteDatabaseLockedException: database is locked 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteDatabase.setLocale_(SQLiteDatabase.java:2211) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteDatabase.setLocale(SQLiteDatabase.java:2199) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1130) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1081) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1167) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:833) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:157) 09-03 23:20:37.902: E/AndroidRuntime(2715): at com.background.Database.open(Database.java:127) 09-03 23:20:37.902: E/AndroidRuntime(2715): at com.background.Broadcast_Reciver.onReceive(BroadcastService.java:100) 09-03 23:20:37.902: E/AndroidRuntime(2715): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728) 09-03 23:20:37.902: E/AndroidRuntime(2715): ... 9 more Checkout that the program goes into BroadcastReceiver class and i don't understand why!

    Read the article

  • How do I pass data from a BroadcastReceiver through to an Activity being started?

    - by Tom Hume
    I've got an Android application which needs to be woken up sporadically throughout the day. To do this, I'm using the AlarmManager to set up a PendingIntent and have this trigger a BroadcastReceiver. This BroadcastReceiver then starts an Activity to bring the UI to the foreground. All of the above seems to work, in that the Activity launches itself correctly; but I'd like the BroadcastReceiver to notify the Activity that it was started by the alarm (as opposed to being started by the user). To do this I'm trying, from the onReceive() method of the BroadcastReceiver to set a variable in the extras bundle of the intent, thus: Intent i = new Intent(context, MyActivity.class); i.putExtra(wakeupKey, true); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); In the onResume() method of my Activity, I then look for the existence of this boolean variable: protected void onResume() { super.onResume(); String wakeupKey = "blah"; if (getIntent()!=null && getIntent().getExtras()!=null) Log.d("app", "onResume at " + System.currentTimeMillis() + ":" + getIntent().getExtras().getBoolean(wakeupKey)); else Log.d("app", "onResume at " + System.currentTimeMillis() + ": null"); } The getIntent().getExtras() call in onResume() always returns null - I don't seem to be able to pass any extras through at all in this bundle. If I use the same method to bind extras to the PendingIntent which triggers the BroadcastReceiver however, the extras come through just fine. Can anyone tell me what's different about passing a bundle from a BroadcastReceiver to an Activity, as opposed to passing the bundle from an Activity to a BroadcastReceiver? I fear I may be doing something very very obvious wrong here...

    Read the article

  • BroadcastReceiver not reading stored value from SharedPreferences

    - by bobby123
    In my app I have a broadcast receiver that turns on GPS upon receiving a set string of text. In the onLocationChanged method, I want to pass the GPS data and a value from my shared preferences to a thread in a string. I have the thread writing to log and can see all the GPS values in the string but the last value from my shared preferences is just showing up as 'prefPhoneNum' which I initialised the string to at the beginning of the receiver class. I have the same code to read the prefPhoneNum from shared preferences in the main class and it works there, can anyone see what I might be doing wrong? public class SmsReceiver extends BroadcastReceiver implements LocationListener { LocationManager lm; LocationListener loc; public SharedPreferences sharedpreferences; public static final String US = "usersettings"; public String prefPhoneNum = "prefPhoneNum"; @Override public void onReceive(Context context, Intent intent) { sharedpreferences = context.getSharedPreferences(US, Context.MODE_PRIVATE); prefPhoneNum = sharedpreferences.getString("prefPhoneNum" , ""); lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); loc = new SmsReceiver(); //---get the SMS message passed in--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null) { //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += msgs[i].getMessageBody().toString() + "\n"; } Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); //Display SMS if ((msgs[0].getMessageBody().toString().equals("Enable")) || (msgs[0].getMessageBody().toString().equals("enable"))) { enableGPS(); } else { /* Do Nothing*/ } } } public void enableGPS() { //new CountDownTimer(10000, 1000) { //10 seconds new CountDownTimer(300000, 1000) { //300 secs = 5 mins public void onTick(long millisUntilFinished) { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loc); } public void onFinish() { lm.removeUpdates(loc); } }.start(); } @Override public void onLocationChanged(Location location) { String s = ""; s += location.getLatitude() + "\n"; s += location.getLongitude() + "\n"; s += location.getAltitude() + "\n"; s += location.getAccuracy() + "\n" + prefPhoneNum; Thread cThread = new Thread(new SocketsClient(s)); cThread.start(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } } Here is the logcat for when the application shuts - D/LocationManager( 3912): requestLocationUpdates: provider = gps, listener = accel.working.TrackGPS@4628bce0 D/GpsLocationProvider( 96): setMinTime 0 D/GpsLocationProvider( 96): startNavigating D/GpsLocationProvider( 96): TTFF: 3227 D/AndroidRuntime( 3912): Shutting down VM W/dalvikvm( 3912): threadid=1: thread exiting with uncaught exception (group=0x400259f8) E/AndroidRuntime( 3912): FATAL EXCEPTION: main E/AndroidRuntime( 3912): java.lang.NullPointerException E/AndroidRuntime( 3912): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146) E/AndroidRuntime( 3912): at accel.working.TrackGPS.onLocationChanged(TrackGPS.java:63) E/AndroidRuntime( 3912): at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:191) E/AndroidRuntime( 3912): at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:124) E/AndroidRuntime( 3912): at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:140) E/AndroidRuntime( 3912): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime( 3912): at android.os.Looper.loop(Looper.java:144) E/AndroidRuntime( 3912): at android.app.ActivityThread.main(ActivityThread.java:4937) E/AndroidRuntime( 3912): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 3912): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime( 3912): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) E/AndroidRuntime( 3912): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) E/AndroidRuntime( 3912): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • Broadcastreceiver to obtain ServiceState information

    - by Andrew
    Hi, Does anyone know of a way to obtain the phone service state (IN_SERVICE, OUT_OF_SERVICE, EMERGENCY_ONLY, POWER_OFF) in android. I was hoping there would be a broadcastreciever to identify the changes, but I can't find anything. I know there's a listener but I'm not sure how I would use that from my app as it runs as a service using a WakefulIntentService (by thecommonsguy). With something like battery level (ie BATTERY_LOW, BATTERY_OKAY) it's quite easy, but I just can't work out a similar things for phone service changes.

    Read the article

  • Null Pointer Exception in my BroadcastReceiver class

    - by user1760007
    I want to search a db and toast a specific column on the startup of the phone. The app keeps crashing and getting an exception even though I feel as the code is correct. @Override public void onReceive(Context ctx, Intent intent) { Log.d("omg", "1"); DBAdapter do = new DBAdapter(ctx); Log.d("omg", "2"); Cursor cursor = do.fetchAllItems(); Log.d("omg", "3"); if (cursor.moveToFirst()) { Log.d("omg", "4"); do { Log.d("omg", "5"); String title = cursor.getString(cursor.getColumnIndex("item")); Log.d("omg", "6"); // i = cursor.getInt(cursor.getColumnIndex("id")); Toast.makeText(ctx, title, Toast.LENGTH_LONG).show(); } while (cursor.moveToNext()); } cursor.close(); } The frustrating part is that I don't see any of my "omg" logs show up in logcat. I only see when my application crashes. I get three lines of errors in logcat. 10-19 12:31:11.656: E/AndroidRuntime(1471): java.lang.RuntimeException: Unable to start receiver com.test.toaster.MyReciever: java.lang.NullPointerException 10-19 12:31:11.656: E/AndroidRuntime(1471): at com.test.toaster.DBAdapter.fetchAllItems(DBAdapter.java:96) 10-19 12:31:11.656: E/AndroidRuntime(1471): at com.test.toaster.MyReciever.onReceive(MyReciever.java:26) For anyone interested, here is my DBAdapter fetchAllItems code: public Cursor fetchAllItems() { return mDb.query(DATABASE_TABLE, new String[] { KEY_ITEM, KEY_PRIORITY, KEY_ROWID }, null, null, null, null, null); }

    Read the article

  • How can I send Data from BroadcastReceiver to Widget?

    - by Yverman
    I have a BroadcastReceiver which loads data from the Internet and then it should send them back to a Widget. But how can I do this? What I've already done is updating the Widget directly from the Broadcast, but I like to just send de data back. public class UpdateManager extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); ComponentName thisWidget = new ComponentName(context, Widget.class); remoteViews.setTextViewText(R.id.widget_textview, "UPDATE DONE"); appWidgetManager.updateAppWidget(thisWidget, remoteViews); } }

    Read the article

  • BroadcastReceiver not receiving an alarm's broadcast

    - by juanjux
    I have a code that sets a new repeating alarm (on production I'll use a inexactRepeating), but the BroadCastReceiver I've registered for handling it is not being called. Here is the code where I set the alarm: newAlarmPeriod = 5000; // For debugging Intent alarmIntent = new Intent(this, GroupsCheckAlarmReceiver.class); PendingIntent sender = PendingIntent.getBroadcast(this, Constants.CHECK_ALARM_CODE, alarmIntent, 0); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + newAlarmPeriod, newAlarmPeriod, sender); It seems to work and it triggers and alarm every five seconds, as seen in the output of "adb shell dumpsys alarm": DUMP OF SERVICE alarm: Current Alarm Manager state: Realtime wakeup (now=1269941046923): RTC_WAKEUP #1: Alarm{43cbac58 type 0 android} type=0 when=1269997200000 repeatInterval=0 count=0 operation=PendingIntent{43bb1738: PendingIntentRecord{43bb1248 android broadcastIntent}} RTC_WAKEUP #0: Alarm{43ce30e0 type 0 com.almarsoft.GroundhogReader} type=0 when=1269941049555 repeatInterval=5000 count=1 operation=PendingIntent{43d990c8: PendingIntentRecord{43d49108 com.almarsoft.GroundhogReader broadcastIntent}} RTC #1: Alarm{43bfc250 type 1 android} type=1 when=1269993600000 repeatInterval=0 count=0 operation=PendingIntent{43c5a618: PendingIntentRecord{43c4f048 android broadcastIntent}} RTC #0: Alarm{43d67dd8 type 1 android} type=1 when=1269941100000 repeatInterval=0 count=0 operation=PendingIntent{43c4e0f0: PendingIntentRecord{43c4f6c8 android broadcastIntent}} Broadcast ref count: 0 Alarm Stats: android 24390ms running, 0 wakeups 80 alarms: act=android.intent.action.TIME_TICK flg=0x40000004 com.almarsoft.GroundhogReader 26ms running, 2 wakeups 2 alarms: flg=0x4 cmp=com.almarsoft.GroundhogReader/.GroupsCheckAlarmReceiver But for some reason my BroadCastReceiver is not being called when the alarm is triggered. I've declared it on the Manifest: <receiver android:name=".GroupsCheckAlarmReceiver" /> And this is the abbreviated code: public class GroupsCheckAlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "XXX Alarm worked.", Toast.LENGTH_LONG).show(); Log.d("XXX", "GroupsCheckAlarmReceiver.onReceive"); }

    Read the article

  • calling background service from BroadcastReceiver....

    - by Shalini Singh
    Hi , i am trying to call a push notification background from BroadcastReceiver class.but my application is going to crash the code is given bellow public class AlarmReceiver extends BroadcastReceiver { Context ctx; static int count=1; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub //Toast.makeText(context, "working"+count, Toast.LENGTH_LONG).show(); count++; Log.e("broadcast***","receiver"); Intent myIntent=new Intent(context,NotifyService.class); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(myIntent); } } * manifest entry:- <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> Error: 05-24 15:17:00.042: ERROR/AndroidRuntime(424): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.android.alarm/com.android.alarm.NotifyService}; have you declared this activity in your AndroidManifest.xml? Please help me....

    Read the article

  • How to access a TextView element in a BroadcastReceiver

    - by ric03uec
    Hello, I am testing a simple widget in android and using Alarms to update a TextView at regular intervals. The problem is that in the BroadcastReceiver class I cannot access the TextView element, which I want to get updated when the alarm expires. The class is being called properly because the Toast i have put there is giving the appropriate message. The following code is from the class where I configure the widget and set the timers. public void onCreate(Bundle bundle) { super.onCreate(bundle); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if(extras != null){ mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(WidgetConfigure.this); RemoteViews views = new RemoteViews(WidgetConfigure.this.getPackageName(), R.layout.widget_layout); views.setTextViewText(R.id.quote, "Widget Loaded From Activity"); appWidgetManager.updateAppWidget(mWidgetId, views); setTimer(); //set the timers... setResult();// set the result... } } Now i want to update the same TextView when the BroadCastReceiver is called after the timer expires. I have tried the code provided in the ExampleAppWidget example provided in android api demos and that isnt working out. How can i set the required text? Thankx in advance

    Read the article

  • Running Send_SMS method from BroadcastReceiver

    - by burmat
    My application is an auto-reply application for text messages. I have a BroadcastReceiver for when a message arrives, and I need it to run a public method (Send_SMS). SMS_Sender.sendSMS(phoneNumber, messageText); does not work however, and eclipse wants to change my method to static. This would not be an issue if I did not have more receivers that catch when the message is sent/delivered/etc in this class. These receivers are then errors for being contained in a static method. So my question is, how do I run this method from a broadcast receiver so I can send the auto reply whenever it is triggered with a received message? -Thank you in advance, Nate

    Read the article

  • Android: A Toast when OutComing call

    - by Skatephone
    Hi, i'm trying this code found on internet...it should show a toast for OutComing call event using a BroadcastReceiver but on my htc tattoo with Android 1.6 it doesn't works (it don't show any toast) public class HFBroadcastOutComingRecevier extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Phone Event", Toast.LENGTH_SHORT).show(); Bundle bundle = intent.getExtras(); if(null == bundle) return; String phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); String info = "Detect Calls sample application\nOutgoing number: " + phonenumber; Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } } Naturally i've registered the BroadcastReceiver on my Manifest as: and with this permissions: <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/> Any idea?

    Read the article

  • Android - Start service on boot

    - by Gady
    From everything I've seen on Stack Exchange and elsewhere, I have everything set up correctly to start an IntentService when Android OS boots. Unfortunately it is not starting on boot, and I'm not getting any errors. Maybe the experts can help... Manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.phx.batterylogger" android:versionCode="1" android:versionName="1.0" android:installLocation="internalOnly"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.BATTERY_STATS" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <service android:name=".BatteryLogger"/> <receiver android:name=".StartupIntentReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> </manifest> BroadcastReceiver for Startup: package com.phx.batterylogger; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class StartupIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent serviceIntent = new Intent(context, BatteryLogger.class); context.startService(serviceIntent); } } UPDATE: I tried just about all of the suggestions below, and I added logging such as Log.v("BatteryLogger", "Got to onReceive, about to start service"); to the onReceive handler of the StartupIntentReceiver, and nothing is ever logged. So it isn't even making it to the BroadcastReceiver. I think I'm deploying the APK and testing correctly, just running Debug in Eclipse and the console says it successfully installs it to my Xoom tablet at \BatteryLogger\bin\BatteryLogger.apk. Then to test, I reboot the tablet and then look at the logs in DDMS and check the Running Services in the OS settings. Does this all sound correct, or am I missing something? Again, any help is much appreciated.

    Read the article

  • android.intent.action.SCREEN_ON doesn't work as a receiver intent filter

    - by Jim Blackler
    I'm trying to get a BroadcastReceiver invoked when the screen is turned on. In my AndroidManifest.xml I have specified : <receiver android:name="IntentReceiver"> <intent-filter> <action android:name="android.intent.action.SCREEN_ON"></action> </intent-filter> </receiver> However it seems the receiver is never invoked (breakpoints don't fire, log statements ignored). I've swapped out SCREEN_ON for BOOT_COMPLETED for a test, and this does get invoked. This is in a 1.6 (SDK level 4) project. A Google Code Search revealed this, I downloaded the project and synced it, converted it to work with latest tools, but it too is not able to intercept that event. http://www.google.com/codesearch/p?hl=en#_8L9bayv7qE/trunk/phxandroid-intent-query/AndroidManifest.xml&q=android.intent.action.SCREEN_ON Is this perhaps no longer supported? Previously I have been able to intercept this event successfully with a call to Context.registerReceiver() like so registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // ... } }, new IntentFilter(Intent.ACTION_SCREEN_ON)); However this was performed by a long-living Service. Following sage advice from CommonsWare I have elected to try to remove the long-living Service and use different techniques. But I still need to detect the screen off and on events.

    Read the article

  • Android - sendOrderedBroadcast help

    - by Donal Rafferty
    I am trying to use a sendOrderedBroadcast in my Android app. I want to be able to send the Intent from one of my applications to another and I then want to get data back from the Application that recieves the Intent, in this case a boolean true or false. Here is the current code: Intent i = new Intent(); i.setAction(GlobalData.PROPOSE_IN_DOMAIN_ROAM_INTENT); i.putExtra("com.testnetworks.QCLEVEL", aProposedTheoreticalQoSLevel); sendOrderedBroadcast(i, null, null, null, Activity.RESULT_OK, null, null); Is this the correct way to achieve what I want? If so what do I use as the resultReceiver* parameter? (3rd parameter) And then how to I recieve data back from the Broadcast? I have done a quick google and not come up with any examples, any help or examples greatly appreciated. UPDATED CODE: sendOrderedBroadcast(i, null, domainBroadcast, null, Activity.RESULT_OK, null, null); class DomainBroadcast extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent intent) { String action = intent.getAction(); if(GlobalData.PROPOSE_IN_DOMAIN_ROAM_INTENT.equals(action)){ Log.d("BROADCAST", "Returning broadcast"); Bundle b = intent.getExtras(); Log.d("BROADCAST", "Returning broadcast " + b.getInt("com.testnetworks.INT_TEST")); } } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(GlobalData.PROPOSE_IN_DOMAIN_ROAM_INTENT.equals(action)){ Bundle b = intent.getExtras(); int testQCLevel = b.getInt("com.testnetworks.QCLEVEL"); switch(testQCLevel){ case 1: Log.d("QCLevel ", "QCLevel = UNAVAILABLE"); break; case 2: Log.d("QCLevel ", "QCLevel = BELOWUSABILITY"); break; case 3: Log.d("QCLevel ", "QCLevel = VOICE"); break; } intent.putExtra("com.testnetworks.INT_TEST", 100); } So according to the Doc's I should recieve 100 back in my DomainBroadcast reciever but it always comes back as 0. Can anyone see why? *resultReceiver - Your own BroadcastReceiver to treat as the final receiver of the broadcast.

    Read the article

  • How to receive sms from a special phone number?

    - by Pariya
    I wrote a send and receive sms in android successfully. I want my program to be able to receive sms from a special number("+9856874236"). But, if the SMS is from any other number, it should go to the phone's message inbox and not to my application. import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.util.Log; public class SmsReceiver extends BroadcastReceiver { public String str = ""; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object messages[] = (Object[]) bundle.get("pdus"); SmsMessage[] msgs = null; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage smsMessage[] = new SmsMessage[messages.length]; String msg_from=""; for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); msg_from += msgs[n].getOriginatingAddress(); } String receivedMessage = smsMessage[0].getMessageBody().toString().toUpperCase(); if(msg_from .equals("+989124236870")) { for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]); str += "SMS from " + msgs[n].getOriginatingAddress(); str += " :"; //str += "sms az shomare makhsus"; str += msgs[n].getMessageBody().toString(); str += "\n"; abortBroadcast(); } Intent act = new Intent(context, MainActivity.class); act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); act.putExtra("message", str); context.startActivity(act); } } } }

    Read the article

  • Scheduling a recurring alarm/event

    - by martinjd
    I have a class that extends Application. In the class I make a call to AlarmManager and pass in an intent. As scheduled my EventReceiver class, that extends BroadcastReceiver, processes the call in the onReceive method. How would I call the intent again from the onReceive method to schedule another event?

    Read the article

  • Broadcast receiver, check status, turning off connection with F8

    - by yoann
    I am using eclipse with android sdk 3.2 I have some problems to make my broadcast receiver working when the connection is lost. first I have checked the type of network to make sure I understand well : ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); boolean is3g = manager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE) .isConnectedOrConnecting(); boolean isWifi = manager.getNetworkInfo( ConnectivityManager.TYPE_WIFI) .isConnectedOrConnecting(); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null) Toast.makeText(getApplicationContext(), info.getTypeName(), Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "Pas de connexion", Toast.LENGTH_LONG).show(); if (!is3g) Log.i("Network Listener", "DISCONNECTED"); else Log.i("Network Listener", "CONNECTED"); == this is a mobile network, I'm connected Then I press F8 or I make : telnet localhost 5554 gsm data off to stop the connection Here is my dynamic broadcast receiver in an activity : public class ActivityA extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.query); this.registerReceiver(this.networkStateReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); } BroadcastReceiver networkStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); //i have tried several things : State networkState = networkInfo.getState(); // if (networkState.compareTo(State.DISCONNECTED) == 0) ... if (networkInfo != null && networkInfo.isConnected()) { Toast.makeText(getApplicationContext(), "CONNECTED", Toast.LENGTH_LONG).show(); Log.i("Network Listener", "Connected"); } else { Toast.makeText(getApplicationContext(), "DISCONNECTED", Toast.LENGTH_LONG).show(); Log.i("Network Listener", "Network Type Changed"); Intent offline = new Intent(AccountInfoActivity.this, OfflineWorkService.class); startService(offline); } }; My manifest : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> The problem is : when the activityA is launched, my broadcast receive something and it displays "Connected"(Log) and my toast. When I turn off the connection manually, nothing happend. My service is not started, log message are not displayed, only toast messages work ... And even better, when I turn on the connection again (by pressing F8), I test again the type of connection, Toast messages are shown but this time Log messages don't work. Problems happend when I press F8. Anyway, I think I miss something with broadcast receivers, it's not totally clear. Please help me.

    Read the article

  • Displaying a notification when bluetooth is disconnected - Android

    - by Ryan T
    I am trying to create a program that will display a notification to the user if a Blue tooth device suddenly comes out of range from my Android device. I currently have the following code but no notification is displayed. I was wondering if it was possible I shouldn't use ACTION_ACL_DISCONNECTED because I believe the bluetooth stack would be expecting packets that state a disconnect is requested. My requirements state that the bluetooth device will disconnect without warning. Thank you for any assistance! BluetoothNotification.java: //This is where the notification is created. import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; public class BluetoothNotification extends Activity { public static final int NOTIFICATION_ID = 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** Define configuration for our notification */ int icon = R.drawable.logo; CharSequence tickerText = "This is a sample notification"; long when = System.currentTimeMillis(); Context context = getApplicationContext(); CharSequence contentTitle = "Sample notification"; CharSequence contentText = "This notification has been generated as a result of BT Disconnecting"; Intent notificationIntent = new Intent(this, BluetoothNotification.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); /** Initialize the Notification using the above configuration */ final Notification notification = new Notification(icon, tickerText, when); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); /** Retrieve reference from NotificationManager */ String ns = Context.NOTIFICATION_SERVICE; final NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); mNotificationManager.notify(NOTIFICATION_ID, notification); finish(); } } Snippet from OnCreate: //Located in Controls.java IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); this.registerReceiver(mReceiver, filter1); Snippet from Controls.java: private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { //Device has disconnected NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); } } };

    Read the article

  • Startup Broadcast Receiver Not Running At Startup

    - by comead
    I have a class StartupReceiver: public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent service = new Intent(context, ARMRService.class); context.startService(service); } and it is declared in my Manifest.xml as <receiver android:name=".StartupReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> and I have given the correct permission: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> Why is this not working???

    Read the article

  • Why do AlarmManager broadcasts get cancelled when app gets killed?

    - by skooter
    Ok so I have two BroadcastReceiver registered. When the app is closed they both fire at the appropriate times and do the appropriate things. If the app is closed then killed (say with an AppKiller), the receivers never receive their broadcasts, and nothing happens. Presumably the same thing happens if the parent app is killed due to low memory, so how do I ensure those broadcasts are fired/received. The API states that even if the app is killed it should fire, does anyone else have experience with this situation? If it helps my manifest is: <!-- receivers for AlarmManager --> <receiver android:exported="true" android:label="Shift roster updating calendar." android:name="com.skooter.shiftroster.backend.service.UpdateCalendar" > </receiver> <receiver android:exported="true" android:label="Shift roster checking alarm." android:name="com.skooter.shiftroster.backend.service.SetWakeup" > </receiver> and nothing esoteric is going on in the AlarmManager/BroadcastReceivers

    Read the article

  • ACTION_MY_PACKAGE_REPLACED not received

    - by Ton
    I am using ACTION_MY_PACKAGE_REPLACED to receive when my app is updated or resinstalled. My problem is that the event is never triggered (I tried Eclipse and real device). This is what I do: Manifest: <receiver android:name=".MyEventReceiver" > <intent-filter android:priority="1000" > <action android:name="android.intent.action.ACTION_MY_PACKAGE_REPLACED" /> </intent-filter> </receiver> Code: public class MyEventReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.ACTION_MY_PACKAGE_REPLACED".equals(intent.getAction())) { //Restart services } } } This code is simple, in real one I used other events like BOOT_COMPLETED and others, and they work but ACTION_MY_PACKAGE_REPLACED. Thanks.

    Read the article

  • Network Data Packet connectivity intent

    - by Rakesh
    I am writing an Android application which can enable and disable the Network Data packet connection. I am also using one broadcast receiver to check the Network Data packet connection. I have registered broadcast receiver and provided required permission in Manifest file. But when I run this application it changes the connection state and after that it crashes. But when I don't include this broadcast receiver it works fine. I am not able to see any kind of log which can provide some clue. Here is my code for broadcast receiver. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rakesh.simplewidget" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <!-- Permissions --> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".SimpleWidgetExampleActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- <receiver android:name=".ExampleAppWidgetProvider" android:label="Widget ErrorBuster" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget1_info" /> </receiver> --> <receiver android:name=".ConnectivityReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest> My Broadcast receiver class is as following. import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; public class ConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NetworkInfo info = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if(info.getType() == ConnectivityManager.TYPE_MOBILE){ if(info.isConnectedOrConnecting()){ Log.e("RK","Mobile data is connected"); }else{ Log.e("RK","Mobile data is disconnected"); } } } } my Main activity file. package com.rakesh.simplewidget; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; public class SimpleWidgetExampleActivity extends Activity { private Button btNetworkSetting; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btNetworkSetting = (Button)findViewById(R.id.btNetworkSetting); if(checkConnectivityState(getApplicationContext())){ btNetworkSetting.setBackgroundColor(Color.GREEN); }else{ btNetworkSetting.setBackgroundColor(Color.GRAY); } } public void openNetworkSetting(View view){ Method dataConnSwitchmethod; Class telephonyManagerClass; Object ITelephonyStub; Class ITelephonyClass; Context context = view.getContext(); boolean enabled = !checkConnectivityState(context); final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); try{ final Class conmanClass = Class.forName(conman.getClass().getName()); final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(conman); final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled); if(enabled){ Toast.makeText(view.getContext(), "Enabled Network Data", Toast.LENGTH_LONG).show(); view.setBackgroundColor(Color.GREEN); } else{ Toast.makeText(view.getContext(), "Disabled Network Data", Toast.LENGTH_LONG).show(); view.setBackgroundColor(Color.LTGRAY); } }catch(Exception e){ Log.e("Error", "some error"); Toast.makeText(view.getContext(), "It didn't work", Toast.LENGTH_LONG).show(); } } private boolean checkConnectivityState(Context context){ final TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); ConnectivityManager af ; return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED; } } Log file: java.lang.RuntimeException: Unable to instantiate receiver com.rakesh.simplewidget.ConnectivityReceiver: java.lang.ClassNotFoundException: com.rakesh.simplewidget.ConnectivityReceiver in loader dalvik.system.PathClassLoader[/data/app/com.rakesh.simplewidget-2.apk] E/AndroidRuntime(26094): at android.app.ActivityThread.handleReceiver(ActivityThread.java:1777) E/AndroidRuntime(26094): at android.app.ActivityThread.access$2400(ActivityThread.java:117) E/AndroidRuntime(26094): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985) E/AndroidRuntime(26094): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime(26094): at android.os.Looper.loop(Looper.java:130) E/AndroidRuntime(26094): at android.app.ActivityThread.main(ActivityThread.java:3691) E/AndroidRuntime(26094): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(26094): at java.lang.reflect.Method.invoke(Method.java:507) E/AndroidRuntime(26094): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) E/AndroidRuntime(26094): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) E/AndroidRuntime(26094): at dalvik.system.NativeStart.main(Native Method) It seems Android is not able to recognize file Broadcast Receiver class. Any idea why I am getting this error? PS: Some information about Android environment and platform. - Android API 10. - Running on Samsung Galaxy II which has android 2.3.6 Edit: my broadcast receiver file ConnectivityReceiver.java was present in default package and it was not being recognized by Android. Android was looking for this file in current package i.e com.rakesh.simplewidget; I just moved connectivityReciever.java file to com.rakesh.simplewidget package and problem was solved.

    Read the article

  • Get from Android BroadcastReciever to a UI

    - by Andy
    I have a reciever that works well, but I can't seem to show a proper UI, although the toast appears correctly. As far as I can tell, this is caused by Android requiring the class to extend Activity, however, the class already extends BroadcastReciever, so I can't do this. So, I tried to do an Intent, but this failed too. There are no errors, but the screen doesn't show. Source code is below, and any help would be most appreciated. Reciever public class Reciever extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Alarm Recieved", Toast.LENGTH_LONG).show(); Intent i = new Intent(); i.setClass(context, AlarmRing.class); } } AlarmRing public class AlarmRing extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarm); MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.sweetchild); mp.start(); } Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.comaad.andyroidalarm" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AndyRoidAlarm" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.comaad.andyroidalarm.Reciever" android:enabled="true"> <intent-filter> <action android:name="com.comaad.andyroidalarm.Reciever"></action> </intent-filter> </receiver> <activity android:name=".AlarmRing"></activity> </application> </manifest> }

    Read the article

1 2 3 4  | Next Page >