Gowtam potluri Gowtam potluri - 5 months ago 26
Android Question

AlarmManager not starting broadcast reciver

I'm working on a project which requires to check flag status from my database every 2 mins but my broadcast receiver class is not triggering . I'm new to android,any help or suggestions would be great :)

Mainactivity

public class MainActivity extends Activity {

Button b1;
PendingIntent pendingIntent;
AlarmManager alarmManager;
int year,month,day,hour,min;

@SuppressWarnings("static-access")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub


mystart();

}
});

Intent i = new Intent(this,myBackgroundChecker.class);
pendingIntent.getBroadcast(this, 0, i, 0);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);





}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public void mystart(){
Calendar c = Calendar.getInstance();

year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
month+=1;
min+=1;
Toast.makeText(getBaseContext(), ""+hour+min+" day: "+day+ "month :"+month+"Year : "+year, Toast.LENGTH_LONG).show();

c.set(Calendar.DAY_OF_MONTH,day);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE,min+1);

int repeat = 1000*60*2;

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), repeat, pendingIntent);

}


}

myBackgroundChecker.java

public class myBackgroundChecker extends BroadcastReceiver{

static MediaPlayer mp;
InputStream is=null;
String result="";
ArrayList<NameValuePair> nameValuePairs;

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub

mp = MediaPlayer.create(arg0, R.raw.alert);

mp.setLooping(true);

//myDb m = new myDb();


nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("flag","0"));

Toast.makeText(arg0, "service started", Toast.LENGTH_SHORT).show();

//m.execute();
//First reading if 1 or not!
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.102/get.php");
//httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();

result=sb.toString();
Log.e("myTag", result);
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}

if(result.equals("1")){
mp.start();
}


// after trigering alarm setting to 0

try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.102/set.php");
httppost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();

}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();

result=sb.toString();
Log.e("myTag", result);
// Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}







}


Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.remotealarm_client"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.remotealarm_client.MainActivity"
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.example.remotealarm_client.myBackgroundChecker">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED">

</action>
</intent-filter>
</receiver>
</application>

</manifest>

Answer

There are a few things to correct in your posted code. First, for your BroadcastReceiver to be delivered the BOOT_COMPLETED broadcast, you'll need to add the RECEIVE_BOOT_COMPLETED permission. Also note that, since 3.1, your app will have to be launched at least once after installation to bring it out of the stopped state in order to get that broadcast.

Second, in figuring the initial time for that alarm, you're a month ahead. It's true that Calendar's months are zero-based, but you're using the Calendar's zero-based value, so adding one to it is pushing it to next month.

Lastly, the PendingIntent.getBroadcast() method is a static method that returns the requested PendingIntent. It doesn't initialize the instance it's called on (which, incidentally, would cause a NullPointerException in this case, if it did). This means you've been passing a null PendingIntent to AlarmManager, so that's obviously not going to do anything. Change that line to call the method on the class, and to assign the return to your field.

pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);
Comments