gpt4 book ai didi

java - Android - 在库和应用程序之间创建接口(interface)

转载 作者:行者123 更新时间:2023-11-30 03:24:29 24 4
gpt4 key购买 nike

我需要在我构建的库和应用程序的其余部分之间创建一个接口(interface) - 如何实现?

我试图通过将它们相互导入并将库添加到项目属性下的主项目来连接两者 - 但我似乎仍然无法将 (XML) 数据从库中获取到初级应用类。

图书馆:

打包 com.project.test.networktasklibrary;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import com.project.test.networktasklibrary.XmlParserHandlerFinal;
import com.project.test.*;

import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

/*this class performs the call to webservice in the background*/
public class NetworkTask extends AsyncTask<String, String, InputStream> {
private static final String LOG_TAG = "STDataSettings";
private static final String TAG_RESULT = "success";
private static InputStream stream;

@Override
protected InputStream doInBackground(String... params) {

try {
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return stream;
}

/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected static synchronized InputStream getQueryResults(
String urlQueryString) throws IOException, SAXException,
SSLException, SocketTimeoutException, Exception {
Bundle queryResults = new Bundle();

HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);

https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(50000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
try {
https = (HttpsURLConnection) urlo.openConnection();

if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();

} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();

} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();

} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();

} finally {

}

String queryResult = null;
queryResults.putString(TAG_RESULT, queryResult);

return stream;
}

public InputStream getInputStream() {
return stream;
}

protected void onPostExecute(InputStream queryResults) {
// TODO Auto-generated method stub
super.onPostExecute(queryResults);
//success();
}
}

主要应用类:

package com.project.test.datasettings;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.project.test.networktasklibrary.*;
import com.project.test.networktasklibrary.NetworkTask;

public class UpdateActivity extends Activity implements OnClickListener {
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
public static int count;
AlertDialog mErrorAlert = null;
int version;
public static int TotalSteps = 8;
private TelephonyManager tm;
private static final String LOG_TAG = "STDataSettings";
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
private int mInstructionNumber = 0;
AlertDialog mConfirmAlert = null;
public static InputStream stream = null;
public static XmlParserHandlerFinal handler;
private NetworkTask task;
private AnimationDrawable loadingAnimation;
private static final String TAG = "UpdateActivity";
Context ctx;
private Button assist_update_btn = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
handler = new XmlParserHandlerFinal();
int version = android.os.Build.VERSION.SDK_INT;
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| !(tm.getSimOperator()
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()
.equals(getString(R.string.numeric_att))))) {

// if SIM is present and is NOT a T-Mo network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo MNC MCC present
else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Initial UI setup for versions lower than ICS
setContentView(R.layout.update);
mUpdateButton = (Button) findViewById(R.id.update_button);

mUpdateButton.setOnClickListener(this);

} else {// ICS and up

if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
task = new NetworkTask();
task.execute("");
// Device has T-Mo network SIM card MCC and MNC correctly
// populated
// Reduce number of steps to 6
TotalSteps = 6;
}

}
}

public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected

onClickMethod(v);

Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else

if (v.getId() == R.id.assist_update_btn) {

// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout

setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));

} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}

public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);

}

private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}

// AsyncTask to call web service
class NetworkTask extends AsyncTask<String, Integer, InputStream> {

@Override
protected void onPreExecute() {

super.onPreExecute();
}

@Override
protected InputStream doInBackground(String... params) {

try {
// saving the response in InputStream
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
// stream = new BufferedInputStream(https.getInputStream());
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { // Print the content
// on the console
System.out.println(strLine);
System.out.println(strLine);
in.close();
}

} catch (IOException e) {

Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {

Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {

Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
// The code below plays a Simple Promo animation

for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show sequential dot
// loading animation
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);

// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
return stream;
}

/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {

HttpsURLConnection https = null;
String uri = urlQueryString;

URL urlo = new URL(uri);

try {
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(20000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");

if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();

} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();

} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();

} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();

} finally {

}

return stream;
}

@Override
protected void onProgressUpdate(Integer... progress) {

// Call function to update image view

setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);

}

@Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
assistUpdate();

}

}

private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener(this);

}

private void setProgressImgView(Integer imageViewId1, Integer imageViewId2,
Integer imageViewId3, Integer imageViewId4, Integer imageViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);

mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview1.setBackgroundResource(imageViewId1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview2.setBackgroundResource(imageViewId2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview3.setBackgroundResource(imageViewId3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview4.setBackgroundResource(imageViewId4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview5.setBackgroundResource(imageViewId5);

}

@Override
protected void onRestart() {
super.onRestart();

if (mErrorAlert != null)
mErrorAlert.dismiss();
}

private void endUpdate(View v) {
finish();

}

public void success() {

// to parse the response
try {
handler.getQueryResponse(stream);

} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);

}

// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
// System.out.println("testing123");

for (int i = 0; i < nameArr.size() - 1; i++) {
System.out.println(nameArr.get(i));
}

for (int i = 0; i < ApnArr.size() - 1; i++) {
System.out.println(ApnArr.get(i));
}
}
}

最佳答案

每当您想从库的 R 类中获取 xml 数据时,您需要显式调用 com.project.test.networktasklibrary.R 而不仅仅是 R , 以区别于您的应用程序包中的 R 类。

默认情况下,R 将引用当前包中的 R。如果您不打算在当前类中使用应用程序的 R 类,您也可以在此类的顶部导入 com.project.test.networktasklibrary.R 然后将其引用为R.

关于java - Android - 在库和应用程序之间创建接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18474797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com