简体   繁体   中英

AlarmManager and how to set it up

I am having a hard time wrapping my head around programming my AlarmManager.

The code below pretty much just assigns the current date to a text field and gets some XML and shows it using setListAdapter . I would like for this code to run on start up and then run every 30 minutes.

     Date anotherCurDate = new Date();
          SimpleDateFormat formatter = new SimpleDateFormat("EEEE', 'MMMM dd', ' yyyy");  
          String formattedDateString = formatter.format(anotherCurDate); 

         TextView currentRoomDate = (TextView)  this.findViewById(R.id.CurrentDate); 
         currentRoomDate.setText(formattedDateString); 

 ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


        String xml = XMLfunctions.getXML(items);
        Document doc = XMLfunctions.XMLfromString(xml);

        /*int numResults = XMLfunctions.numResults(doc);

        if((numResults <= 0)){
            Toast.makeText(MeetingManager.this, "NOT GETTING XML", Toast.LENGTH_LONG).show();  
            finish();
        } */

        Element docElem = doc.getDocumentElement();
        NodeList nodes = (NodeList)docElem.getElementsByTagName("meeting_item");

int node_number = nodes.getLength();
String node_final = String.valueOf(node_number);

        Log.d(TAG, node_final);

        for (int i = 0; i < nodes.getLength(); i++) {                           
            HashMap<String, String> map = new HashMap<String, String>();    

            Element e = (Element)nodes.item(i);

            String date_value = XMLfunctions.getValue(e, "date");

           // Log.d(TAG, date_value);
            //Log.d(TAG, formattedDateString);
                //if (date_value == formattedDateString){
                    map.put("time", XMLfunctions.getValue(e, "time"));
                    map.put("endtime", XMLfunctions.getValue(e, "endtime"));
                    map.put("name", XMLfunctions.getValue(e, "meeting_name"));
                    map.put("hostname", XMLfunctions.getValue(e, "host_name"));
                    mylist.add(map);
                //}


        }       

        ListAdapter adapter = new SimpleAdapter(MeetingManager.this, mylist , R.layout.listlayout, 
                        new String[] {"time","endtime", "name", "hostname" }, 
                        new int[] { R.id.time, R.id.endtime, R.id.meeting_name, R.id.host });

       setListAdapter(adapter);





     Intent mRefreshIntent = new Intent().setComponent(new ComponentName(getBaseContext(), UpdateData.class)).setAction("com.MeetingManager.UpdateData");

    PendingIntent mPendingRefreshIntent = PendingIntent.getBroadcast(getBaseContext(), 0, mRefreshIntent, PendingIntent.FLAG_CANCEL_CURRENT); //choose your desired flag


    AlarmManager mAlarmManager = null;

    mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), AlarmManager.INTERVAL_HALF_HOUR, mPendingRefreshIntent);

And here is my UpdateData class:

package com.MeetingManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class UpdateData extends BroadcastReceiver {


        private static final String TAG = "MyApp";

        @Override
        public void onReceive(Context context, Intent intent) {
              Log.d(TAG, "HELLO UPDATE");
        }
    }

Here is my Manifest file:

        <receiver android:name="UpdateData">
    <intent-filter>
        <action android:name="com.MeetingManager.UpdateData" />
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.HOME" />
    </intent-filter>
</receiver>

Can anyone please give me advice on what I am doing wrong.

Below is the output of my debug:

<terminated>MeetingManager [Android Application]    
    <disconnected>DalvikVM[localhost:8615]  
MeetingManager [Android Application]    
    DalvikVM[localhost:8615]    
        Thread [<1> main] (Suspended (exception RuntimeException))  
            ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2663  
            ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2679   
            ActivityThread.access$2300(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 125 
            ActivityThread$H.handleMessage(Message) line: 2033  
            ActivityThread$H(Handler).dispatchMessage(Message) line: 99 
            Looper.loop() line: 123 
            ActivityThread.main(String[]) line: 4627    
            Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
            Method.invoke(Object, Object...) line: 521  
            ZygoteInit$MethodAndArgsCaller.run() line: 868  
            ZygoteInit.main(String[]) line: 626 
            NativeStart.main(String[]) line: not available [native method]  
        Thread [<6> Binder Thread #2] (Running) 
        Thread [<5> Binder Thread #1] (Running) 

At first you need to create a PendingIntent :

mRefreshIntent = new Intent()
    .setComponent(new ComponentName(mContext, YourBroadcastReceiver.class))
    .setAction("my.package.name.YOUR_ACTION");
mPendingRefreshIntent = PendingIntent.getBroadcast(
    mContext, 
    0, 
    mRefreshIntent, 
    PendingIntent.FLAG_CANCEL_CURRENT); //choose your desired flag

You can then set the alarm using the following code

mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, time, yourInterval, mPendingRefreshIntent);

Again, you can choose some other flag than RTC_WAKEUP.

For the execution of the code, you need your own implementation of BroadCastReceiver :

public class YourBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //execute your code here
    }
}

And you need to register that receiver in the manifest, for your Alarm-generated intent, as well as the intent that is broadcasted on system boot:

<manifest>
    ...
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    ...
    <application>
        ...
        <receiver
            android:name="YourBroadcastReceiver">
            <intent-filter>
                <action android:name="my.package.name.REFRESH_WALLPAPER" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </receiver>
        ...
    </application>
</manifest>

The permission is important!
Hope this answers your question.

It appears like you are trying to use a Broadcast Receiver as if it was a service. One option would be to turn the BR into a service and change the pending intent to launch that service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM