Search code examples
androidbroadcastreceiveralarmmanageralarm

Cannot get AlarmManager to work at all on Galaxy III or an emulator


I've browse two dozens samples, articles and so on trying to see why my code won't work. I have a very simple broadcast listener I'm trying to call with an alarm manager. Here's my code:

Main Activity onCreate and function (MapsActivity.java)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_maps);

    setUpMapIfNeeded();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(240 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(80 * 1000); // 1 second, in milliseconds
    Button clickButton = (Button) findViewById(R.id.search_for_beer);
    clickButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent bar = new Intent(MapsActivity.this, SearchBeer.class);
            bar.putExtra("tloc", Double.toString(location.getLongitude()) + "," + Double.toString(location.getLatitude()));
            startActivity(bar);
        }
    });
    startNotes();
}

public void startNotes() {

    Calendar cal = Calendar.getInstance();

    Intent intent = new Intent(MapsActivity.this, BeerNotes.class);
    PendingIntent pintent = PendingIntent.getService(MapsActivity.this, 12345, intent, 0);

    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarm.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + (5 * 1000), 5 * 1000, pintent);

}

My BroadcastReceiver ... I've commented out code I'm going to want to do and just trying to get a log right now and I'm getting nothing.

package com.tapmap.app.tapmapapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.io.InputStream;
import java.net.HttpURLConnection;

public class BeerNotes extends BroadcastReceiver {

private Exception exception;
private HttpURLConnection urlConnection;
public InputStream in;
private String total;
private static final long REPEAT_TIME = 1000 * 30;
private static final String APP_TAG = "LOG: ";
private static final int EXEC_INTERVAL = 20 * 1000;

@Override
public void onReceive(Context context, Intent intent) {

    Log.i(APP_TAG, "onReceive() called");
    /*
    try {
        URL url = new URL("http://fltapmap.com/notes.php");
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            in = new BufferedInputStream(urlConnection.getInputStream());
            try {
                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                String line;
                total = "";
                while ((line = r.readLine()) != null) {
                    total += line + "\n";
                }
                urlConnection.disconnect();
                Log.i("TOTAL NOTES", total);
            } catch(IOException ioe) {
                Log.i("MALFORMED1", ioe.getMessage());
                urlConnection.disconnect();
            }
        } catch (IOException ioe) {
            Log.i("MALFORMED2", ioe.getMessage());
            urlConnection.disconnect();
        }
    } catch (MalformedURLException ioex) {
        Log.i("MALFORMED3", ioex.getMessage());
    }
    */
}
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tapmap.app.tapmapapp" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<permission
    android:name="com.javapapers.android.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.javapapers.android.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:configChanges="orientation|screenSize"
        android:screenOrientation="portrait"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="AIzaSyAksheZLMAALUfLHKWOsfTFCz7iP_KwpCE" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".BarBrewry"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_bar_brewry"
        android:theme="@style/FullscreenTheme" >
    </activity>
    <activity
        android:name=".SearchBeer"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_search_beer"
        android:theme="@style/FullscreenTheme" >
    </activity>
    <activity
        android:name=".ViewBeer"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_search_beer"
        android:theme="@style/FullscreenTheme" >
    </activity>
    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" />

    <provider
        android:name="com.facebook.FacebookContentProvider"
        android:authorities="com.facebook.app.FacebookContentProvider934301593259187"
        android:exported="true" />

    <receiver
        android:name="com.tapmap.app.tapmapapp.BeerNotes"></receiver>
</application>

</manifest>

Solution

  • Change PendingIntent.getService() to PendingIntent.getBroadcast()

    EDIT

    I notice the commented code in your BroadcastReceiver will try to make a network request. This will cause your app to crash with a NetworkOnMainThread exception. I recommend you create a class that extends IntentService and do your network operations inside of onHandleIntent() instead. In that case, you can use PendingIntent.getService() to have the intent go to the service.