Android開発は初めてです。
Web サービスを使用してロケーション アドレスを取得しようとしましたが、このコードを起動したときにクラスが見つからないという例外が発生しました。
サービス クラスのコード....
public class MWService extends Service implements LocationListener {
private LocationManager myLocationManager;
private LocationProvider myLocationProvider;
private NotificationManager myNotificationManager;
private long frequency;
private double total_distance = 0;
private Location currentLocation;
public static final String BROADCAST_ACTION = "com.motorvehicle.android";
private final Handler handler = new Handler();
Intent intent;
private GeocoderHelper geocoder = new GeocoderHelper();
private boolean isStart=true;
private Location startLocation,endLocation;
private String startAddress="";
private String endAddress="";
private JSONArray jarray = new JSONArray();
private boolean isInternet;
//private final Handler handler = new Handler();
public void onLocationChanged(Location newLocation) {
try {
System.out.println("latitude current :"+currentLocation.getLatitude());
System.out.println("latitude current :"+currentLocation.getLongitude());
System.out.println("latitude new :"+newLocation.getLatitude());
System.out.println("latitude new :"+newLocation.getLongitude());
System.out.println("distance total :"+total_distance);
//System.out.println(distance(22.306813, 73.180239,22.301016, 73.177986, 'K') + " Kilometers\n");
double diff = 0.0;
diff = currentLocation.getLatitude()- newLocation.getLatitude();
System.out.println("difference ::"+diff);
if(diff != 0){
total_distance = total_distance + currentLocation.distanceTo(newLocation);
}
if(isStart){
isStart = false;
startLocation = newLocation;
/* if(InternetAvailable()){
//startAddress = geocoder.fetchCityName(getApplicationContext(),newLocation);
System.out.println("start address:"+startAddress);
}*/
}else{
endLocation = newLocation;
/*if(InternetAvailable()){
//endAddress = geocoder.fetchCityName(getApplicationContext(),newLocation);
System.out.println("endAddress :"+endAddress);
}*/
}
currentLocation = newLocation;
} catch (Exception e) {
currentLocation = newLocation;
e.printStackTrace();
}
}
public boolean InternetAvailable() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// while(isStopMe){
System.out.println("This is inside ................. :");
try {
if (!checkConnection()) {
System.out.println("No Internet Connectivity");
isInternet = false;
System.out.println("First");
} else {
if (inetAddr()) {
System.out.println("Net Connectivity is Present");
isInternet = true;
System.out.println("Second");
} else {
if (mobileConnect()) {
System.out.println("THIRD");
if (inetAddr()) {
System.out
.println("Net Connectivity is Present");
isInternet = true;
System.out.println("FOURTH");
} else {
System.out
.println("No Internet Connectivity");
isInternet = false;
System.out.println("FIFTH");
}
} else {
System.out.println("No Internet Connectivity");
isInternet = false;
System.out.println("SIX");
}
}
}
} catch (Exception ex) {
System.out.println("Leak ko catch");
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isInternet;
}
public boolean checkConnection() {
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI") || ni
.getTypeName().equalsIgnoreCase("MOBILE"))
& ni.isConnected() & ni.isAvailable()) {
connected = true;
}
}
}
return connected;
}
public boolean inetAddr() {
boolean x1 = false;
try {
Socket s = new Socket();
s.connect(new InetSocketAddress("ntp-nist.ldsbc.edu",37),3000);
InputStream is = s.getInputStream();
Scanner scan = new Scanner(is);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
x1 = true;
}
} catch (IOException e) {
x1 = false;
}
return x1;
}
public boolean mobileConnect() {
boolean conn = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNet != null) {
conn = true;
} else {
conn = false;
}
return conn;
}
@SuppressWarnings("deprecation")
private void myNotify(String text) {
Notification notif = new Notification(R.drawable.ic_launcher, text, System
.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, MainActivity.class), 0);
notif.setLatestEventInfo(this, "MotorVehicleApp", text, contentIntent);
// notif.defaults = Notification.DEFAULT_VIBRATE;
myNotificationManager.notify((int) System.currentTimeMillis(), notif);
}
@Override
public void onCreate() {
super.onCreate();
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
intent = new Intent(BROADCAST_ACTION);
android.util.Log.d("MWD", "creating");
myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("location manager:"+myLocationManager.getAllProviders());
myLocationProvider = myLocationManager.getProvider("gps");
myNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
updatePreferences();
handler.post(new Runnable() {
@Override public void run() {
Toast.makeText(getApplicationContext(), "Address:"+startAddress, Toast.LENGTH_LONG).show(); } });
}
public void updatePreferences() {
// sync local variables with preferences
android.util.Log.d("NWD", "updating preferences");
frequency = 10;
// update the LM with the new frequency
myLocationManager.removeUpdates(this);
myLocationManager.requestLocationUpdates(myLocationProvider.getName(),frequency, 0, this);
}
@Override
public void onDestroy() {
super.onDestroy();
/////------set edittext editable
android.util.Log.d("NWD", "destroying");
System.out.println("Inside on destroy of MWService");
myLocationManager.removeUpdates(this);
//myNotify("stopping");
InsertTripDetails_AsyncTask insert = new InsertTripDetails_AsyncTask();
insert.execute();
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
handler.removeCallbacks(sendUpdatesToUI);
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
android.util.Log.d("NWD", "starting");
currentLocation = myLocationManager.getLastKnownLocation(myLocationProvider.getName());
//myNotify("starting");
handler.postDelayed(sendUpdatesToUI, 3000); // 1 sec
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
System.out.println("total_distance::"+total_distance);
intent.putExtra("distance",(total_distance/1000));
sendBroadcast(intent);
handler.postDelayed(this, 3000);
}
};
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
@Override
public IBinder onBind(Intent arg0) {
return null; // this is for heavy IPC, not used
}
private class InsertTripDetails_AsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
try {
//InternetAvailable()
if(InternetAvailable()){
startAddress = geocoder.fetchCityName(getApplicationContext(),startLocation);
System.out.println("start address:"+startAddress);
endAddress = geocoder.fetchCityName(getApplicationContext(),endLocation);
System.out.println("end address:"+endAddress);
}else{
System.out.println("internet not available");
}
// Internet not available when data are store in latitude and longitute format
if(startAddress.equalsIgnoreCase("") && endAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
System.out.println("1 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+",lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
}else if(startAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
System.out.println("2 lat:"+sd.format(startLocation.getLatitude()) +" long:"+sd.format(startLocation.getLongitude())+","+endAddress);
}else if(endAddress.equalsIgnoreCase("")){
DecimalFormat sd = new DecimalFormat("##.##");
try {
System.out.println(startAddress+",3 lat:"+sd.format(endLocation.getLatitude()) +" long:"+sd.format(endLocation.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
System.out.println(startAddress+" "+ endAddress);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("In catch of webservice thus no internet");
}
return "dfs";
}
@Override
protected void onPostExecute(String result) {
}
}
}
ジオコーダー クラスのコード
public class GeocoderHelper
{
private static final AndroidHttpClient ANDROID_HTTP_CLIENT = AndroidHttpClient.newInstance(GeocoderHelper.class.getName());
private String address="";
private Location i_Location;
private Context i_Context;
public String fetchCityName(final Context contex, final Location location)
{
i_Location = location;
i_Context = contex;
try {
return new Address().execute().get();
} catch (Exception e) {
return address;
}
}
public class Address extends AsyncTask<Void, Void, String>
{
@SuppressWarnings("unused")
@Override
protected String doInBackground(Void... params)
{
String cityName = null;
if (Geocoder.isPresent())
{
try
{
System.out.println("location latitude is"+i_Location.getLatitude());
System.out.println("location longitude is"+i_Location.getLongitude());
Geocoder geocoder = new Geocoder(i_Context, Locale.getDefault());
List<android.location.Address> addresses = geocoder.getFromLocation(i_Location.getLatitude(), i_Location.getLongitude(), 1);
if (addresses.size() > 0)
{
//cityName = addresses.get(0).getLocality();
address = addresses.get(0).getLocality();
System.out.println("geocoder inside present address is"+address);
}
}
catch (Exception ignored)
{
// after a while, Geocoder start to trhow "Service not availalbe" exception. really weird since it was working before (same device, same Android version etc..
}
}
if (cityName != null) // i.e., Geocoder succeed
{
return cityName;
}
else // i.e., Geocoder failed
{
return fetchCityNameUsingGoogleMap();
}
}
// Geocoder failed :-(
// Our B Plan : Google Map
private String fetchCityNameUsingGoogleMap()
{
try
{
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + i_Location.getLatitude() + ","
+ i_Location.getLongitude() + "&sensor=false&language=fr";
JSONObject googleMapResponse = new JSONObject(ANDROID_HTTP_CLIENT.execute(new HttpGet(googleMapUrl),
new BasicResponseHandler()));
// many nested loops.. not great -> use expression instead
// loop among all results
JSONArray results = (JSONArray) googleMapResponse.get("results");
for (int i = 0; i < results.length(); i++)
{
// loop among all addresses within this result
JSONObject result = results.getJSONObject(i);
address = result.getString("formatted_address");
System.out.println("map address:"+address);
break;
/* if (result.has("address_components"))
{
JSONArray addressComponents = result.getJSONArray("address_components");
// loop among all address component to find a 'locality' or 'sublocality'
for (int j = 0; j < addressComponents.length(); j++)
{
JSONObject addressComponent = addressComponents.getJSONObject(j);
if (result.has("types"))
{
JSONArray types = addressComponent.getJSONArray("types");
// search for locality and sublocality
String cityName = null;
String ROUTE= null;
for (int k = 0; k < types.length(); k++)
{
if ("locality".equals(types.getString(k)) && cityName == null)
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
if ("sublocality".equals(types.getString(k)))
{
if (addressComponent.has("long_name"))
{
cityName = addressComponent.getString("long_name");
}
else if (addressComponent.has("short_name"))
{
cityName = addressComponent.getString("short_name");
}
}
}
if (cityName != null)
{
address = cityName;
return cityName;
}
}
}
}*/
}
}
catch (Exception ignored)
{
ignored.printStackTrace();
}
return address;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
}
MAinActivity クラスのコード
public class MainActivity extends Activity {
//private final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(MainActivity.this,MWService.class));
}
@Override
protected void onPause() {
super.onPause();
stopService(new Intent(MainActivity.this,MWService.class));
}
}
インターネットと AccessFineLocation の両方について、menifest ファイルで使用許可を持っています。
私のlogcatメッセージ.....
10-31 13:40:41.937: ERROR/AndroidRuntime(825): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.address2/com.example.android.MainActivity}: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
10-31 13:40:41.937: ERROR/AndroidRuntime(825): Caused by: java.lang.ClassNotFoundException: com.example.android.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.address2-1.apk]
私のメニフェストファイルのコード....
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.android.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="MWService"></service>
</application>