切换按钮以打开通知 [英] Switch button to turn on notifications

查看:108
本文介绍了切换按钮以打开通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



切换按钮在设置片段上



我的MainActivity.java:

 公共类MainActivity扩展AppCompatActivity 
实现NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
工具栏工具栏=(工具栏)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);
返回;
}

if(getSupportFragmentManager()。findFragmentById(R.id.content_main)instanceof Article){
((Article)getSupportFragmentManager()。findFragmentById(R.id.content_main ))handleOnBackPress();
返回;
}

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();
休息;
case R.id.nav_Recipes:
fragment = new RecipesMain();
休息;
case R.id.nav_Converter:
fragment = new Converter();
休息;
case R.id.nav_Videos:
fragment = new Videos();
休息;
case R.id.nav_Tracking:
fragment = new Tracking();
休息;
case R.id.nav_TrainerMenu:
fragment = new TrainerMenu();
休息;
case R.id.nav_Settings:
fragment = new Settings();
休息;
case R.id.nav_About:
showDialog();
休息;

}


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());
返回true;
}
private void showDialog()
{
String text2 =< font color =#6774bd>关于SG50 App< / font>;

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

字符串text3 =< font color =#A4A4A4>由Matan Cohen制作的应用程序,如有任何问题,请与我联系。< / font>; //自定义消息
builder .setMessage(Html.fromHtml(文字3));

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

}

片段Settings.java editor.getBoolean给我无法解决错误!我该怎么办?

 公共类设置扩展片段{

@Nullable
@Override
public查看onCreateView(LayoutInflater inflater,@ Nullable ViewGroup容器,@ Nullable Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_settings,container,false);

}


@Override
public void onViewCreated(View view,@ Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
getActivity()。setTitle(הגדרות);

切换aSwitch =(切换)getView()。findViewById(R.id.dailyTipSwitch);
SharedPreferences sharedPreferences = getActivity()。getSharedPreferences(key,0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(switchValue,aSwitch.isChecked());
editor.apply();
boolean showNotifications = editor.getBoolean(key,false);
if(aSwitch.isChecked()!= showNotifications){
editor.putBoolean(key,!showNotifications).apply();
}
else {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,19);
calendar.set(Calendar.MINUTE,27);
Intent intent = new Intent(getActivity()。getApplicationContext(),NotificationReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity()。getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager =(AlarmManager)getActivity()。getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(alarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}


}

}

Notification_Reciever.java

 公共类NotificationReciever扩展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 =垂直
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 =horizo​​ntal
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>

谢谢!!希望你能帮助我!



编辑器.getBoolean让我无法解决错误!
我能做什么?

解决方案

您需要在某处保存交换机的值(SQLite或SharedPreferences)并检查它是否是当前的切换值,而不是更改保持位置的值在交换机上选中或取消选中



这个是如何创建SharedPreferences并输入值:

  SharedPreferences sharedPreferences = getSharedPreferences(key,0); 
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(switchValue,aSwitch.isChecked());
editor.apply();

这是检查SharedPreferences值并更改它的方式:

  Boolean showNotifications = editor.getBoolean(key,false); 
if(aSwitch.isChecked()!= showNotifications){
editor.putBoolean(key,!showNotifications).apply();
}

如果要通知通知,则应检查SharedPreferences值:

  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, 通知标题))
.setContentIntent(contentPendingIntent)
.setDeleteIntent(deletePendingIntent)
.setAutoCancel(true);

//通知通知
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);


hope you could help me here! I want to make a switch button that turns on a function of push daily push notification. how do I do that?

the switch button is on the Settings fragment

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

}

fragment Settings.java the "editor.getBoolean" gives me cannot resolve error!! what can I do?:

public class Settings extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_settings, container, false);

}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("הגדרות");

    Switch aSwitch = (Switch) getView().findViewById(R.id.dailyTipSwitch);
    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("key", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("switchValue", aSwitch.isChecked());
    editor.apply();
    boolean showNotifications = editor.getBoolean("key",false);
            if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }
            else {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,19);
                calendar.set(Calendar.MINUTE,27);
                Intent intent = new Intent(getActivity().getApplicationContext(),NotificationReciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
                alarmManager.setRepeating(alarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
            }


    }

}

Notification_Reciever.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>

Thank you!! Hope you can help me!

THE editor.getBoolean GIVES ME CANNOT RESOLVE ERROR!!! what Can I do???

解决方案

You will need to save the value of the switch somewhere(SQLite or SharedPreferences) and check if it is the current switch value, than change the value in the place you keep it on switch checked or unchecked

this is how you create SharedPreferences and put in a value:

 SharedPreferences sharedPreferences = getSharedPreferences("key", 0);
 SharedPreferences.Editor editor = sharedPreferences.edit();
 editor.putBoolean("switchValue", aSwitch.isChecked());
 editor.apply();

this is how you check the SharedPreferences value and change it:

 Boolean showNotifications = editor.getBoolean("key",false);
 if (aSwitch.isChecked() != showNotifications) {
                editor.putBoolean("key",!showNotifications).apply();
            }

where you want to notify a notification you should check the SharedPreferences value:

Boolean showNotifications = editor.getBoolean("key",false);

edited This is how you fire a notifications:

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 you can give to every notification. you can set delete intent and content intent(if the user clicks on the notification)

Man you need to use the same "key". like that:

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

这篇关于切换按钮以打开通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆