You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用通知点击后如何启动Main Activity?附实现代码

Fixing Notification Click to Launch MainActivity in Your Android App

Got it, let's figure out why your notification isn't launching MainActivity when clicked! The problem is straightforward: your current notification code doesn't include a PendingIntent — that's the component that tells Android exactly what action to take when the user taps the notification. Here's how to fix it step by step:

Step 1: Understand the Missing Piece

Right now, your notification is just a visual alert with no attached action. We need to add a PendingIntent that points to your MainActivity, so Android knows to launch it on tap.

Step 2: Modify Your Code

Here's the updated version of your code with all necessary changes (I've marked new lines with comments for clarity):

public void run_loop(){ 
    final Globalv globalv = (Globalv) getApplicationContext(); 
    RequestQueue requestQueue; 
    String url = "https://......./show.php"; 
    requestQueue = Volley.newRequestQueue(this); 

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null , 
        new Response.Listener<JSONObject>() { 
            @Override 
            public void onResponse(JSONObject response) { 
                try { 
                    JSONArray jsonArray = response.getJSONArray("allmess"); 
                    JSONObject respons = jsonArray.getJSONObject(0); 
                    String id = respons.getString("id"); 
                    int lastThread= Integer.parseInt(String.valueOf(id)); 

                    if (globalv.getTotal_threads() < lastThread) { 
                        globalv.setTotal_threads(lastThread); 

                        // --- NEW CODE: Create Intent and PendingIntent for navigation ---
                        // 1. Intent to launch MainActivity
                        Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
                        // Flags ensure the activity launches properly (adjust based on your needs)
                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                        // 2. Build PendingIntent (handle Android 12+ immutable flag)
                        PendingIntent pendingIntent;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                            pendingIntent = PendingIntent.getActivity(
                                getApplicationContext(),
                                0,
                                notificationIntent,
                                PendingIntent.FLAG_IMMUTABLE
                            );
                        } else {
                            pendingIntent = PendingIntent.getActivity(
                                getApplicationContext(),
                                0,
                                notificationIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT
                            );
                        }
                        // --- END OF NEW CODE ---

                        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); 
                        builder.setContentTitle("هلالية للغات"); 
                        builder.setContentText("رسالة جديدة"); 
                        builder.setSmallIcon(R.drawable.splash_img); 
                        builder.setAutoCancel(true); 
                        builder.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE); 
                        builder.setNumber(1); 

                        // Attach the PendingIntent to the notification
                        builder.setContentIntent(pendingIntent); // <-- Critical line to add

                        Notification notification = builder.build(); 
                        NotificationManager mm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
                        mm.cancel(1); 
                        mm.notify(1, notification); 
                    } 
                } catch (JSONException e) { 
                    e.printStackTrace(); 
                } 
            } 
        }, 
        new Response.ErrorListener() { 
            @Override 
            public void onErrorResponse(VolleyError error) { 
                Log.e("VOLLEY", "ERROR"); 
            } 
        } 
    ); 

    requestQueue.add(jsonObjectRequest); 

    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
        @Override 
        public void run() { 
            run_loop(); 
        } 
    }, 29000); 
}

Key Notes About the Changes:

  • Intent Flags: FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK ensures that if MainActivity is already running in the background, it's brought to the foreground and any existing task stack is cleared. Adjust these flags if you need different navigation behavior.
  • PendingIntent Flags: For Android 12 (API 31+) and above, we use FLAG_IMMUTABLE for security. For older versions, FLAG_UPDATE_CURRENT ensures the intent is updated if it already exists.
  • Request Code: The 0 in PendingIntent.getActivity() is a request code — use a unique value if you need to distinguish between multiple notification actions later.

Quick Check for Manifest

Make sure your MainActivity is properly registered in AndroidManifest.xml (it should look something like this, which is standard for launch activities):

<activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

内容的提问来源于stack exchange,提问作者mohamed mrzouk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:11:45