0
votes

I am new to android. I was playing with the AlarmManager and had successufully go a piece of code running with the BroadcastReceiver as a separate class.

I am now trying to put the BroadcastReceiver as inner class but have no luck on firing the BroadcastReceiver. I had no idea what might have gone wrong after hours looking at the code...

Here is my code:

public class InnerService extends Service{

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter(InnerBroadcastReceiver.class.toString());
        Log.d("InnerService","InnerService starts!");
        Log.d("InnerService","class : "+InnerBroadcastReceiver.class.toString());
        this.registerReceiver(new InnerBroadcastReceiver(), filter);
        scheduleTestAlarmReceiver(this);

    }

    public static void scheduleTestAlarmReceiver(Context context) {
        Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver start");
        Intent receiverIntent = new Intent(context, InnerBroadcastReceiver.class);
        receiverIntent.setAction("com.example.alarmmanagertest.InnerService$InnerBroadcastReceiver");
        PendingIntent sender = PendingIntent.getBroadcast(context, 123456789,
                receiverIntent, 0);

        AlarmManager alarmManager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime(), 1000, sender);
        Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver complete");
    }

    private class InnerBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.d("InnerBroadcastReceiver","InnerBroadcastReceiver ALARM Manager fires success!");
        }

    }

}

It looks like the AlarmManager tried to fire the BroadcastReceiver every second but failed

Logcat:

V/AlarmManager(2439): waitForAlarm result :4
V/AlarmManager(2439): trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP

UPDATE

I have tried to change the code for creating intent in onCreate() and scheduleTestAlarmReceiver() to intent = new intent("action_string") and it works. It seems that intent.setAction() is not working.

What will be the pros and cons for creating intent with and without context (Intent(Context packageContext, Class<?> cls) and Intent(String action))? But I would still like to know why the above code failed. Can anyone explain?

1
have You registered the receiver in manifest?Opiatefuchs
I am trying to use register the receiver dynamically so I did not put it in manifest.user2763829
by the way, wwhy You are using SystemClock.elapsedRealtime()? this returns the time in ms after boot. Instead use a Calendar object and use cal.getTimeInMillis()Opiatefuchs
This piece of code is just used for learning purpose. BTW Thanks for the information on using calendar.user2763829
and does this solve Your problem?Opiatefuchs

1 Answers

0
votes

True, it works!

Small changes in my code. Apk with AsyncTask (downloading file from web and parsing it). "OneMeeting" is my class from project.

public class MainActivity extends AppCompatActivity {
public static final String INPUT_FILE_URL = "https://.../";

private RecyclerView recyclerView;
private String getFilesDir;
private ArrayList<OneMeeting> meetingsArr = new ArrayList<>();
private BroadcastReceiver receiver;
private RefreshFile refreshFile;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    getFilesDir = getFilesDir().getAbsolutePath();

    recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    meetingsArr.add(new OneMeeting("Launching..." , "", "", ""));
    recyclerView.setAdapter(new MyAdapter(meetingsArr, recyclerView));

    Intent alarmIntent = new Intent("commaciejprogramuje.facebook.conferenceapplication.MainActivity$RefreshFile");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 111, alarmIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 5, pendingIntent);
}

@Override
protected void onResume() {
    super.onResume();
    refreshFile = new RefreshFile();
    IntentFilter filter = new IntentFilter("commaciejprogramuje.facebook.conferenceapplication.MainActivity$RefreshFile");
    this.registerReceiver(refreshFile, filter);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(refreshFile);
}

private class RefreshFile extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Refresh", Toast.LENGTH_LONG).show();

        ParsePage refreshParsingPage = new ParsePage(new ParsePage.OnTaskCompletedListener() {
            @Override
            public void onTaskCompletedListener(ArrayList<OneMeeting> parsingResultArr) {
                meetingsArr = parsingResultArr;
                recyclerView.setAdapter(new MyAdapter(meetingsArr, recyclerView));
            }
        });
        refreshParsingPage.execute(getFilesDir);
    }
}

}