问题
I'm realy newbie in android, and i'm having dificult with broadcastreceiver in my project.
I've created uses-permission and the receiver in AndroidManifest.xml, created the class but it not passing on the logcat message.
MY RECEIVER CLASS
package com.polifrete.polifreteFunctions;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("Script", "Passou AQUI");
Intent i = new Intent(context, VerificaNovoFreteService.class);
context.startService(i);
}
}
MY ANDROIDMANIFEST.XML
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.polifrete.polifreteFunctions.MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
What i'm doing wrong? Please, help me!
回答1:
Not every Phone sends the BOOT_COMPLETED
Broadcast. For example, I think it was HTC, sends the QUICKBOOT_POWERON
Broadcast, if it has boot up. Also your logcat is maybe not connected to your phone at Boot-Up-Time. I'd suggest to create a Toast
to check, wether your Boot-Reciever
is executed.
You can create this Toast
with this code:
Toast toast = Toast.makeText(getApplicationContext(), "Boot-Reciever Started", Toast.LENGT_LONG);
回答2:
@Felipe A., it's possible that you have a problems with CPU...The oficial documentation talks about it, and says the best use is WakefulBroadcastReceiver guarantee a that CPU will stays awake, you can read this post that talk about it: https://stackoverflow.com/a/26380942/3996257
This is my code with WakefulBroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntent_Service.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
The gcm receiver needs to add your package in your intent-filter it's the only difference with my code. And my receiver have this code:
<receiver
android:name=".App_Services.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />/>
<category android:name="your.package" />
</intent-filter>
</receiver>
It's possible your code don't recognizes your receiver because doesn't know their package. Tell me if I helps you, good luck!
来源:https://stackoverflow.com/questions/30104113/broadcastreceiver-android