开发者

android broadcastReceiver not working

This is my supposed to work code according to Apress Android Recipes book:

package com.tugce.AlarmActivity;
public class AlarmActivity extends Activity implements OnClickListener {

    private PendingIntent mAlarmIntent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);

        Intent launchIntent = new Intent(this,AlarmReceiver.class);
        mAlarmIntent = PendingIntent.getBroadcast(this, 0, launchIntent, 0);
    }

    @Override
    public void onClick(View v) {
        AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        long interval = 2000;

        switch (v.getId()) {
        case R.id.start:
            Toast.makeText(this, "Scheduled", Toast.LENGTH_SHORT).show();
            manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+interval, interval, mAlarmIntent);
            break;

        case R.id.stop:
            Toast.makeText(this, "Canceled", Toast.LENGTH_LONG).show();
            manager.cancel(mAlarmIntent);
            break;

            default:
                break;
        }

    }

    public class AlarmRec开发者_运维知识库eiver extends BroadcastReceiver {

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

            Calendar now = Calendar.getInstance();
            DateFormat formatter = SimpleDateFormat.getDateTimeInstance();
            Toast.makeText(context, formatter.format(now.getTime()),
                    Toast.LENGTH_SHORT).show();

        }

    }
}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.tugce.AlarmActivity"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver android:name=".AlarmReceiver"></receiver>
        <activity android:name=".AlarmActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

I can't see any time stamp on the screen.


Is your receiver an inner class? It should not be. Put it in its own Java file. Android can't instantiate it otherwise.


I haven't tried it myself, but do you may need to set this permission:

SET_ALARM Permission

How to set Receiver's Permissions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜