AlarmManager无法启动广播接收器

时间:2016-06-25 10:43:57

标签: android

我正在处理一个项目,该项目需要每2分钟检查一次数据库中的标记状态,但我的广播接收器类没有触发。

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());
}







}

清单

  <?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>

1 个答案:

答案 0 :(得分:0)

您发布的代码中有一些问题需要纠正。首先,要为BroadcastReceiver广告发送BOOT_COMPLETED,您需要添加RECEIVE_BOOT_COMPLETED权限。另请注意,自3.1以来,您的应用必须在安装后至少启动一次,才能使其退出已停止状态,以便进行广播。

其次,在确定该警报的初始时间时,您还需要一个月的时间。确实,Calendar的月份是从零开始的,但是您使用的是Calendar的从零开始的值,因此添加一个将其推向下个月。

最后,PendingIntent.getBroadcast()方法是static方法,返回请求的PendingIntent。它没有初始化它被调用的实例(顺便说一句,在这种情况下会导致NullPointerException,如果确实如此)。这意味着您已将空PendingIntent传递给AlarmManager,因此显然不会做任何事情。更改该行以调用类上的方法,并将返回值分配给您的字段。

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