gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:26:52 31 4
gpt4 key购买 nike

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

我的 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());
}
}

这是 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>

这是 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;
}

}

这是 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>

这是 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>

我尝试了一些其他的解决方案,比如 resuming an activity from a notificationAndroid: How to resume an App from a Notification? ,但没有运气,也因为似乎没有人在任何地方使用 Fragments :) 不过我需要这样做。

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

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

编辑 2:

我对此感到尴尬,但我让它工作了,但我真的不知道如何或为什么。我尝试实现不同的解决方案,但最后缺少的部分是此示例对 PendingIntent.getActivity() 的第二个参数的更改:android pending intent notification problem (参见 U-Ramos 的第二个回答)

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

fragment .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());
}

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>

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

编码愉快!

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

编辑 3:

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

mBuilder.setAutoCancel(true);

就是这样!

最佳答案

在我看来,您应该始终做的第一件事是覆盖 Activity 中的 onSaveInstanceState 和 onRestoreInstanceState,这样您就可以在 Activity 停止后保存 Activity 状态,并在再次恢复 Activity 后将其恢复原状。

完成后您可以做几件事,不好的是从传入的 Intent 中保存触发此 Activity 的 Activity 并覆盖 onBackPressed 以返回到上一个 Activity 。

更好更简单的方法是添加 resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);如所述here

关于Android:如何从通知中恢复 fragment 类。不创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20540555/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com