当我的安卓应用收到 Firebase 消息通知时,会立即关闭。

huangapple 未分类评论45阅读模式
英文:

When my android App get firebase message notification, then shutting down

问题

以下是翻译好的部分:

我在实践 FCM 发送和接收通知。
它在测试包中可以运行,但在我的自己的包中无法运行...

以下是我的日志..

2020-07-23 15:11:29.433 19947-19947/? E/FirebaseInstanceId: 尝试在后台启动服务时失败: java.lang.IllegalStateException: 不允许启动 Intent { act=com.google.firebase.INSTANCE_ID_EVENT pkg=lg.uplusbox cmp=lg.uplusbox/.controller.fcm.FcmInstanceIdService (有附加信息) }: 应用程序在后台 uid UidRecord{91a4603 u0a198 TRNB 空闲 change:未缓存的 进程:1 进程列表:19947, 序列(0,0,0)}
2020-07-23 15:11:29.437 19947-19947/? I/FA: 应用测量正在启动,版本: 11400
2020-07-23 15:11:29.437 19947-19947/? I/FA: 要启用调试日志记录,请运行: adb shell setprop log.tag.FA VERBOSE
2020-07-23 15:11:29.444 19947-19947/? V/FA: 启用了收集
2020-07-23 15:11:29.445 19947-19947/? V/FA: 应用程序包、谷歌应用程序 ID: lg.uplusbox, 1:814604498086:android:0700c6cb9bf60793
2020-07-23 15:11:29.445 19947-19947/? I/FA: 要启用更快的调试模式事件日志记录,请运行:
adb shell setprop debug.firebase.analytics.app lg.uplusbox
2020-07-23 15:11:29.445 19947-19947/? D/FA: 启用了调试级别的消息日志记录
2020-07-23 15:11:29.446 19947-19947/? V/FA: 取消作业。作业 ID: -1683691085
2020-07-23 15:11:29.450 19947-19947/? V/FA: 注册了活动生命周期回调
2020-07-23 15:11:29.467 19947-19970/? V/FA: 使用测量服务
2020-07-23 15:11:29.467 19947-19970/? V/FA: 正在连接到远程服务
2020-07-23 15:11:29.486 19947-19970/? V/FA: 使用测量服务
2020-07-23 15:11:29.486 19947-19970/? V/FA: 连接尝试已经在进行中
2020-07-23 15:11:29.588 19947-19970/? D/FA: 已连接到远程服务
2020-07-23 15:11:29.588 19947-19970/? V/FA: 处理排队的服务任务: 2
2020-07-23 15:11:34.642 19947-19970/? V/FA: 不活动,正在断开连接

英文:

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

答案1

得分: 0

2. 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); // 它能运行...
                Log.d("Mytoken", "token : " + newToken); // 不能运行...

            }
        });
        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); // 它能运行...!
                Log.d("Mytoken", "instance id: " + instancedId); // 但不能运行...
                Toast.makeText(TestActivity.this, instancedId, Toast.LENGTH_SHORT).show(); // 也不能运行...
            }
        });
    }

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

        if (intent != null) {
            println("Intent 不为 null");
            processIntent(intent);
        } else {
            println("Intent 为 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");
    }
}
英文:
  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(&quot;FMS_MAIN&quot;, &quot;onCreate() called&quot;);

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

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

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

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

    Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String instancedId = FirebaseInstanceId.getInstance().getId();                 println(&quot;instanced id: &quot; + instancedId); // it work..!
            Log.d(&quot;Mytoken&quot;, &quot;instance id: &quot; + 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(&quot;onNewIntent() called&quot;);
    Log.d(&quot;FMS_MAIN&quot;, &quot;onNewIntent() called&quot;);

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

    super.onNewIntent(intent);
}

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

    println(&quot;ekey: &quot; + ekey);
    textView.setText(&quot;&quot;);
    textView.setText(&quot;[&quot; + ename + &quot;]&#39;s eKey : &quot; + ekey);
}

public void println(String data) {
    textView2.setText(data + &quot;\n&quot;);
}

答案2

得分: 0

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());
    }
}
英文:
  1. MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    public MyFirebaseMessagingService() {
    }

    private static final String TAG = &quot;FMS&quot;;

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

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

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

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

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

        intent.putExtra(&quot;ekey&quot;,Integer.valueOf(key));
        intent.putExtra(&quot;ename&quot;,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, &quot;sendNotification() called&quot;);

        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 &gt;= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    &quot;Channel human readable title&quot;,
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

答案3

得分: 0

这是PushSendProject的代码部分,它用于发送紧急数据。你之前已经知道如何接收应用程序的令牌,在发送应用程序中使用了regid。

英文:

Here is PushSendProject

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

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

            pushData.put(&quot;title&quot;, name);
            pushData.put(&quot;body&quot;, &quot;emergancy&quot;);

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

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

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

huangapple
  • 本文由 发表于 2020年7月23日 14:50:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/63048462.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定