Java 打开通知的开关按钮

Java 打开通知的开关按钮,java,android,android-fragments,push-notification,Java,Android,Android Fragments,Push Notification,希望你能在这里帮助我! 我想做一个开关按钮,打开每日推送通知功能。我该怎么做 开关按钮位于设置片段上 My MainActivity.java: public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @Override protected void onCreate(Bundle savedInstanceState

希望你能在这里帮助我! 我想做一个开关按钮,打开每日推送通知功能。我该怎么做

开关按钮位于设置片段上

My MainActivity.java:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    displayView(R.id.nav_home);



}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
        return;
    }

    if (getSupportFragmentManager().findFragmentById(R.id.content_main) instanceof Article) {
        ((Article) getSupportFragmentManager().findFragmentById(R.id.content_main)).handleOnBackPress();
        return;
    }

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        displayView(R.id.nav_home);
    } else {
        super.onBackPressed();

    }
}

private void displayView(int itemId) {
    Fragment fragment = null;

    switch (itemId) {
        case R.id.nav_home:
            fragment = new Article();
            break;
        case R.id.nav_Recipes:
            fragment = new RecipesMain();
            break;
        case R.id.nav_Converter:
            fragment = new Converter();
            break;
        case R.id.nav_Videos:
            fragment = new Videos();
            break;
        case R.id.nav_Tracking:
            fragment = new Tracking();
            break;
        case R.id.nav_TrainerMenu:
            fragment = new TrainerMenu();
            break;
        case R.id.nav_Settings:
            fragment = new Settings();
            break;
        case R.id.nav_About:
            showDialog();
            break;

    }


    if (fragment != null) {
        final Fragment finalFragment = fragment;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                        .replace(R.id.content_main, finalFragment)
                        .commit();
            }
        }, 0);
            }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }




@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    displayView(item.getItemId());
    return true;
}
private void showDialog()
{
    String text2 = "<font color=#6774bd>About SG50 App</font>";

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "<font color=#A4A4A4>App made by Matan Cohen , Please contact me for any questions.</font>";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            Toast toast = Toast.makeText(getApplicationContext(), "תודה על שימוש", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });

    builder.show();
 }

}
通知_receiver.java

public class NotificationReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

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

    Intent repeatingIntent = new Intent(context,MainActivity.class);
    repeatingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeatingIntent,PendingIntent.FLAG_UPDATE_CURRENT);



    NotificationCompat.Builder mBuilder = new
            NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(new NotificationCompat.BigTextStyle().bigText("בוקר טוב אלוף! תאכל ותשתה טוב!"))
            .setContentText(context.getString(R.string.NotificationText))
            .setContentTitle(context.getString(R.string.GoodMorningNotification))
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);

    notificationManager.notify(100, mBuilder.build());
    }
}
fragemnt_settings.XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="30dp"
android:paddingBottom="30dp"
android:paddingTop="30dp"
android:paddingRight="30dp">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="left" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right"
        android:text="@string/daily_tip"
        android:textSize="20sp"/>
</LinearLayout>


</LinearLayout>

谢谢!!希望你能帮助我

editor.getBoolean给了我无法解决的错误!!!
我能做些什么?

您需要将开关的值保存在某个位置(SQLite或SharedReferences)并检查它是否为当前开关值,而不是在开关处于选中或未选中状态时更改该值

以下是创建SharedReference并输入值的方式:

 SharedPreferences sharedPreferences = getSharedPreferences("key", 0);
 SharedPreferences.Editor editor = sharedPreferences.edit();
 editor.putBoolean("switchValue", aSwitch.isChecked());
 editor.apply();
以下是检查SharedReferences值并对其进行更改的方式:

 Boolean showNotifications = editor.getBoolean("key",false);
 if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
如果要通知通知,应检查SharedReferences值:

Boolean showNotifications = editor.getBoolean("key",false);
已编辑这是您触发通知的方式:

NotificationCompat.Builder mBuilder = new  
NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.your_drawable)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("notification text"))
                    .setContentText(notificationToNotify.getText())
                    .setContentTitle(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "notification title"))
                    .setContentIntent(contentPendingIntent)
                    .setDeleteIntent(deletePendingIntent)
                    .setAutoCancel(true);

            //notify the Notification
            mNotifyMgr.notify(notification_id, mBuilder.build());
notification_id-可以为每个通知提供的int id。 您可以设置删除意图和内容意图(如果用户单击通知)

伙计,你需要用同样的“钥匙”。就像这样:

SharedPreferences sharedPreferences = 
getActivity().getSharedPreferences("key", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("**switchValue**", aSwitch.isChecked());
editor.apply();
boolean showNotifications = 
editor.getBoolean("**switchValue**",false);

如果理解正确,这里的问题不是如何知道开关是打开还是关闭,而是如何避免根据开关状态获取推送通知

您希望避免收到通知而不收到-收到通知并决定是否提交

因此,您需要的是保存其他答案中提到的切换状态,但除此之外-如果用户将状态切换为“关闭”,则需要使用以下命令注销用户获取通知的权限,反之亦然:

从保存用户FCM令牌的服务器中删除令牌:

// Remove user from notification messages
InstanceID.getInstance(context).deleteInstanceID();

// Register user back to get notifications
FirebaseInstanceId.getInstance().getToken() // This will call the onTokenRefresh() method which will call your implementation that calls your FCM server and update the new user's token
或者如果此用户已注册到特定的通知主题

// Unregister him from the topic
FirebaseMessaging.getInstance().unsubscribeToTopic("news");

// Register him back in case switch is on
FirebaseMessaging.getInstance().subscribeToTopic("news");
boolean showNotifications=editor.getBoolean(“key”,false);


我假设你希望有人来代替你做这件事,但这样不行。因此,您需要将开关的值保存在某个位置(true或false),并在显示通知之前进行检查。如果该值为true,则显示它。否则-不,这是应该做的,但我怎么做通知本身?哈哈,如果你问如何从服务器端发送/不发送通知,你需要在这里添加你正在使用的服务器端技术(NodeJS、PHP、C#、Java等),然后你将能够得到帮助-但这似乎是另一个问题。是的,这应该可以做到,但我如何制作通知本身?HahayYou可以检查MainActivity的每个onResume或onCreate,以及用户是否需要通知。真是太棒了。非常感谢你,我会试试看,稍后再给你确认!嘿,无法获取“editor.getBoolean”它说它无法解决在片段中执行它的问题。您是否编写了:SharedReferences SharedReferences=GetSharedReferences(“键”,0);SharedReferences.Editor=SharedReferences.edit();在你使用编辑器之前?
// Unregister him from the topic
FirebaseMessaging.getInstance().unsubscribeToTopic("news");

// Register him back in case switch is on
FirebaseMessaging.getInstance().subscribeToTopic("news");
boolean showNotifications = sharedPreferences.getBoolean("key",false);