1

我在学校有一个项目的 android 应用程序。该应用程序的目标是获取 GPS 位置,扫描可用的 wifi 网络,并将该信息捆绑到要发布的字符串中(也由应用程序发送)。gps 和 wifi 部分是从头开始编写的,而 twitter 代码是我的一位队友发现的一些开源内容。我们中没有人以前有任何 android 编程经验,所以我们一直在学习我们只需要飞行的东西。该应用程序现在可以正常工作,但还不够好。它通常可以关闭一些推文,但最终总是会收到 ANR。我认为这可能来自 GPS 或 WIFI 代码,因为这是我们自己编写的。我们只用 twitter 代码编写了一个单独的应用程序来测试它,它似乎工作正常,所以我不这么认为'

一些有更多经验的 android 程序员是否可以查看其中的一些代码并指出他们看到的任何问题,特别是可能导致该应用程序 ANR 的原因?此外,如果有人愿意提出比我们目前拥有的更好的架构/框架,我会很感兴趣。当应用程序运行时,我们最终会发送一条类似于下面这样的推文:

ajd7v-34 U0b0ed38fc_ _ __ _ __ _ __ _ __ _ __ _ __ _ _ 00b0ed39c4 _ __ _ __ _ __ _ __ _ __ _ __ _ _ _W0b0edf50c+44974893-093232387

这是我们活动类的相关代码......

    private Intent in;
public static TextView textView1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_spectral_tweets);


    mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

    mProvider = new DefaultOAuthProvider(
            "http://api.twitter.com/oauth/request_token",
            "http://api.twitter.com/oauth/access_token",
            "http://api.twitter.com/oauth/authorize");

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String token = prefs.getString("token", null);
    String tokenSecret = prefs.getString("tokenSecret", null);

    if (token != null && tokenSecret != null) {
        mConsumer.setTokenWithSecret(token, tokenSecret);
        oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
                CONSUMER_SECRET, token, tokenSecret);
        twitter = new Twitter(TWITTER_USER, oauthClient);
    } else {
        Log.d(TAG, "onCreate. Not Authenticated Yet " );
        new OAuthAuthorizeTask().execute();
    }

    in = new Intent(this, BackgroundService.class);
    textView1 = (TextView) findViewById(R.id.textView1);
    changeText("On Create");
}

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

/**
 * Changes textView1 to string msg
 */
public static void changeText(String msg) {
    textView1.setText(msg);
}

/**
 * tell the service to start displaying GPS/WIFI updates
 */
public void startMessages(View view) {
    startService(in);
}

/**
 * tell the service to stop displaying GPS/WIFI updates
 */
public void stopMessages(View view) {
    changeText("stopped");
    stopService(in);
}

/**
 * When the BACK key is pressed ask the user if they want to quit
 * if they do then stop the service and exit the program
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        @SuppressWarnings("unused")
        AlertDialog alertbox = new AlertDialog.Builder(this)
        .setMessage("Do you want to exit the application?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            // stop the service and end the program
            public void onClick(DialogInterface arg0, int arg1) {
                stopService(in);
                finish();
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            // return to program
            public void onClick(DialogInterface arg0, int arg1) {}
        })

        .show();
    }
    return super.onKeyDown(keyCode, event);
}

这是我们服务中处理 gps 和 wifi 的代码......

public class BackgroundService extends Service implements LocationListener
{
private static Timer repeater = new Timer();
private static LocationManager lm;
private getInfoAndTweet getAndTweet = this.new getInfoAndTweet();

private static final int MIN_TIME_MILLISECONDS = 0;
private static final int MIN_DIST_METERS = 0;
private static final int frequency = 30 * 1000;
private double temp_long = 0.0;
private double temp_lat = 0.0;
private int temp_count = 0;
private boolean thread_running = false;


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

public void onCreate()
{
    super.onCreate();
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_MILLISECONDS, MIN_DIST_METERS, this);
    Toast.makeText(getApplicationContext(), "Location display is on", Toast.LENGTH_SHORT).show();
    startService();
}

public void onDestroy()
{
    repeater.cancel();
    lm.removeUpdates(this);
    unregisterReceiver(getAndTweet.receiver);
    Toast.makeText(getApplicationContext(), "Location display is off", Toast.LENGTH_SHORT).show();
    temp_lat = 0;
    temp_long = 0;
    temp_count = 0;
}

private void startService()
{
    repeater.scheduleAtFixedRate(getAndTweet, 0, frequency);
}

/* this class will contain all of the GPS and WIFI classes so that none of that stuff clogs up the main thread */
private class getInfoAndTweet extends TimerTask
{
    WifiManager wifi;
    BroadcastReceiver receiver;

    DecimalFormat lat = new DecimalFormat("00.000000");
    DecimalFormat lon = new DecimalFormat("000.000000");
    String gps_info;
    String wifi_info;
    String final_string;
    private final String hashtag = "#ajd7v-34 ";
    int count = 0;

    private class WIFIscanner extends BroadcastReceiver
    {

        private final ArrayList<Integer> channel_numbers = new ArrayList<Integer> (Arrays.asList(0, 2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462));
        List <ScanResult> results;
        Map<Integer, String> levels = new HashMap<Integer, String>();
        String empty_channel = "__________";        // 10 spaces

        public WIFIscanner()
        {
            init_levels();
        }

            public void onReceive(Context context, Intent intent)
        {
            wifi_info = "";
            results = wifi.getScanResults();
            ScanResult sr;
            Iterator<ScanResult> it = results.iterator();
            ScanResult channel_info[] = new ScanResult[12];

            for (int i = 1; i < 12; i++)
            {
                channel_info[i] = null;
            }

            while (it.hasNext())
            {
                sr = it.next();
                int channel = channel_numbers.indexOf(Integer.valueOf(sr.frequency));

                if (channel_info[channel] == null)
                {
                    channel_info[channel] = sr;
                }
                else
                {
                    if (channel_info[channel].level < sr.level)
                    {
                        channel_info[channel] = sr;
                    }
                }
            }

            for (int i = 1; i < 12; i++)
            {
                if (channel_info[i] != null)
                {
                    wifi_info += (levels.get(channel_info[i].level) == null ? "0" : levels.get(channel_info[i].level))  + channel_info[i].BSSID.replace(":", "").substring(2, 11);
                }
                else
                {
                    wifi_info += empty_channel;
                }
            }

            final_string = hashtag + wifi_info + gps_info;
            if (temp_count != 0)
            {
                if(Twitter_Test_AppActivity.twitter != null) {
                    Twitter_Test_AppActivity.twitter.setStatus(final_string);
                    Twitter_Test_AppActivity.changeText("Auto Tweet Sent: " + count + "\t" + final_string);
                } else {
                    Twitter_Test_AppActivity.changeText("Tweet not sent");
                }
            }
            else
            {
                Twitter_Test_AppActivity.changeText(count + "\tno new GPS info");
            }
            thread_running = false;
        }

    }

    public void run()
    {
        thread_running = true;
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (receiver == null)
        {
            receiver = new WIFIscanner();
        }
        registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        String latitude = lat.format(temp_lat / temp_count).replace(".",  "");
        String longitude = lon.format(temp_long / temp_count).replace(".",  "");
        gps_info = ((temp_lat / temp_count) > 0 ? "+" : "") + latitude + ((temp_long / temp_count) > 0 ? "+" : "") + longitude;

        wifi.startScan();
        count++;
    }
}

public void onLocationChanged(Location location) {
    if (thread_running)
    {
        temp_lat += location.getLatitude();
        temp_long += location.getLongitude();
        temp_count ++;
    }
}

public void onProviderDisabled(String provider) {
    Toast.makeText(getApplicationContext(), "GPS disabled", Toast.LENGTH_SHORT).show();

}

public void onProviderEnabled(String provider) {
    Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_SHORT).show();

}

public void onStatusChanged(String provider, int status, Bundle extras) {}

}

编辑当我更多地考虑这个问题时,我想到在主线程上运行的 twitter 代码也可能导致我的 ANR。学校的网络不是最好的,我的笔记本电脑有时甚至无法上网(不是我的笔记本电脑的错,其他地方都很好)。尝试发送推文时,网络连接缓慢或不良是否会导致我的主线程挂断,从而导致手机 ANR 我的应用程序?

4

1 回答 1

0

首先TimerTask不是存储数据的最佳位置。使用您的TimerTaskonly 定期从您的Service.

其次,最好将所有Context相关组件的所有内部类都设为类Activity或类。这将保护您的代码免受内存泄漏。Servicestatic

此外,您最好只注册BroadcastRreceiver一次,并且不要在每次调用计时器任务时都这样做。

我真的建议您阅读一些东西,例如 Reto Meier “Android 应用程序开发”一书。

于 2012-12-01T06:00:56.613 回答