-1

I practice FCM send and get notification. It works at test package, but not works at my own package..

Here is my log..

2020-07-23 15:11:29.433 19947-19947/? E/FirebaseInstanceId: Failed to start service while in background: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.firebase.INSTANCE_ID_EVENT pkg=lg.uplusbox cmp=lg.uplusbox/.controller.fcm.FcmInstanceIdService (has extras) }: app is in background uid UidRecord{91a4603 u0a198 TRNB idle change:uncached procs:1 proclist:19947, seq(0,0,0)} 2020-07-23 15:11:29.437 19947-19947/? I/FA: App measurement is starting up, version: 11400 2020-07-23 15:11:29.437 19947-19947/? I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE 2020-07-23 15:11:29.444 19947-19947/? V/FA: Collection enabled 2020-07-23 15:11:29.445 19947-19947/? V/FA: App package, google app id: lg.uplusbox, 1:814604498086:android:0700c6cb9bf60793 2020-07-23 15:11:29.445 19947-19947/? I/FA: To enable faster debug mode event logging run: adb shell setprop debug.firebase.analytics.app lg.uplusbox 2020-07-23 15:11:29.445 19947-19947/? D/FA: Debug-level message logging enabled 2020-07-23 15:11:29.446 19947-19947/? V/FA: Cancelling job. JobID: -1683691085 2020-07-23 15:11:29.450 19947-19947/? V/FA: Registered activity lifecycle callback 2020-07-23 15:11:29.467 19947-19970/? V/FA: Using measurement service 2020-07-23 15:11:29.467 19947-19970/? V/FA: Connecting to remote service 2020-07-23 15:11:29.486 19947-19970/? V/FA: Using measurement service 2020-07-23 15:11:29.486 19947-19970/? V/FA: Connection attempt already in progress 2020-07-23 15:11:29.588 19947-19970/? D/FA: Connected to remote service 2020-07-23 15:11:29.588 19947-19970/? V/FA: Processing queued up service tasks: 2 2020-07-23 15:11:34.642 19947-19970/? V/FA: Inactivity, disconnecting from the service

cm94
  • 9
  • my own app shutting down when get push message.. – cm94 Jul 23 '20 at 07:05
  • Hi @cm94 welcome to SO. I see you have added your code as answers by mistake. You should add those to your question by clicking the above "edit" link. You should also delete the below answers. – tune5ths Jul 23 '20 at 07:12
  • Try following this answer -> https://stackoverflow.com/a/70858784/13546426 – Shubham Panchal Jan 26 '22 at 04:52

3 Answers3

0
  1. TestActivity

public class TestActivity extends AppCompatActivity {

TextView textView;
TextView textView2;
String newToken;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    Log.d("FMS_MAIN", "onCreate() called");

    textView = findViewById(R.id.textView);
    textView2 = findViewById(R.id.textView2);

    FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            newToken = instanceIdResult.getToken();

            println("token: " + newToken);// it work..
            Log.d("Mytoken", "token : " + newToken); // not work..

        }
    });
    Log.d("Mytoken", "token : " + newToken);

    Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String instancedId = FirebaseInstanceId.getInstance().getId();                 println("instanced id: " + instancedId); // it work..!
            Log.d("Mytoken", "instance id: " + instancedId);// but it not work..
            Toast.makeText(TestActivity.this,instancedId,Toast.LENGTH_SHORT).show(); // it not work too..
        }
    });
}

@Override
protected void onNewIntent(Intent intent) {
    println("onNewIntent() called");
    Log.d("FMS_MAIN", "onNewIntent() called");

    if (intent != null) {
        println("Intent is Not null");
        processIntent(intent);
    } else {
        println("Intent is null");
    }

    super.onNewIntent(intent);
}

private void processIntent(Intent intent) {
    Log.d("FMS_MAIN", "processIntent called");
    int ekey = intent.getIntExtra("ekey", 2);
    String ename = intent.getStringExtra("ename");

    println("ekey: " + ekey);
    textView.setText("");
    textView.setText("[" + ename + "]'s eKey : " + ekey);
}

public void println(String data) {
    textView2.setText(data + "\n");
}
cm94
  • 9
0
  1. MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public MyFirebaseMessagingService() {
    }

    private static final String TAG = "FMS";

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e(TAG,"onNewToken() called: "+s);
    }
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Log.d(TAG,"onMessageReceived() called");

        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");
        String ekey = remoteMessage.getData().get("ekey");
        String ename = remoteMessage.getData().get("ename");

        if (title != null && body != null && ekey != null && ename != null){
            Log.d(TAG,"Title: "+title+", body: "+body+", ekey: "+ekey);

            sendNotification(title,body);
            newActivityIntent(ekey,ename);
        }
    }

    private void newActivityIntent(String key,String name){
        Log.d(TAG, "sendToActivity() called. ekey: " +key);
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);

        intent.putExtra("ekey",Integer.valueOf(key));
        intent.putExtra("ename",name);

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
                Intent.FLAG_ACTIVITY_SINGLE_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);
    }

    public void sendNotification(String title, String text) {
        Intent intent1 = new Intent(getApplicationContext(),MainActivity.class);
        Log.d(TAG, "sendNotification() called");

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent1,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(text)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setDefaults(Notification.DEFAULT_VIBRATE)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}
cm94
  • 9
0

Here is PushSendProject

public void sendEmergancyData() {
        Log.d("PUSH","Start");
        try {
            RequestQueue queue = Volley.newRequestQueue(this);
            String url = "https://fcm.googleapis.com/fcm/send";
            JSONObject pushData = new JSONObject();

            pushData.put("ekey", elderlyData.getEkey());
            pushData.put("ename", name);
            pushData.put("homeIot", homeIot);

            pushData.put("title", name);
            pushData.put("body", "emergancy");

            JSONObject push = new JSONObject();
            push.put("to", regid);
            push.put("data", pushData);

            JsonObjectRequest request = new JsonObjectRequest(url, push, new com.android.volley.Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("Emergancy_Push","success:"+response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("Emergancy_Push","error:"+error.getMessage());
                }
            }) {
                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String> headers = new HashMap<>();
                    headers.put("Content-Type", "application/json");
                    headers.put("Authorization", Constants.FCM_API_KEY);
                    return headers;
                }
            };
            queue.add(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d("PUSH","End");
    }

I already know Receive App's token before, so it used regid in Send App.

cm94
  • 9