Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Error in doing interval task using BroadcastReceiver and AlarmManager in Android

I am absolute beginner to Android. So now I am trying to develop a to-do list app on my own to improve my skills. My app is offline. But in my app I need to notify the user of the to-do tasks everyday. So I need to fire event for it in the background even my app is not running.

So I am trying to integrate AlarmManager with BroadcastReceiver by creating a simple project to show a simple toast message at every interval. But it is throwing error. This code is not the to-do app code. I am just testing to do background event firing even my app is not running. But when I run this code. It is throwing error.

This is my Android manifest file:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".RemainderReceiver"></receiver>
    </application>

</manifest>

This is the activity class

public class MainActivity extends AppCompatActivity {
    private RemainderReceiver remainderReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        remainderReceiver = new RemainderReceiver();
        remainderReceiver.startRemainder(this.getApplicationContext());
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

This is the Broadcast Receiver

public class RemainderReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
        //Acquire the lock

        wl.acquire();

        Toast.makeText(context,"my message", Toast.LENGTH_SHORT).show();
        wl.release();
    }

    public void startRemainder(Context context)
    {
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context,RemainderReceiver.class);

        PendingIntent pi = PendingIntent.getBroadcast(context,0,intent,0);
        am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000*2,pi);
    }
}

This is the Logcat when I run this app

01-23 09:45:33.853 2029-2029/? D/AndroidRuntime: Shutting down VM
01-23 09:45:33.853 2029-2029/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa615a908)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime: FATAL EXCEPTION: main
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start receiver com.example.bgnotification.bgnotification.RemainderReceiver: java.lang.SecurityException: Neither user 10058 nor current process has android.permission.WAKE_LOCK.
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2383)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.access$1500(ActivityThread.java:141)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:  Caused by: java.lang.SecurityException: Neither user 10058 nor current process has android.permission.WAKE_LOCK.
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Parcel.readException(Parcel.java:1425)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Parcel.readException(Parcel.java:1379)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:271)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:717)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.PowerManager$WakeLock.acquire(PowerManager.java:686)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.example.bgnotification.bgnotification.RemainderReceiver.onReceive(RemainderReceiver.java:22)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2376)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.access$1500(ActivityThread.java:141)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5041)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)?
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)?
01-23 09:45:33.853 476-1662/? W/ActivityManager:   Force finishing activity com.example.bgnotification.bgnotification/.MainActivity
01-23 09:45:33.909 476-1662/? D/dalvikvm: GC_FOR_ALLOC freed 2598K, 47% free 6995K/13080K, paused 9ms, total 9ms
01-23 09:45:33.937 476-492/? D/dalvikvm: GC_FOR_ALLOC freed 57K, 40% free 7894K/13080K, paused 19ms, total 19ms
01-23 09:45:33.957 476-479/? D/dalvikvm: GC_CONCURRENT freed 100K, 31% free 9117K/13080K, paused 1ms+5ms, total 19ms
01-23 09:45:33.969 476-492/? I/dalvikvm-heap: Grow heap (frag case) to 11.451MB for 2536932-byte allocation
01-23 09:45:33.993 476-484/? D/dalvikvm: GC_FOR_ALLOC freed <1K, 26% free 11594K/15560K, paused 25ms, total 25ms
01-23 09:45:34.021 476-479/? D/dalvikvm: GC_CONCURRENT freed 69K, 25% free 11770K/15560K, paused 2ms+1ms, total 30ms
01-23 09:45:34.413 476-488/? W/ActivityManager: Activity pause timeout for ActivityRecord{532d55cc u0 com.example.bgnotification.bgnotification/.MainActivity}
01-23 09:45:34.441 679-679/? W/EGL_genymotion: eglSurfaceAttrib not implemented
01-23 09:45:34.513 476-544/? I/qtaguid: Failed write_ctrl(s 0 10058) res=-1 errno=1
01-23 09:45:34.513 476-544/? W/NetworkManagementSocketTagger: setKernelCountSet(10058, 0) failed with errno -1
01-23 09:45:44.513 476-488/? W/ActivityManager: Activity destroy timeout for ActivityRecord{532d55cc u0 com.example.bgnotification.bgnotification/.MainActivity}

How can I debug this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you missed WAKE_LOCK permission in manifest.XML:

<uses-permission android:name="android.permission.WAKE_LOCK"/>

Your manifest.xml will like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bgnotification.bgnotification" >
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".RemainderReceiver"></receiver>
</application>

</manifest>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...