2017-04-03 85 views
-2

希望你能幫助我在這裏! 我想打開一個開關按鈕,打開推送每日推送通知的功能。我怎麼做?開關按鈕打開通知

開關按鈕在設置片段

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

} 

片段Settings.java 的 「editor.getBoolean」 讓我無法解析錯誤!我能做什麼?

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> 

謝謝!!希望你能幫我!

THE editor.getBoolean GIVES ME can not RESOLVE ERROR !!! 我能做什麼?

+1

我假設你想讓別人做這個而不是你,但是這種方式不行。因此,您需要將某個開關的值保存在某個位置(true爲false),並在顯示通知之前檢查它。如果該值爲真,則顯示它。否則 - 沒有 –

回答

0

您需要保存的地方交換機(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, "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); 
+0

是的,這是應該這樣做,但我怎麼做通知本身? haha –

+0

查看編輯的版本 – TzlilPha

+0

我在哪裏放這段代碼?主要活動? –

1

如果正確理解,這裏的問題不是如何知道如果開關打開或關閉,但有關避免根據開關狀態得到推送通知。

你想避免得到通知,而不是 - 得到通知,並決定是否提出通知。

因此,您需要的是如其他答案中所述保存開關狀態,但另外 - 如果用戶將狀態切換爲OFF,則需要註銷用戶以獲取通知,反之亦然,使用以下內容:

要麼刪除其保存用戶的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"); 
+0

是的,這是應該做的,但我怎麼做通知本身? haha –

+0

如果您要求如何發送/不發送來自服務器端的通知 您需要在此處添加您正在使用哪種服務器端技術(NodeJS,PHP,C#,Java等),然後您將能夠得到協助 - 但這似乎是另一個問題。 – Mercury