这件事对我们来说很奇怪。有些设备会打开onmsgrcv,而其他设备则不会关闭应用程序。为什么像Whatsapp这样的应用会在关闭时收到通知?我的应用程序关闭时为什么不收到?需要帮助......
alert.php
$divisions = $_GET['divisions'];
$tokens = array();
$tokens[0] = "e3-nlNImIR8:APA91bGQ3WJW_jWfelz5mEp6L6--wNgdZtb93Bx7kZBSsXUaGYOvdg0_RaP7KlnlfGBD4Xqs3Kyr-IKc0s3072DPGCvToeFeO0w9EHazGOqZt30KbNE7zQr4gbklJ9nZlypyU8IyYzIl";
$tokens[1] = "fWFN3lpvIjI:APA91bF1Kkh-EBEEi8-qkrBgtwxzFAK4WfupWvgjA1PlWjquKTg8yUzMALO9UeTBJHw8UMbE_SLM2cObpf_PolQNkg4AW10Dsg7rtwvI41tIL83Kpm8BZ8cs4GEGXOYrbF0KaB_GG3jo";
$tokens[2] = "eimGs3j1bsA:APA91bFhJHRtxTKldSsrIVr8d12fVLId1DYkUIKgiczTrXGgKLQnoud9ZMIvi1wKHHQWkGcV2ptmLqLfHywgIwWzRxpfaJuICNvgqF2OUnfKist3_t-2XuASukuc4_6Ua9sER29c-oi9";
$data = array(
"divisions" => $divisions
);
$fields = array(
'to' => "/topics/ALERT",
'data' => $data
);
$headers = array(
'Authorization:key = AAAAjCAUSaQ:APA91bGa0FsAjY-5tjEBIiavo960rU39UmendbRC-akMdKxJIdSsqwwlNl4YMl1iAIYd2evyp_5kWe6l_RmpzLGXHiY91NY8LRKa75XNruD9Jvnyu8xNA2IIinLlkJLi8TL5Ud4M9hjY',
'Content-Type: application/json'
);
$ch = curl_init();
$url = "https://fcm.googleapis.com/fcm/send";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($fields));
$result = curl_exec($ch);
echo $result;
curl_close($ch);
>
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:hardwareAccelerated="false"
android:largeHeap="true"
android:label="@string/app_name"
android:roundIcon="@drawable/ic_launcher"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name="android.support.multidex.MultiDexApplication"
>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_launcher" />
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
<activity
android:name="com.kayhanswarup.avtro.prokriti.ui.HomeActivity"
android:configChanges="locale|orientation"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
</activity>
<!-- <service android:name=".services.MyService" android:process=":my_service" /> -->
<service android:name="com.kayhanswarup.avtro.prokriti.services.CloudMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="com.kayhanswarup.avtro.prokriti.services.InstanceTokenService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<provider android:authorities="com.facebook.app.FacebookContentProvider1697853730520523"
android:name="com.facebook.FacebookContentProvider"
android:exported="true"/>
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
<activity android:name="com.kayhanswarup.avtro.prokriti.ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="@string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
CloudMessagingService.java
公共类CloudMessagingService扩展了FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
ML.d("Message data exists. Should go background: " + remoteMessage.getData());
goBackend(remoteMessage.getData().get("divisions"));
}
else if (remoteMessage.getNotification() != null) {
ML.d("Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
public int currentDivisionIndex = -1;
public String currentDivision="";
private void goBackend(final String messageBody){
ML.setTagServer(true);
ML.i("Reached with data: "+messageBody);
final Intent intent1 = new Intent(this,HomeActivity.class);
final String[] divisions = ApiEndPoints.DIVISIONS;
try {
provider = LocationManager.NETWORK_PROVIDER;
locationManager=(LocationManager)getBaseContext().getSystemService(Context.LOCATION_SERVICE);
final Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
ML.d("location(lng,lat) value in background app: "+location.getLongitude()+","+location.getLatitude());
ApiClient.getInstance(getBaseContext())
.getWeather(location.getLatitude()+"", location.getLongitude()+"", new OnResponse<Weather, ANError>() {
@Override
public void onResponse(Weather response) {
try{
currentDivision= response.getQuery().getResults().getChannel().getLocation()
.getRegion();
}catch (Exception e){
ML.e("Exception during api client weather: "+e.getMessage());
return;
}
ML.d("Current DIVISION: "+currentDivision);
if(currentDivision!=null&¤tDivision.length()>=3){
ML.d("current Division is: "+currentDivision);
for(int i=0;i<divisions.length;i++){
ML.i("No#"+i+" division: "+divisions[i]);
if((currentDivision.toLowerCase().contains(divisions[i].toLowerCase()))||divisions[i].toLowerCase().contains(currentDivision.toLowerCase())){
ML.d("We got a match: "+i);
currentDivisionIndex = i;
}else{
ML.d("Current division: "+currentDivision.toLowerCase());
ML.d("INDEX DIVISION: "+divisions[i].toLowerCase());
}
}
ML.d("Current: "+currentDivisionIndex);
if(currentDivisionIndex<0||(currentDivisionIndex>=0&&messageBody.substring(currentDivisionIndex,currentDivisionIndex+1).equals("0"))){
ML.d("Returning from background" +
"DONE");
ML.d("Reached background but location mismatched");
if(currentDivisionIndex>=0){
ML.d("What is this: "+messageBody.substring(currentDivisionIndex,currentDivisionIndex+1));
}
return;
}else{
ML.d("Atleast found sth...");
}
ML.d("VALUE ACCORDING TO : "+messageBody.substring(currentDivisionIndex,currentDivisionIndex+1));
int val=0;
try {
val= Integer.parseInt(messageBody.substring(currentDivisionIndex,currentDivisionIndex+1));
} catch (Exception e) {
ML.e("Integer parsing error: "+e.getMessage());
}
if(currentDivisionIndex>=0&&val!=0){
String lang = "en";
try {
lang = isLangBangla()?"bn":"en";
} catch (Exception e) {
ML.e("GOT EXCEPTION");
lang="bn";
}
FirebaseDatabase.getInstance().getReference("versions")
.child("001")
.child("locales")
.child(lang)
.child("alert")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ML.d("Will show an alert... IF LUCKY...");
final Alert alert = dataSnapshot.getValue(Alert.class);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("versions").child("001")
.child("LOG");
String key = ref.push().getKey();
ref.child(key).setValue(ML.getLog() + "", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError==null)
Log.d("Prokriti","sent");
ML.setTagServer(false);
Notify.getInstance().setHasNotification(true);
String title = getString(R.string.alert_title);
String body = getString(R.string.alert_body);
try {
if(alert!=null){
ML.d("Alert: "+alert.toString());
title = alert.getTitle();
body = alert.getBody();
}else ML.e("Alert is null");
} catch (Exception e) {
ML.e("no alert found"+e.getMessage());
}
try {
Notify.getInstance().setTitle(title);
Notify.getInstance().setDescription(body);
} catch (Exception e) {
ML.e("Notify error: "+e.getMessage());
Notify.getInstance().setTitle("Title");
Notify.getInstance().setDescription("Danger");
}
PendingIntent pendingIntent = PendingIntent.getActivity(CloudMessagingService.this, 0 /* Request code */, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
ML.d("Pack res path: "+getPackageResourcePath());
ML.d("Pack res: "+getPackageName());
Uri defaultSoundUri= Uri.parse("android.resource://"+getPackageName()+"/"+ R.raw.alert);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(CloudMessagingService.this)
.setSmallIcon(R.drawable.ic_cloud)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
});
// intent.putExtra("locale","notify");
}
@Override
public void onCancelled(DatabaseError databaseError) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("versions").child("001")
.child("LOG");
String key = ref.push().getKey();
ref.child(key).setValue(ML.getLog() + "", new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError==null)
Log.d("Prokriti","sent");
ML.setTagServer(false);
}
});
}
});
}
}
}
@Override
public void onError(ANError error) {
ML.e("Error: "+error.getMessage());
}
});
}
} catch (Exception e) {
ML.e("Still shows fucking ERROR: "+e.getMessage());
}
}
public static boolean isLangBangla(){
return LocaleManager.getInstance().getLocale().getDisplayLanguage().toLowerCase().contains("bengali");
}
LocationManager locationManager=null;
String provider;
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// provider = LocationManager.NETWORK_PROVIDER; // locationManager =(LocationManager)getBaseContext()。getSystemService(Context.LOCATION_SERVICE); 位置location = locationManager.getLastKnownLocation(provider);
if(location!=null){
ML.d("location(lng,lat): "+location.getLongitude()+","+location.getLatitude());
}else ML.d("location is null...");
intent.putExtra("locale","notify");
Notify.getInstance().setHasNotification(true);
Notify.getInstance().setTitle("Title");
Notify.getInstance().setDescription("ED");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
ML.d("Pack res path: "+getPackageResourcePath());
ML.d("Pack res: "+getPackageName());
Uri defaultSoundUri= Uri.parse("android.resource://"+getPackageName()+"/"+ R.raw.alert);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_cloud)
.setContentTitle(getString(R.string.alert_title))
.setContentText(getString(R.string.alert_body))
.setAutoCancel(false)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
}