Java tutorial
/** * Copyright (C) 2016 Hyphenate Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nxt.yn.app.ui; import android.Manifest; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.LocalBroadcastManager; import android.view.ContextMenu; import android.view.Display; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.hyphenate.EMCallBack; import com.hyphenate.EMContactListener; import com.hyphenate.EMMessageListener; import com.hyphenate.chat.EMClient; import com.hyphenate.chat.EMConversation; import com.hyphenate.chat.EMMessage; import com.hyphenate.easeui.utils.EaseCommonUtils; import com.hyphenate.easeui.utils.ZPreferenceUtils; import com.hyphenate.util.EMLog; import com.jaeger.library.StatusBarUtil; import com.nxt.yn.app.MyApplication; import com.nxt.yn.app.R; import com.nxt.yn.app.db.InviteMessgeDao; import com.nxt.yn.app.db.UserDao; import com.nxt.yn.app.domain.InviteMessage; import com.nxt.yn.app.ui.fragment.ForumFragment; import com.nxt.yn.app.ui.fragment.MeFragment; import com.nxt.yn.app.ui.fragment.NewHomeFragment; import com.nxt.yn.app.util.Constant; import com.nxt.yn.app.util.DemoHelper; import com.umeng.analytics.MobclickAgent; import java.util.ArrayList; import java.util.List; public class MainActivity extends FragmentActivity { protected static final String TAG = "MainActivity"; // ?textview private TextView unreadLabel; // textview private TextView unreadAddressLable; private Button[] mTabs; // private conversationListFragment conversationListFragment; // private ChatAllHistoryFragment conversationListFragment; private Fragment[] fragments; private int index; // ?fragmentindex private int currentTabIndex; // ? public boolean isConflict = false; // ? private boolean isCurrentAccountRemoved = false, islogin = false; private long exitTime; private NewHomeFragment znjFragment; private ForumFragment newsFragment; private MeFragment meFragment; private String permissionInfo; private final int SDK_PERMISSION_REQUEST = 127; /** * ?? */ public boolean getCurrentAccountRemoved() { return isCurrentAccountRemoved; } @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); MyApplication.getInstance().addActivity(this); if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) { // ??home???appcrash // fragment?? DemoHelper.getInstance().logout(true, null); finish(); startActivity(new Intent(this, LoginActivity.class)); return; } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) { // T??home???appcrash // fragment?? finish(); startActivity(new Intent(this, LoginActivity.class)); return; } setContentView(R.layout.em_activity_main); StatusBarUtil.setColor(this, getResources().getColor(R.color.title_color)); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // setTranslucentStatus(true); // } // // SystemBarTintManager tintManager = new SystemBarTintManager(this); // tintManager.setStatusBarTintEnabled(true); // tintManager.setStatusBarTintResource(R.color.top_bar_color); initView(); znjFragment = new NewHomeFragment(); newsFragment = new ForumFragment(); meFragment = new MeFragment(); //umeng api MobclickAgent.updateOnlineConfig(this); //UmengUpdateAgent.setUpdateOnlyWifi(false); //UmengUpdateAgent.update(this if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) { showConflictDialog(); } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) { showAccountRemovedDialog(); } inviteMessgeDao = new InviteMessgeDao(this); userDao = new UserDao(this); conversationListFragment = new ConversationListFragment(); System.out.println("conversationListFragment init refresh-------------->"); fragments = new Fragment[] { znjFragment, newsFragment, conversationListFragment, meFragment }; // fragment //setfragment(homeFragment); getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, znjFragment) .add(R.id.fragment_container, newsFragment).hide(newsFragment).show(znjFragment).commit(); //localdemohelper??? registerBroadcastReceiver(); EMClient.getInstance().contactManager().setContactListener(new MyContactListener()); // registerInternalDebugReceiver(); EMLog.d(TAG, "width:" + getScreenWidth(this) + " height:" + getScreenHeight(this)); } public static int getScreenWidth(Context context) { WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); return display.getWidth(); } //?? public static int getScreenHeight(Context context) { WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); return display.getHeight(); } /** * ? */ private void initView() { // findViewById(R.id.layout_main_bottom).setBackgroundColor(ZPreferenceUtils.getPrefInt(Constant.SKIN_COLOR, getResources().getColor(R.color.title_color))); islogin = ZPreferenceUtils.getPrefBoolean(Constant.ISLOGIN, false); unreadLabel = (TextView) findViewById(R.id.unread_msg_number); ////unreadAddressLable = (TextView) findViewById(R.id.unread_address_number); mTabs = new Button[4]; mTabs[0] = (Button) findViewById(R.id.btn_znj); mTabs[1] = (Button) findViewById(R.id.btn_news); mTabs[2] = (Button) findViewById(R.id.btn_comm); mTabs[3] = (Button) findViewById(R.id.btn_me); // tab? mTabs[0].setSelected(true); } /** * button * * @param view */ public void onTabClicked(View view) { switch (view.getId()) { case R.id.btn_znj: index = 0; break; case R.id.btn_comm: // if(!islogin){ // // startActivity(new Intent(this,LoginActivity.class)); // }else{ index = 2; //} break; case R.id.btn_news: index = 1; break; case R.id.btn_me: index = 3; break; } if (currentTabIndex != index) { FragmentTransaction trx = getSupportFragmentManager().beginTransaction(); trx.hide(fragments[currentTabIndex]); if (!fragments[index].isAdded()) { trx.add(R.id.fragment_container, fragments[index]); } trx.show(fragments[index]).commit(); } // setfragment(fragments[index]); mTabs[currentTabIndex].setSelected(false); // ?tab? mTabs[index].setSelected(true); currentTabIndex = index; } private void setfragment(Fragment fragment) { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit(); } EMMessageListener messageListener = new EMMessageListener() { @Override public void onMessageReceived(List<EMMessage> messages) { // ??? for (EMMessage message : messages) { DemoHelper.getInstance().getNotifier().onNewMsg(message); } refreshUIWithMessage(); } @Override public void onCmdMessageReceived(List<EMMessage> messages) { } @Override public void onMessageReadAckReceived(List<EMMessage> messages) { } @Override public void onMessageDeliveryAckReceived(List<EMMessage> message) { } @Override public void onMessageChanged(EMMessage message, Object change) { } }; private void refreshUIWithMessage() { runOnUiThread(new Runnable() { public void run() { // bottom bar? updateUnreadLabel(); if (currentTabIndex == 1) { // ?????? if (conversationListFragment != null) { System.out.println("conversationListFragment refresh-------------->"); conversationListFragment.refresh(); } } } }); } private void registerBroadcastReceiver() { broadcastManager = LocalBroadcastManager.getInstance(this); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED); intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateUnreadLabel(); // updateUnreadAddressLable(); if (currentTabIndex == 1) { System.out.println("conversationListFragment refresh-------------->"); // ?????? if (conversationListFragment != null) { conversationListFragment.refresh(); } // } else if (currentTabIndex == 1) { //// if(conversationListFragment != null) { //// conversationListFragment.refresh(); //// } } String action = intent.getAction(); if (action.equals(Constant.ACTION_GROUP_CHANAGED)) { if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) { GroupsActivity.instance.onResume(); } } } }; broadcastManager.registerReceiver(broadcastReceiver, intentFilter); } public class MyContactListener implements EMContactListener { @Override public void onContactAdded(String username) { } @Override public void onContactDeleted(final String username) { runOnUiThread(new Runnable() { public void run() { if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.toChatUsername != null && username.equals(ChatActivity.activityInstance.toChatUsername)) { String st10 = getResources().getString(R.string.have_you_removed); Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_SHORT).show(); ChatActivity.activityInstance.finish(); } } }); } @Override public void onContactInvited(String username, String reason) { } @Override public void onContactAgreed(String username) { } @Override public void onContactRefused(String username) { } } private void unregisterBroadcastReceiver() { broadcastManager.unregisterReceiver(broadcastReceiver); } @Override protected void onDestroy() { super.onDestroy(); if (conflictBuilder != null) { conflictBuilder.create().dismiss(); conflictBuilder = null; } unregisterBroadcastReceiver(); try { unregisterReceiver(internalDebugReceiver); } catch (Exception e) { } } /** * ? */ public void updateUnreadLabel() { int count = getUnreadMsgCountTotal(); if (count > 0) { unreadLabel.setText(String.valueOf(count)); unreadLabel.setVisibility(View.VISIBLE); } else { unreadLabel.setVisibility(View.INVISIBLE); } } /** * ? */ public void updateUnreadAddressLable() { runOnUiThread(new Runnable() { public void run() { int count = getUnreadAddressCountTotal(); if (count > 0) { // //unreadAddressLable.setText(String.valueOf(count)); //unreadAddressLable.setVisibility(View.VISIBLE); } else { //unreadAddressLable.setVisibility(View.INVISIBLE); } } }); } /** * ?? * * @return */ public int getUnreadAddressCountTotal() { int unreadAddressCountTotal = 0; unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount(); return unreadAddressCountTotal; } /** * ?? * * @return */ public int getUnreadMsgCountTotal() { int unreadMsgCountTotal = 0; int chatroomUnreadMsgCount = 0; unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount(); for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) { if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount(); } return unreadMsgCountTotal - chatroomUnreadMsgCount; } private InviteMessgeDao inviteMessgeDao; private UserDao userDao; /** * ???? * * @param msg */ private void notifyNewIviteMessage(InviteMessage msg) { saveInviteMsg(msg); // ??? DemoHelper.getInstance().getNotifier().viberateAndPlayTone(null); // bottom bar? updateUnreadAddressLable(); // ??ui if (currentTabIndex == 1) System.out.println("conversationListFragment refresh-------------->"); if (conversationListFragment != null) conversationListFragment.refresh(); } /** * ?msg * * @param msg */ private void saveInviteMsg(InviteMessage msg) { // ?msg inviteMessgeDao.saveMessage(msg); //? inviteMessgeDao.saveUnreadMessageCount(1); } @Override protected void onResume() { super.onResume(); if (!isConflict && !isCurrentAccountRemoved) { updateUnreadLabel(); updateUnreadAddressLable(); } // unregister this event listener when this activity enters the // background DemoHelper sdkHelper = DemoHelper.getInstance(); sdkHelper.pushActivity(this); EMClient.getInstance().chatManager().addMessageListener(messageListener); } @Override protected void onStop() { EMClient.getInstance().chatManager().removeMessageListener(messageListener); DemoHelper sdkHelper = DemoHelper.getInstance(); sdkHelper.popActivity(this); super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("isConflict", isConflict); outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved); super.onSaveInstanceState(outState); } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { // moveTaskToBack(false); // return true; // } // return super.onKeyDown(keyCode, event); // } private android.app.AlertDialog.Builder conflictBuilder; private android.app.AlertDialog.Builder accountRemovedBuilder; private boolean isConflictDialogShow; private boolean isAccountRemovedDialogShow; private BroadcastReceiver internalDebugReceiver; private ConversationListFragment conversationListFragment; private BroadcastReceiver broadcastReceiver; private LocalBroadcastManager broadcastManager; /** * ??dialog */ private void showConflictDialog() { isConflictDialogShow = true; DemoHelper.getInstance().logout(false, null); String st = getResources().getString(R.string.Logoff_notification); if (!MainActivity.this.isFinishing()) { // clear up global variables try { if (conflictBuilder == null) conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this); conflictBuilder.setTitle(st); conflictBuilder.setMessage(R.string.connect_conflict); conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); conflictBuilder = null; finish(); MyApplication.getInstance().cleanspf(); Intent intent = new Intent(MainActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); conflictBuilder.setCancelable(false); conflictBuilder.create().show(); isConflict = true; } catch (Exception e) { EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage()); } } } /** * ??dialog */ private void showAccountRemovedDialog() { isAccountRemovedDialogShow = true; DemoHelper.getInstance().logout(false, null); String st5 = getResources().getString(R.string.Remove_the_notification); if (!MainActivity.this.isFinishing()) { // clear up global variables try { if (accountRemovedBuilder == null) accountRemovedBuilder = new android.app.AlertDialog.Builder(MainActivity.this); accountRemovedBuilder.setTitle(st5); accountRemovedBuilder.setMessage(R.string.em_user_remove); accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); accountRemovedBuilder = null; finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); accountRemovedBuilder.setCancelable(false); accountRemovedBuilder.create().show(); isCurrentAccountRemoved = true; } catch (Exception e) { EMLog.e(TAG, "---------color userRemovedBuilder error" + e.getMessage()); } } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) { showConflictDialog(); } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) { showAccountRemovedDialog(); } } /** * ?? */ private void registerInternalDebugReceiver() { internalDebugReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { DemoHelper.getInstance().logout(false, new EMCallBack() { @Override public void onSuccess() { runOnUiThread(new Runnable() { public void run() { // ?? finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); } @Override public void onProgress(int progress, String status) { } @Override public void onError(int code, String message) { } }); } }; IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug"); registerReceiver(internalDebugReceiver, filter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); //getMenuInflater().inflate(R.menu.context_tab_contact, menu); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { if ((System.currentTimeMillis() - exitTime) > 2000) { // Snackbar snackbar=Snackbar.make(getCurrentFocus(), R.string.exit_notice, Snackbar.LENGTH_SHORT); // TextView textView= (TextView) snackbar.getView().findViewById(R.id.snackbar_text); // textView.setGravity(Gravity.CENTER); // snackbar.getView().setBackgroundColor(getResources().getColor(ZPreferenceUtils.getPrefInt(com.nxt.ott.util.Constant.SKIN_COLOR, getResources().getColor(R.color.title_color)))); // snackbar.show(); Toast.makeText(getApplicationContext(), getString(R.string.exit_notice), Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { MyApplication.getInstance().exit(); finish(); } return true; } return super.onKeyDown(keyCode, event); } @TargetApi(23) private void getPersimmions() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ArrayList<String> permissions = new ArrayList<String>(); /*** * ??????? */ // ?? if (checkSelfPermission( Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissions.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (checkSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION); } /* * ??????????()????? */ // ?? if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n"; } // ????? if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) { permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n"; } if (permissions.size() > 0) { requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST); } } } @TargetApi(23) private boolean addPermission(ArrayList<String> permissionsList, String permission) { if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // ??,,? if (shouldShowRequestPermissionRationale(permission)) { return true; } else { permissionsList.add(permission); return false; } } else { return true; } } @TargetApi(23) @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { // TODO Auto-generated method stub super.onRequestPermissionsResult(requestCode, permissions, grantResults); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } }