清理Android主要活动代码(Cleaning up Android Main Activity Code)

编程入门 行业动态 更新时间:2024-10-24 01:57:56
清理Android主要活动代码(Cleaning up Android Main Activity Code)

就Java和OOP而言,我是一个真正的菜鸟。 我的应用程序崩溃问题,我认为这是因为我的主要活动混乱,我的整体程序结构不正确。 任何人都可以建议我如何清理以下代码,使事情运行更顺畅,并有更好的应用程序结构? 我认为我需要将事物分成不同的类并将大部分功能保存在不同的类中,但我是新的并且确实不确定。 我在手机上运行应用程序时遇到ANR错误(keyDispatchingTimedOut错误),我认为我的无组织代码导致了这种情况。 任何帮助都会很棒! 谢谢。

package com.example.www; public class MainActivity extends Activity { Button mCloseButton; Button mOpenButton; MultiDirectionSlidingDrawer mDrawer; private Button send_button; EditText msgTextField; private LocationManager locManager; private LocationListener locListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature( Window.FEATURE_NO_TITLE ); setContentView(R.layout.main); mDrawer.open(); final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); final String phone = shared.getString("PHONE", ""); String usr_id = shared.getString("USR_ID", null); if(phone == null) { TextView text = (TextView)findViewById(R.id.textView1); text.setText("Please Enter Your Phone Number"); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Please Enter Your Phone Number"); alert.setMessage("You must enter your phone number in order to use this application"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); if (value.length() == 10) { Editor editor = shared.edit(); editor.putString("PHONE", value); editor.commit(); } } }); alert.show(); } Button profile = (Button) findViewById(R.id.button1); profile.setOnClickListener(new OnClickListener() { public void onClick(View v) { startActivity(new Intent(MainActivity.this, PreferencesActivity.class)); } }); if (usr_id == null) { char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray(); Random r = new Random(System.currentTimeMillis()); char[] id = new char[8]; for (int i = 0; i < 8; i++) { id[i] = chars[r.nextInt(chars.length)]; } usr_id = new String(id); Editor editor = shared.edit(); editor.putString("USR_ID", usr_id); editor.commit(); } final String usr_id1 = shared.getString("USR_ID", "none"); send_button = (Button)findViewById(R.id.button2); send_button.setOnClickListener(new OnClickListener() { private boolean running = false; private CountDownTimer timer; public void onClick(View v) { if(!running) { running = true; timer = new CountDownTimer(4000, 1000) { @Override public void onFinish() { send_button.setText("GPS Sent"); startLocation(); sendId(usr_id1, phone); } @Override public void onTick(long sec) { send_button.setText("CANCEL (" + sec / 1000 + ")"); } }.start(); } else { timer.cancel(); send_button.setText("Send GPS"); running = false; } } }); } private void startLocation() { //get a reference to the LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //get the last known position Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //show the last known position //showPosition(loc); //checked to receive updates from the position locListener = new LocationListener() { public void onLocationChanged(Location location) { showPosition(location); } public void onProviderDisabled(String provider){ //labelState.setText("Provider OFF"); } public void onProviderEnabled(String provider){ //labelState.setText("Provider ON "); } public void onStatusChanged(String provider, int status, Bundle extras){ //Log.i("", "Provider Status: " + status); //labelState.setText("Provider Status: " + status); } }; locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener); } private void showPosition(Location loc) { if(loc != null) { Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude()))); send(loc); } } private void send(Location loc) { String lat = String.valueOf(loc.getLatitude()); String lon = String.valueOf(loc.getLongitude()); SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); final String usr_id2 = shared.getString("USR_ID", "none"); if (lat != "0" && lon != "0") { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://example.com/test/example1.php"); //HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4 nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat" nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line nameValuePairs.add(new BasicNameValuePair("id", usr_id2)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } else { // display message if text fields are empty Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); } } private void sendId(String usr_id1, String phone) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://example.com/test/example.php"); //HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive_user.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4 nameValuePairs.add(new BasicNameValuePair("id", usr_id1)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); //msgTextField.setText(""); // clear text box } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } mCloseButton.setOnClickListener( new OnClickListener() { public void onClick( View v ) { mDrawer.animateClose(); } }); mOpenButton.setOnClickListener( new OnClickListener() { public void onClick( View v ) { if( !mDrawer.isOpened() ) mDrawer.animateOpen(); } }); } @Override public void onContentChanged() { super.onContentChanged(); mCloseButton = (Button) findViewById( R.id.button_open ); mOpenButton = (Button) findViewById( R.id.button_open ); mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer ); } }

I'm a real noob when it comes to Java and OOP in general. I'm having issues with my app crashing and I think it's because my Main Activity is cluttered and my overall program is not structured properly. Can anyone advise me on how to clean up the following code to make things run smoother and have a better app structure? I think I need to separate things into different classes and keep most of the functions in different classes, but I'm new and really not sure. I keep getting an ANR error when I run the app on a phone (keyDispatchingTimedOut error) and I think my unorganized code is causing this. Any help would be great! Thanks.

package com.example.www; public class MainActivity extends Activity { Button mCloseButton; Button mOpenButton; MultiDirectionSlidingDrawer mDrawer; private Button send_button; EditText msgTextField; private LocationManager locManager; private LocationListener locListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature( Window.FEATURE_NO_TITLE ); setContentView(R.layout.main); mDrawer.open(); final SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); final String phone = shared.getString("PHONE", ""); String usr_id = shared.getString("USR_ID", null); if(phone == null) { TextView text = (TextView)findViewById(R.id.textView1); text.setText("Please Enter Your Phone Number"); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Please Enter Your Phone Number"); alert.setMessage("You must enter your phone number in order to use this application"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); if (value.length() == 10) { Editor editor = shared.edit(); editor.putString("PHONE", value); editor.commit(); } } }); alert.show(); } Button profile = (Button) findViewById(R.id.button1); profile.setOnClickListener(new OnClickListener() { public void onClick(View v) { startActivity(new Intent(MainActivity.this, PreferencesActivity.class)); } }); if (usr_id == null) { char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray(); Random r = new Random(System.currentTimeMillis()); char[] id = new char[8]; for (int i = 0; i < 8; i++) { id[i] = chars[r.nextInt(chars.length)]; } usr_id = new String(id); Editor editor = shared.edit(); editor.putString("USR_ID", usr_id); editor.commit(); } final String usr_id1 = shared.getString("USR_ID", "none"); send_button = (Button)findViewById(R.id.button2); send_button.setOnClickListener(new OnClickListener() { private boolean running = false; private CountDownTimer timer; public void onClick(View v) { if(!running) { running = true; timer = new CountDownTimer(4000, 1000) { @Override public void onFinish() { send_button.setText("GPS Sent"); startLocation(); sendId(usr_id1, phone); } @Override public void onTick(long sec) { send_button.setText("CANCEL (" + sec / 1000 + ")"); } }.start(); } else { timer.cancel(); send_button.setText("Send GPS"); running = false; } } }); } private void startLocation() { //get a reference to the LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //get the last known position Location loc = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); //show the last known position //showPosition(loc); //checked to receive updates from the position locListener = new LocationListener() { public void onLocationChanged(Location location) { showPosition(location); } public void onProviderDisabled(String provider){ //labelState.setText("Provider OFF"); } public void onProviderEnabled(String provider){ //labelState.setText("Provider ON "); } public void onStatusChanged(String provider, int status, Bundle extras){ //Log.i("", "Provider Status: " + status); //labelState.setText("Provider Status: " + status); } }; locManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener); } private void showPosition(Location loc) { if(loc != null) { Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude()))); send(loc); } } private void send(Location loc) { String lat = String.valueOf(loc.getLatitude()); String lon = String.valueOf(loc.getLongitude()); SharedPreferences shared = getSharedPreferences("PEOPLE_PREFERENCES", MODE_PRIVATE); final String usr_id2 = shared.getString("USR_ID", "none"); if (lat != "0" && lon != "0") { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://example.com/test/example1.php"); //HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4 nameValuePairs.add(new BasicNameValuePair("lat", lat)); //changed "message" to "lat" changed "msg" to "lat" nameValuePairs.add(new BasicNameValuePair("lon", lon)); //added this line nameValuePairs.add(new BasicNameValuePair("id", usr_id2)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } else { // display message if text fields are empty Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); } } private void sendId(String usr_id1, String phone) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://example.com/test/example.php"); //HttpPost httppost = new HttpPost("http://kblapdesk.com/myers27/receive_user.php"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //changed to 4 nameValuePairs.add(new BasicNameValuePair("id", usr_id1)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpclient.execute(httppost); //msgTextField.setText(""); // clear text box } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } mCloseButton.setOnClickListener( new OnClickListener() { public void onClick( View v ) { mDrawer.animateClose(); } }); mOpenButton.setOnClickListener( new OnClickListener() { public void onClick( View v ) { if( !mDrawer.isOpened() ) mDrawer.animateOpen(); } }); } @Override public void onContentChanged() { super.onContentChanged(); mCloseButton = (Button) findViewById( R.id.button_open ); mOpenButton = (Button) findViewById( R.id.button_open ); mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer ); } }

最满意答案

我会将LocationListener封装在一个完全不同的类中。 这应该会缩短您的大部分代码,并为您提供可管理的大块代码。

此外,您似乎在MainActivity中有一些HTTP帖子或Web请求方法。 把它们拿出来放在不同的班级里。 将其命名为ActivityServer或类似的东西。

在ActivityServer类中,您应该创建一个回调和异步接口,以便在执行Web请求时不会阻止UI线程。

I would encapsulate the LocationListener in a totally different class. That should shorten up most of your code and leave you with a manageable chunk to work with.

Additionally, you seem to have some HTTP post or web-request methods in your MainActivity. Take those out and put them in a different class as well. Name it something like ActivityServer or something akin to that.

In your ActivityServer class, you should make a callback and asynchronous interfaces so that you don't block the UI thread when doing web requests.

更多推荐

new,void,public,String,setText,电脑培训,计算机培训,IT培训"/> <meta name=&quo

本文发布于:2023-07-24 10:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1245012.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   Cleaning   Android   Code   Activity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!