Android应用程序无响应错误

时间:2017-04-07 14:49:51

标签: java android

当我从最近的活动中滑动应用程序时,我两次得到了anr。然后应用程序正常工作,当我切换到横向模式时,我得到一个anr。该应用程序按预期工作,只要它不是面向风景或从最近的应用程序刷过。 有人可以指出我在这里做错了什么。 感谢

MyService.java:

public class MyService extends Service {

public static boolean started = false;
public static String TRANSACTION_DONE = "com.example.root.project";
private WebSocketClient client = null;
public static SQLiteDatabase myDataBase = null;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(final Intent intent, int flags, int startId) {

    if(started){
        String message = intent.getStringExtra("message");
        if(client != null){
            client.send(message);
        }
    }

    if (!started) {
        myDataBase = openOrCreateDatabase("Messages.db", MODE_PRIVATE, null);
        myDataBase.execSQL("CREATE TABLE IF NOT EXISTS messages " +
                "(tag TEXT primary key, message TEXT);");
        started = true;
        URI uri = null;
        try {
            uri = new URI(intent.getStringExtra("ip"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        client = new WebSocketClient(uri) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {

                JSONObject jsonObject = null;

                try {
                    jsonObject = new JSONObject();
                    jsonObject.accumulate("addme",intent.getStringExtra("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                client.send(jsonObject.toString());

            }

            @Override
            public void onMessage(String message) {

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (jsonObject.has("resolve")) {
                    PendingIntent notificIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                            new Intent(getApplicationContext(), MainActivity.class), 0);

                    // Builds a notification
                    NotificationCompat.Builder mBuilder =
                            null;
                    try {
                        mBuilder = new NotificationCompat.Builder(getApplicationContext())
                                .setSmallIcon(R.drawable.add)
                                .setContentTitle(jsonObject.getString("name"))
                                .setTicker(jsonObject.getString("resolve"))
                                .setContentText(jsonObject.getString("destination"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    // Defines the Intent to fire when the notification is clicked
                    mBuilder.setContentIntent(notificIntent);

                    // Set the default notification option
                    // DEFAULT_SOUND : Make sound
                    // DEFAULT_VIBRATE : Vibrate
                    // DEFAULT_LIGHTS : Use the default light notification
                    mBuilder.setDefaults(Notification.DEFAULT_ALL);

                    // Auto cancels the notification when clicked on in the task bar
                    mBuilder.setAutoCancel(true);

                    // Gets a NotificationManager which is used to notify the user of the background event
                    NotificationManager mNotificationManager =
                            (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

                    // Post the notification
                    mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
                } else if (jsonObject.has("remove")) {

                    try {
                        String tag = jsonObject.getString("remove");
                        myDataBase.execSQL("DELETE FROM messages WHERE tag = " + tag + ";");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    if (isForeground(TRANSACTION_DONE)) {
                        Intent broadcast = new Intent(TRANSACTION_DONE);
                        broadcast.putExtra("message", message);
                        sendBroadcast(broadcast);
                    }
                } else {

                    try {
                        myDataBase.execSQL("INSERT INTO messages (tag, message) VALUES ('" +
                                jsonObject.getString("tag") + "', '" + message + "');");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    if (isForeground(TRANSACTION_DONE)) {
                        Intent broadcast = new Intent(TRANSACTION_DONE);
                        broadcast.putExtra("message", message);
                        sendBroadcast(broadcast);
                    }
                }
            }

            @Override
            public void onClose(int i, String s, boolean b) {
                Log.d("myTag", "onClose: websocket closing ");
                Toast.makeText(getApplicationContext(),"closing websocket",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onError(Exception e) {
                Log.i("Websocket", "Error " + e.getMessage());
            }
        };
        client.connect();
    }
    return START_STICKY;
}


@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    Toast.makeText(getApplicationContext(),"closing client",Toast.LENGTH_LONG).show();
    client.close();
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d("myTag", "onDestroy: service being destroyed ");
    try {
        client.closeBlocking();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Toast.makeText(this,"Service is closing on destroy called",Toast.LENGTH_LONG).show();
}

public boolean isForeground(String myPackage) {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
    ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
    return componentInfo.getPackageName().equals(myPackage);
}

}

MainActivity.java:

public class MainActivity extends AppCompatActivity {

private CustomAdapter adapter;
private String name;
private String ip;

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.add) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title");
        final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog_layout, null);
        builder.setView(viewInflated);

        // Set up the buttons
        builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                EditText editText = (EditText) viewInflated.findViewById(R.id.dialogTitle);
                EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogDesc);
                String title = editText.getText().toString().trim();
                String desc = editText2.getText().toString().trim();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.accumulate("title", title);
                    jsonObject.accumulate("desc", desc);
                    jsonObject.accumulate("name",name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(MainActivity.this,MyService.class);
                intent.putExtra("message",jsonObject.toString());
                startService(intent);
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if(MyPreferences.isFirst(this)) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title");
        final View viewInflated = getLayoutInflater().inflate(R.layout.login_dialog, null);
        builder.setView(viewInflated);

        // Set up the buttons
        builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                EditText editText = (EditText) viewInflated.findViewById(R.id.dialogName);
                EditText editText2 = (EditText) viewInflated.findViewById(R.id.dialogIp);
                name = editText.getText().toString().trim();
                ip = editText2.getText().toString().trim();
                Intent intent = new Intent(MainActivity.this, MyService.class);
                intent.putExtra("name", name);
                intent.putExtra("ip", ip);
                MainActivity.this.getSharedPreferences("my_preferences",MODE_PRIVATE).edit().putString("name",name).putString("ip",ip).commit();
                startService(intent);
                ListView listView = (ListView) findViewById(R.id.listView);
                adapter = new CustomAdapter(MainActivity.this);
                listView.setAdapter(adapter);
                IntentFilter filter = new IntentFilter();
                filter.addAction(MyService.TRANSACTION_DONE);
                registerReceiver(myReceiver, filter);
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (MyService.myDataBase == null) return;
                        Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
                        int messageColumn = cursor.getColumnIndex("message");
                        cursor.moveToFirst();
                        if (cursor != null && (cursor.getCount() > 0)) {
                            do {
                                String message = cursor.getString(messageColumn);
                                try {
                                    JSONObject jsonObject = new JSONObject(message);
                                    adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            } while (cursor.moveToNext());
                            adapter.update();
                        }
                    }
                });

            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }else {
        Intent intent = new Intent(this, MyService.class);
        name = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("name","no_name");
        ip  = this.getSharedPreferences("my_preferences",MODE_PRIVATE).getString("ip","no_ip");
        intent.putExtra("name",name);
        intent.putExtra("ip",ip);
        startService(intent);
        ListView listView = (ListView) findViewById(R.id.listView);
        adapter = new CustomAdapter(this);
        listView.setAdapter(adapter);
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyService.TRANSACTION_DONE);
        registerReceiver(myReceiver, filter);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                if (MyService.myDataBase == null) return;
                Cursor cursor = MyService.myDataBase.rawQuery("SELECT * FROM messages", null);
                int messageColumn = cursor.getColumnIndex("message");
                cursor.moveToFirst();
                if (cursor != null && (cursor.getCount() > 0)) {
                    do {
                        String message = cursor.getString(messageColumn);
                        try {
                            JSONObject jsonObject = new JSONObject(message);
                            adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } while (cursor.moveToNext());
                    adapter.update();
                }
            }
        });
    }
}

@Override
protected void onDestroy() {
    if (myReceiver != null) {
        unregisterReceiver(myReceiver);
        myReceiver = null;
    }
    super.onDestroy();
}

private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("message");
        Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(message);
            if(jsonObject.has("remove")){
                adapter.remove(jsonObject.getString("remove"));
                adapter.update();
            }else {
                adapter.add(jsonObject.getString("title"), jsonObject.getString("desc"), jsonObject.getString("tag"));
                adapter.update();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    };

    class CustomAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private ArrayList<ListViewData> objects;

    public void add(String title, String desc, String tag) {
        objects.add(new ListViewData(title, desc, tag));
    }

    public void remove(String tag){
        for(ListViewData data : objects){
            if(data.getTag().equals(tag)){
                objects.remove(data);
                break;
            }
        }
    }

    public void update(){
        notifyDataSetChanged();
    }

    private class ViewHolder {
        TextView title;
        TextView description;
        Button resolve;
        Button subscribe;
        Button unSubscribe;
    }

    public CustomAdapter(Context context) {
        inflater = LayoutInflater.from(context);
        objects = new ArrayList<>();
    }

    public int getCount() {
        return objects.size();
    }

    public ListViewData getItem(int position) {
        return objects.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.custom_list_layout, null);
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.description = (TextView) convertView.findViewById(R.id.desc);
            holder.resolve = (Button) convertView.findViewById(R.id.resolve);
            holder.subscribe = (Button) convertView.findViewById(R.id.subscribe);
            holder.unSubscribe = (Button) convertView.findViewById(R.id.unsubscribe);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.title.setText(objects.get(position).getTitle());
        holder.description.setText(objects.get(position).getDescription());
        holder.resolve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Title");
                final View viewInflated = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
                builder.setView(viewInflated);

                // Set up the buttons
                builder.setPositiveButton("Publish", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        EditText editText = (EditText) viewInflated.findViewById(R.id.name);
                        EditText editText2 = (EditText) viewInflated.findViewById(R.id.destination);
                        String name = editText.getText().toString().trim();
                        String destination = editText2.getText().toString().trim();
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.accumulate("name", name);
                            jsonObject.accumulate("destination", destination);
                            jsonObject.accumulate("resolve",objects.get(position).getTag());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Intent intent = new Intent(MainActivity.this,MyService.class);
                        intent.putExtra("message",jsonObject.toString());
                        startService(intent);
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                builder.show();
            }

        });
        holder.subscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String tag = objects.get(position).getTag();
                try {
                    Intent intent = new Intent(MainActivity.this,MyService.class);
                    intent.putExtra("message",new JSONObject().accumulate("subscribe",tag).accumulate("name",name).toString());
                    startService(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        holder.unSubscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String tag = objects.get(position).getTag();
                try {
                    Intent intent = new Intent(MainActivity.this,MyService.class);
                    intent.putExtra("message",new JSONObject().accumulate("unsubscribe",tag).accumulate("name",name).toString());
                    startService(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        return convertView;
    }
}

}

class MyPreferences {

private static final String MY_PREFERENCES = "my_preferences";

public static boolean isFirst(Context context){
    final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
    final boolean first = reader.getBoolean("is_first", true);
    if(first){
        final SharedPreferences.Editor editor = reader.edit();
        editor.putBoolean("is_first", false);
        editor.commit();
    }
    return first;
}

}

0 个答案:

没有答案