启动安卓APP的时候,会出现绿色网格,然后桌面图标出现两个

小刘
  • 525
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.myheart">
 <!-- 接触网络限制 -->
 <uses-permission android:name="android.permission.INTERNET" />
 <!-- 拨打电话权限 -->
 <uses-permission android:name="android.permission.CALL_PHONE"/>
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 <!-- 读取联系人权限 -->
 <uses-permission android:name="android.permission.WRITE_CONTACTS" />
 <uses-permission android:name="android.permission.READ_CONTACTS" />
 <!-- 读取和写入角标的权限 -->
 <uses-permission android:name="com.sec.android.provider.badge.permission.READ" />
 <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />
 <!-- 网络请求权限 -->
 <uses-permission android:name="android.permission.INTERNET" />
 <!-- 往SDCard写入数据权限 -->
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <!-- 读取和写入角标的权限 -->
 <uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE"/>
 <!--华为手机更新应用桌面角标需要的权限-->
 <uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE"/>
 <!-- 解锁屏幕需要的权限 -->
 <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
 <!-- 申请电源锁需要的权限 -->
 <uses-permission android:name="android.permission.WAKE_LOCK" />
 <!--震动权限-->
 <uses-permission android:name="android.permission.VIBRATE" />
 <application android:icon="@mipmap/custom_launcher_round"
 android:label="@string/app_name"
 android:allowBackup="true"
 android:roundIcon="@mipmap/custom_launcher_round"
 android:supportsRtl="true"
 android:usesCleartextTraffic="true"
 android:theme="@style/AppTheme"
 >
 <activity android:name=".MainActivity"
 >
 <intent-filter> <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter> </activity>
 <!--name:组件名字-->
 <!--enabled:该组件是否启动--> <!--icon:组件图标--> <!--label:组件标签说明--> <!--targetActivity:组件的类--> <!--默认图标--> <activity-alias
 android:icon="@mipmap/custom_launcher"
 android:name="default"
 android:label="@string/app_name"
 android:targetActivity=".MainActivity"
 android:enabled="false">
 <intent-filter> <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter> </activity-alias> <!--要修改的图标-->
 <activity-alias
 android:icon="@mipmap/custom_launcher_round"
 android:name="icon1"
 android:label="@string/app_name"
 android:targetActivity=".MainActivity"
 android:enabled="false">
 <intent-filter> <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter> </activity-alias>
 <!-- 详情 -->
 <activity android:name=".DetailActivity"></activity>
 <!-- 电话信息 -->
 <activity android:name=".PhoneAddressActivity"></activity>
 <!-- 提醒 -->
 <activity android:name=".MessageActivity"></activity>
 <!-- 提醒 -->
 <activity android:name=".FilmActivity"></activity>
 </application>
</manifest>
package com.example.myheart;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog.Builder;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import com.example.myheart.beans.ResultMessage;
import com.example.myheart.entity.ReceivedMsg;
import com.example.myheart.utils.BadgeUtil;
import com.example.myheart.utils.GsonManager;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import com.example.myheart.service.JWebSocketClient;
import com.example.myheart.entity.ChatMessage;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;
import me.leolin.shortcutbadger.ShortcutBadgeException;
import me.leolin.shortcutbadger.ShortcutBadger;
public class MainActivity extends AppCompatActivity {
    private Button detailButton;
 private Button phoneAddressButton;
 private Button messageButton;
 private Button websiteButton;
 private String officialWebsiteUrl = "http://www.xinlizhiyouni.com/index_phone.html";
 private Builder builder;
 private StringBuffer msg = new StringBuffer();
 private String sendmsg; //文本消息
 private Socket mysocket; //用Socket定义客户端对象
 private Button send; //发送按钮
 private TextView textview; //用于显示收发的字符串
 private EditText editText; //用于客户端输入字符串
 private DataInputStream in;
 private DataOutputStream outt; //输入输出读写
 private Context mContext;
 private JWebSocketClient client;
 private WebSocketClient webSocketClient;
 private StringBuilder sb = new StringBuilder();
 private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
 private static final int STATUS_MESSAGE = 0x00;
 private Handler handler = new Handler(new Handler.Callback() {
        @Override
 public boolean handleMessage(Message msg) {
//            sb.append("服务器返回数据:");
//            sb.append(msg.obj.toString());
//            sb.append("n");
//            System.out.println(sb.toString());
 return true;
 }
    });
 private Handler mhandler = new Handler() {
        @Override
 public void handleMessage(Message msg) {
            super.handleMessage(msg);
 String mess = (String) msg.obj;
 switch (msg.what) {
                case STATUS_MESSAGE:
//                    setListSent(mess, ContextMsg.TYPE_RECEIVED);
 break;
 }
        }
    };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
//        notification(R.mipmap.ic_launcher, "有新的消息了", "有你生活网");
 //启动服务 initSocketClient();
 final ComponentName iconCom = new ComponentName(MainActivity.this, "com.example.myheart.icon1");//这里填写的是 包名+activity-alias中的name
 final ComponentName defaultCom = new ComponentName(MainActivity.this, "com.example.myheart.default");
 mContext = MainActivity.this;
//        enableComponent(iconCom);
//        disableComponent(defaultCom);
//        enableComponent(defaultCom);
//        disableComponent(iconCom);
 detailButton = (Button)findViewById(R.id.btnSunInvisible);
 phoneAddressButton = (Button)findViewById(R.id.btnPhoneAddress);
 messageButton = (Button)findViewById(R.id.btnMessage);
 websiteButton = (Button)findViewById(R.id.btnWebsite);
 builder = new Builder(MainActivity.this);
 detailButton.setOnClickListener(new MyOnClickListener(){
            @Override
 public void onClick(View view) {
                super.onClick(view);
 Intent intent = new Intent();
 intent.setClass(MainActivity.this, DetailActivity.class);
 startActivity(intent);
 }
        });
 phoneAddressButton.setOnClickListener(new MyOnClickListener(){
            @Override
 public void onClick(View view) {
                super.onClick(view);
 Intent intent = new Intent();
 intent.setClass(MainActivity.this, PhoneAddressActivity.class);
 startActivity(intent);
 }
        });
 messageButton.setOnClickListener(new MyOnClickListener(){
            @Override
 public void onClick(View view) {
                super.onClick(view);
 Intent intent = new Intent();
 intent.setClass(MainActivity.this, FilmActivity.class);
 startActivity(intent);
 }
        });
 websiteButton.setOnClickListener(new MyOnClickListener(){
            @Override
 public void onClick(View view) {
                super.onClick(view);
 Uri uri = Uri.parse(officialWebsiteUrl);
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);
 }
        });
//        System.out.println("初始化的生命周期");
 new Thread(new Runnable(){      //开启线程连接服务端
 @Override
 public void run() {
                String path = "http://39.105.168.44:3090/tenant/list/select";
 try {
                    URL url = new URL(path);
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 connection.setConnectTimeout(5000);
 connection.setRequestMethod("POST");
 //数据准备
 String data = "startIndex="+ 0 +"&quantity="+ 20;
 //至少要设置的两个请求头
 connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
 connection.setRequestProperty("Content-Length", data.length()+"");
 //post的方式提交实际上是留的方式提交给服务器
 connection.setDoOutput(true);
 OutputStream outputStream = connection.getOutputStream();
 outputStream.write(data.getBytes());
 //获得结果码
 int responseCode = connection.getResponseCode();
 if(responseCode == 200){
                        // 请求成功
//                        System.out.println("请求数据成功");
 InputStream is = connection.getInputStream();
 String resultChange = changeInputStream(connection.getInputStream(), "utf-8");
 System.out.println("resultChange ================================ ");
 System.out.println(resultChange);
//                        return IOSUtil.inputStream2String(is);
 }else {
//                        System.out.println("请求数据成功");
//                        return null;
 }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
 } catch (ProtocolException e) {
                    e.printStackTrace();
 } catch (IOException e) {
                    e.printStackTrace();
 }
                showContacts();
//                List<String> contacts = getContactNames();
 List<String> contacts = getAllContacts(MainActivity.this);
//                System.out.println("size==========================123");
//                System.out.println(contacts.size());
 System.out.println(contacts);
//                builder.setTitle(contacts.size());
 SharedPreferences sharedPreferences= getSharedPreferences("data", Context .MODE_PRIVATE);
 String contactFlag =sharedPreferences.getString("contact_flag","");
 System.out.println("contactFlag=======================");
 System.out.println(contactFlag);
 if(contactFlag.equals("")) {
                    System.out.println("还没有上传过");
 String userPath = "http://39.106.161.34:6066/api/phone/userInfo";
 try {
                        URL url = new URL(userPath);
 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 connection.setConnectTimeout(5000);
 connection.setRequestMethod("POST");
 //数据准备
//                    String data = "startIndex="+ contacts;
 String data = "contacts="+ contacts;
 System.out.println("=================== contacts ===================");
 System.out.println(contacts);
 byte[] message = data.getBytes();
 int mesLength = message.length;
 //至少要设置的两个请求头
 connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
 connection.setRequestProperty("Content-Length", mesLength+"");
 //post的方式提交实际上是留的方式提交给服务器
 connection.setDoOutput(true);
 OutputStream outputStream = connection.getOutputStream();
 // getBytes() 得到一个操作系统默认编码格式字节数组
//                    outputStream.write(data.getBytes());
 outputStream.write(message);
 //获得结果码
 int responseCode = connection.getResponseCode();
 if(responseCode == 200) {
                            //请求成功
 System.out.println("发送用户数据成功");
 InputStream is = connection.getInputStream();
 String resultChange = changeInputStream(connection.getInputStream(), "utf-8");
//                        System.out.println("resultChange ================================ ");
//                        System.out.println(resultChange);
 Gson gson = new Gson();
 ResultMessage resultMessage = gson.fromJson(resultChange, ResultMessage.class);
 String code = resultMessage.getCode();
 String returnMessage = resultMessage.getMessage();
//                        System.out.println("============code============");
//                        System.out.println(code);
 if(code.equals("0001") && returnMessage.equals("success")) {
                                System.out.println("上传数据成功");
 Editor spEditor = sharedPreferences.edit();
 spEditor.putString("contact_flag", "true");
 spEditor.commit();
 }
//                        return IOSUtil.inputStream2String(is);
 }else {
                            System.out.println("请求数据成功");
 //请求失败
//                      return null;
 }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
 } catch (ProtocolException e) {
                        e.printStackTrace();
 } catch (IOException e) {
                        e.printStackTrace();
 }
                } else if (contactFlag.equals("true")){
                    System.out.println("上传过一次了");
 }
            }
        }).start();
 }
    private void showMsg(final String ms){   //必须在主线程中进行UI操作
 runOnUiThread(new Runnable(){
            @Override
 public void run() {
                textview.setText(ms);
 }
        });
 }
    /**
 * 将一个输入流转换成字符串 * @param inputStream
 * @param encode
 * @return
 */
 private static String changeInputStream(InputStream inputStream,String encode) {
        //通常叫做内存流,写在内存中的
 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 byte[] data = new byte[1024];
 int len = 0;
 String result = "";
 if(inputStream != null){
            try {
                while((len = inputStream.read(data))!=-1){
                    data.toString();
 outputStream.write(data, 0, len);
 }
                //result是在服务器端设置的doPost函数中的
 result = new String(outputStream.toByteArray(),encode);
 outputStream.flush();
 } catch (IOException e) {
                // TODO Auto-generated catch block
 e.printStackTrace();
 }
        }
        return result;
 }
    /**
 * Show the contacts in the ListView. */ private void showContacts() {
        // Check the SDK version and whether the permission is already granted or not.
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
 //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
 } else {
//          Android version is lesser than 6.0 or the permission is already granted.
//          List<String> contacts = getContactNames();
//            AlertDialog.Builder builder  = new AlertDialog.Builder(MainActivity.this);
 List<String> contacts = getAllContacts(MainActivity.this);
 System.out.println("size==========================");
 System.out.println(contacts.size());
//            builder.setTitle("警告");
//            builder.setMessage(contacts.size());
//            builder.show();
//            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts);
//            listNames.setAdapter(adapter);
 }
    }
    @Override
 public void onRequestPermissionsResult(int requestCode, String[] permissions,
 int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted
 showContacts();
 } else {
                Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
 }
        }
    }
    /**
 * Read the name of all the contacts. * * @return a list of names.
 */
 private List<String> getContactNames() {
        List<String> contacts = new ArrayList<>();
 // Get the ContentResolver
 ContentResolver cr = getContentResolver();
 // Get the Cursor of all the contacts
 Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
 // Move the cursor to first. Also check whether the cursor is empty or not.
 if (cursor.moveToFirst()) {
            // Iterate through the cursor
 do {
                // Get the contacts name
 String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
 contacts.add(name);
 //取得电话号码
 } while (cursor.moveToNext());
 }
        // Close the curosor
 cursor.close();
 return contacts;
 }
    private List<String> getAllContacts(Context context) {
//        public static ArrayList<MyContacts> getAllContacts(Context context) {
//        ArrayList<MyContacts> contacts = new ArrayList<MyContacts>();
 List<String> contacts = new ArrayList<>();
 Cursor cursor = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
 while (cursor.moveToNext()) {
            //新建一个联系人实例
 MyContacts temp = new MyContacts();
 String contactId = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts._ID));
 //获取联系人姓名
 String name = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
 temp.name = name;
 //获取联系人电话号码
 Cursor phoneCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
 null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
 while (phoneCursor.moveToNext()) {
                String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
 phone = phone.replace("-", "");
 phone = phone.replace(" ", "");
 temp.phone = phone;
 }
            //获取联系人备注信息
 Cursor noteCursor = context.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI,
 new String[]{ContactsContract.Data._ID, ContactsContract.CommonDataKinds.Nickname.NAME},
 ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "='"
 + ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE + "'",
 new String[]{contactId}, null);
 if (noteCursor.moveToFirst()) {
                do {
                    String note = noteCursor.getString(noteCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));
 temp.note = note;
 Log.i("note:", note);
 } while (noteCursor.moveToNext());
 }
            // contacts.add(temp);
 String namePhone = temp.name + "*" + temp.phone;
 contacts.add(namePhone);
 //记得要把cursor给close掉
 phoneCursor.close();
 noteCursor.close();
 }
        cursor.close();
 return contacts;
 }
    public void notification(int iconId, String title, String content){
        final String CHANNEL_ID = "channel_id_1";
 final String CHANNEL_NAME = "channel_name_1";
 NotificationManager mNotificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //只在Android O之上需要渠道
 NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
 CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
 //如果这里用IMPORTANCE_NOENE就需要在系统的设置里面开启渠道,
 //通知才能正常弹出 mNotificationManager.createNotificationChannel(notificationChannel);
 }
        NotificationCompat.Builder builder= new NotificationCompat.Builder(this,CHANNEL_ID);
 builder.setSmallIcon(iconId)
                .setContentTitle(title)
                .setContentText(content)
                .setAutoCancel(true);
 mNotificationManager.notify(1, builder.build());
 }
    private void enableComponent (ComponentName componentName) {
        getPackageManager().setComponentEnabledSetting(componentName,
 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
 }
    private void disableComponent (ComponentName componentName) {
        getPackageManager().setComponentEnabledSetting(componentName,
 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
// 0立即生效会杀掉进程 DONT_KILL_APP约10秒后生效 android10也会杀掉进程 10以下不会
 }
    /**
 * 启动服务(websocket客户端服务) */ private void initSocketClient() {
        System.out.println("^^^^^^^^^^^^ initSocketClient");
 URI serverURI = URI.create("ws://192.168.3.21:9091/websocket/chat?nickname=abbott20210312");
 client = new JWebSocketClient(serverURI) {
            @Override
 public void onMessage(String message) {
                Log.e("onMessage", message);
 ReceivedMsg receivedMsg = GsonManager.getGson(message, ReceivedMsg.class);
 Message msg = new Message();
 msg.what = STATUS_MESSAGE;
 if (receivedMsg.getType().equals("7")) {
                    notification(R.mipmap.ic_launcher, receivedMsg.getTitle(), receivedMsg.getContent());
 }
                mhandler.sendMessage(msg);
 }
        };
 connect();
 }
    //连接
 private void connect() {
        new Thread() {
            @Override
 public void run() {
                try {
                    client.connectBlocking();
 Log.e("connectBlocking", "连接成功");
 if(client.isOpen()){
                        senJsonInit();
 }
                } catch (InterruptedException e) {
                    e.printStackTrace();
 }
            }
        }.start();
 }
    private void senJsonInit() {
        try {
            JSONObject msg = new JSONObject();
 msg.put("from", 2);
 JSONObject init = new JSONObject();
//            init.put("type", "init");
//            init.put("msg", msg);
 init.put("type", "0");
 init.put("nickname", "");
 init.put("content", "");
 init.put("roomName", "公共聊天室");
 init.put("roomId", "heart-app");
 init.put("UUID", "");
 init.put("connect", false);
 init.put("sender", "uid10350");
 init.put("recipient", "");
 sendMsg(init.toString());
 Log.e("init", "Init初始化成功");
 } catch (JSONException e) {
            e.printStackTrace();
 }
    }
    private void sendMsg(String msg) {
        if (null != client) {
            client.send(msg);
 Log.e("发送的消息", msg);
 }
    }
    public String jsonToString() {
        JSONObject param = new JSONObject();
 try {
            param.put("type", "0");
 param.put("nickname", "");
 param.put("content", "");
 param.put("roomName", "公共聊天室");
 param.put("roomId", "public-room");
 param.put("UUID", "");
 param.put("connect", false);
 param.put("recipient", "");
 } catch (JSONException e) {
            // TODO Auto-generated catch block
 e.printStackTrace();
 }
        return param.toString();
 }
}
class MyOnClickListener implements View.OnClickListener{
    @Override
 public void onClick(View view) {
    }
}
回复
阅读 237
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏