Android:如何从通知恢复 Fragment 类。不创建新实例

Noo*_*Man 6 resume notifications android back-button fragment

我想在 Fragment 类中启动一个 CountDownTimer,当计时器到达时,比如说 3 分钟,Fragment 类(尽管应用程序在后台)将创建一个通知。当用户推送通知时,使用 CountDownTimer 保存此片段的应用程序应该恢复到其“状态”,就好像它是从主屏幕重新打开一样。所以当用户点击“后退按钮”时,用户应该被带到应用程序中的前一个活动,而不是回到主屏幕。

我的 Fragment_C.java 类,它在 Activity_C.java 类中:

package example.app;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class Fragment_C extends Fragment {

    static int amount;
    static String phone;
    static String message;

    long mMilliseconds;
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
    TextView mTextView;

    CountDownTimer mCountDownTimer = new CountDownTimer(amount * 60000, 1000) {
        @Override
        public void onFinish() {
            mTextView.setText(mSimpleDateFormat.format(0));
                        // Do something cool
        }

        public void onTick(long millisUntilFinished) {
                        // Show the countdown in a TextView:
            mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));

                        // Get the time in string format, to use for if-statements:
            String millisInString = mSimpleDateFormat.format(millisUntilFinished);

            if (millisInString.equals("00:03:00")) {
                generateNotification();
                Log.i("There is exactly 3 minutes left", "YO!");
            }
            if (millisInString.equals("00:02:00")) {
                generateNotification();
                Log.i("There is exactly 2 minutes left", "YO!");
            }
            if (millisInString.equals("00:01:00")) {
                generateNotification();
                Log.i("There is exactly 1 minute left", "YO!");
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Get the view for this fragment, to retrieve views from it.
        View view = inflater.inflate(R.layout.fragment_c, container, false);

        mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        mTextView = (TextView) view.findViewById(R.id.timerview);

        mCountDownTimer.start();

        // Get the start_alarm_button object from the fragment_c.xml:
        Button button = (Button) view
                .findViewById(R.id.fragment_c_cancel_alarm_button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // If this button is pushed, return to Activity_B:
                mCountDownTimer.cancel();
                                // Basically push the "back-button"
                getActivity().finish();
            }
        });

        return view;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
                // Stop the CountDownTimer if the Activity gets destroyed:
        if(mCountDownTimer != null){
            mCountDownTimer.cancel();
        }
    }

    public static void setTimer(int min) {
        amount = min;
    }

    public static void setMessage(String msg) {
        message = msg;
    }

    public static void setNumber(String num) {
        phone = num;
    }

    public void generateNotification() {

                // This basically taken from developer.android.com
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                getActivity()).setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Rescue Me ALARM")
                .setContentText("Press here to cancel the SOS SMS");

        // Make the notification play the default notification sound:
        Uri alarmSound = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(getActivity(), Activity_C.class);

        // The stack builder object will contain an artificial back stack for the started  
                // Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(getActivity());

        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(Activity_C.class);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);

        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getActivity()
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // mId allows you to update the notification later on.
        mNotificationManager.notify(0, mBuilder.build());
    }
}
Run Code Online (Sandbox Code Playgroud)

这是 fragment_c.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/fragment_c_cancel_alarm_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/fragment_c_cancel_alarm_button" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这是 Activity_C.java 类:

package example.app;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;

public class Activity_C extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_c);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity__c, menu);
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)

这是activity_c.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false">

    <fragment android:name="app.me.rescue.rescuemeapp.Fragment_C"
            android:id="@+id/fragment_c" 
            android:layout_weight="1"
            android:layout_width="0dp" 
            android:layout_height="match_parent" />

 </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这是 AndroidManifest.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.me.rescue.rescuemeapp"
    android:versionCode="1"
    android:versionName="1.0"
    android:launchMode="singleInstance" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="app.me.rescue.rescuemeapp.Activity_A"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="app.me.rescue.rescuemeapp.Activity_B"
            android:label="@string/title_activity_activity__b"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name="app.me.rescue.rescuemeapp.Activity_C"
            android:label="@string/title_activity_activity__c"
            android:screenOrientation="portrait"
            android:launchMode="singleTask">

        </activity>
    </application>

</manifest>
Run Code Online (Sandbox Code Playgroud)

我尝试了其他一些解决方案,例如 从通知Android恢复活动:如何从通知恢复应用程序?,但没有运气,也因为似乎没有人在任何地方使用 Fragments :) 不过我需要。

非常欢迎任何帮助:) 我是一个菜鸟,所以如果你能让你的答案容易理解,我将不胜感激:)

///////////////////////////////

编辑2:

我对此感到尴尬,但我让它工作了,但我真的不知道如何或为什么。我尝试实现不同的解决方案,但最后缺少的部分是本示例对 PendingIntent.getActivity() 的第二个参数的更改:android 挂起意图通知问题(请参阅 U-Ramos 的第二个答案)

我所做的更改仅在 AndroidManifest.xml 文件和 Fragment_C.java 类中的“generateNotification()”方法中:

片段.java:

public void generateNotification() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                getActivity()).setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Rescue Me ALARM")
                .setContentText("Press here to cancel the SOS SMS");

        // Make the notification play the default notification sound:
        Uri alarmSound = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
        mBuilder.setOngoing(true);

        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(getActivity(), Activity_C.class);

        // This somehow makes sure, there is only 1 CountDownTimer going if the notification is pressed:
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        // The stack builder object will contain an artificial back stack for the started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(getActivity());

        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(Activity_C.class);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);

        // Make this unique ID to make sure there is not generated just a brand new intent with new extra values:
        int requestID = (int) System.currentTimeMillis();

        // Pass the unique ID to the resultPendingIntent:
        PendingIntent resultPendingIntent = PendingIntent.getActivity(getActivity(), requestID, resultIntent, 0);

        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getActivity()
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // mId allows you to update the notification later on.
        mNotificationManager.notify(0, mBuilder.build());
    }
Run Code Online (Sandbox Code Playgroud)

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="app.me.rescue.rescuemeapp"
    android:versionCode="1"
    android:versionName="1.0"
    android:launchMode="singleInstance" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />


    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="app.me.rescue.rescuemeapp.Activity_A"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="app.me.rescue.rescuemeapp.Activity_B"
            android:label="@string/title_activity_activity__b"
            android:screenOrientation="portrait">
        </activity>
        <activity
            android:name="app.me.rescue.rescuemeapp.Activity_C"
            android:parentActivityName="app.me.rescue.rescuemeapp.Activity_B"
            android:label="@string/title_activity_activity__c"
            android:screenOrientation="portrait">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="app.me.rescue.rescuemeapp.Activity_B" />            
        </activity>
    </application>

</manifest>
Run Code Online (Sandbox Code Playgroud)

如果有人想发表评论或为什么这样做的原因,欢迎您这样做:)

快乐编码!

///////////////////////////////

编辑 3:

还!如果您希望通知消失,当用户按下它时,只需在 mBuider 对象的实例化下方放入以下代码:

mBuilder.setAutoCancel(true);
Run Code Online (Sandbox Code Playgroud)

就是这样!

Noo*_*Man 0

我让它工作了,但不完全确定为什么。

有关详细信息,请参阅问题中的编辑 1 中所做的更改。

有谁知道为什么现在有效?:)