Android活动可以自我重建
我的应用程序通常工作正常,直到我在特定设备上遇到一个奇怪的问题。应用程序中有2个活动。当我在ActivityA内部启动ActivityB后,ActivityA将无问题启动。但是,在我返回到ActivityA并按下硬件按钮或调用finish()之后;在ActivityB中的closeButton内部,ActivityA重新加载自身。它再次触发onCreate()并重新加载其所有内容。我不会改变手机的方向。这种奇怪的行为只出现在15部下载了1000多个应用程序的手机上 此问题仅发生在Galaxy S3 Android OS 4.1.2上。这也很奇怪。 你知道为什么会这样吗 当我在button listener中启动新活动时,如下所示: 活动a.java(MesajlarListViewActivity)Android活动可以自我重建,android,mobile,galaxy,Android,Mobile,Galaxy,我的应用程序通常工作正常,直到我在特定设备上遇到一个奇怪的问题。应用程序中有2个活动。当我在ActivityA内部启动ActivityB后,ActivityA将无问题启动。但是,在我返回到ActivityA并按下硬件按钮或调用finish()之后;在ActivityB中的closeButton内部,ActivityA重新加载自身。它再次触发onCreate()并重新加载其所有内容。我不会改变手机的方向。这种奇怪的行为只出现在15部下载了1000多个应用程序的手机上 此问题仅发生在Galaxy S
公共类MesajlarListViewActivity扩展了TrackedActivity{
Context=null;
//联系JSONArray
JSONArray联系人=null;
ArrayList productArray=新的ArrayList();
私有产品适配器;
私有ListView产品列表;
私人可运行视图命令;
私有HoloProgressIndicator profilInfoProgress=null;
ImageView kapatButton=null;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajlar_列表);
上下文=这个;
kapatButton=(ImageView)findViewById(R.id.kapat_按钮);
/*点击监听器上的kapat按钮*/
// =================================================================================================================
kapatButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图)
{
//触摸时设置振动。
KnetGenericClass.VibrationPhone(上下文);
完成();
}
});
// =================================================================================================================
//进度条。
profilInfoProgress=(HoloProgressIndicator)findViewById(R.id.profil\u info\u progress);
//检查互联网连接。
if(KnetGenericClass.checkInternetConnection(上下文))
{
//开始任务!
/*互联网服务baglantisi kurmaya baslayabiliriz*/
StartActivityIndicator with Thread();
}
其他的
{
KnetGenericClass.printErrorMessage(上下文,“BağlantıHatası”,
“吕特芬互联网公司bağlantınızıkontrol ediniz。”);
}
productList=(ListView)findViewById(R.id.product\u列表);
adapter=新产品适配器(此,R.layout.message\u行,productArray);
productList.setAdapter(适配器);
//当用户单击列表视图上的视图时,将显示新页面。
productList.setOnItemClickListener(新的OnItemClickListener(){
public void onItemClick(AdapterView父对象、视图、整型位置、长id)
{
//触摸时设置振动。
KnetGenericClass.VibrationPhone(上下文);
/*导航到具有ilan ID的message detay活动类*/
Intent myIntent=newintent(view.getContext(),MesajDetayActivity.class);
myIntent.putExtra(“messageID”,productArray.get(position.getId());
星触觉(myIntent);
//将已单击邮件的图像设置为空。
RelativeLayout RelativeLayout=(RelativeLayout)视图;
ImageView未读ImageView=(ImageView)relativeLayout.findViewById(R.id.unreaded_image);
未读ImageView.setImageResource(0);
}
});
}
公共类ProductAdapter扩展了ArrayAdapter{
数组列表项;
public ProductAdapter(上下文上下文、int-textViewResourceId、ArrayList对象){
超级(上下文、textViewResourceId、对象);
此项=对象;
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图)
{
if(convertView==null)
{
LayoutInflater vi=(LayoutInflater)getSystemService(Context.LAYOUT\u INFLATER\u SERVICE);
convertView=vi.充气(R.布局.消息行,空);
}
ImageView未读ImageView=(ImageView)convertView.findViewById(R.id.unreaded\u image);
TextView产品名称=(TextView)convertView.findViewById(R.id.product\u名称);
TextView产品详细信息=(TextView)convertView.findViewById(R.id.product\u详细信息);
//TextView productDate=(TextView)
//convertView.findViewById(R.id.product\U日期);
TextView sentDate=(TextView)convertView.findViewById(R.id.product\u日期);
productName.setText(items.get(position.getSender());
setText(items.get(position.getTitle());
//字符串bodyNoHTML=items.get(position.getBody();
if(items.get(position.getIsReaded())
{
未读ImageView.setImageResource(0);
}
其他的
{
未读ImageView.setImageResource(R.drawable.bluedot);
}
字符串dateStr=items.get(position.getSentDate();
尝试
{
sentDate.setText(dateStr.substring(6,8)+“+”+dateStr.substring(4,6)+“+”+dateStr.substring(0,4)
+“+dateStr.substring(8,10)+”:“+dateStr.substring(10,12));
}
捕获(例外e)
{
sentDate.setText(“”);
}
返回视图;
}
}//@产品适配器类的结尾。
/*web service’e baglanti kurulan methodu threadin Icerinde cagiriyoruz*/
公共无效StartActivityIndicator
public class MesajlarListViewActivity extends TrackedActivity {
Context context = null;
// contacts JSONArray
JSONArray contacts = null;
ArrayList<Message> productArray = new ArrayList<Message>();
private ProductAdapter adapter;
private ListView productList;
private Runnable viewOrders;
private HoloProgressIndicator profilInfoProgress = null;
ImageView kapatButton = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajlar_list);
context = this;
kapatButton = (ImageView) findViewById(R.id.kapat_button);
/* kapat button onclick listener. */
// =================================================================================================================
kapatButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
finish();
}
});
// =================================================================================================================
//Progress bar.
profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);
// cheking internet connectivity.
if(KnetGenericClass.checkInternetConnection(context))
{
// start task!
/* internet var ise web service baglantisi kurmaya baslayabiliriz. */
startActivityIndicatorWithThread();
}
else
{
KnetGenericClass.printErrorMessage(context, "Bağlantı Hatası",
"Lütfen internet bağlantınızı kontrol ediniz.");
}
productList = (ListView) findViewById(R.id.product_list);
adapter = new ProductAdapter(this, R.layout.message_row, productArray);
productList.setAdapter(adapter);
// When user click a view on list view new page is appearing.
productList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
/* Navigate to message detay activity class with ilan ID. */
Intent myIntent = new Intent(view.getContext(), MesajDetayActivity.class);
myIntent.putExtra("messageID", productArray.get(position).getId());
startActivity(myIntent);
// setting image of clicked message null.
RelativeLayout relativeLayout = (RelativeLayout) view;
ImageView unreadedImageView = (ImageView) relativeLayout.findViewById(R.id.unreaded_image);
unreadedImageView.setImageResource(0);
}
});
}
public class ProductAdapter extends ArrayAdapter<Message> {
ArrayList<Message> items;
public ProductAdapter(Context context, int textViewResourceId, ArrayList<Message> objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.message_row, null);
}
ImageView unreadedImageView = (ImageView) convertView.findViewById(R.id.unreaded_image);
TextView productName = (TextView) convertView.findViewById(R.id.product_name);
TextView productDetail = (TextView) convertView.findViewById(R.id.product_detail);
// TextView productDate = (TextView)
// convertView.findViewById(R.id.product_date);
TextView sentDate = (TextView) convertView.findViewById(R.id.product_date);
productName.setText(items.get(position).getSender());
productDetail.setText(items.get(position).getTitle());
// String bodyNoHTML = items.get(position).getBody();
if(items.get(position).getIsReaded())
{
unreadedImageView.setImageResource(0);
}
else
{
unreadedImageView.setImageResource(R.drawable.bluedot);
}
String dateStr = items.get(position).getSentDate();
try
{
sentDate.setText(dateStr.substring(6, 8) + "." + dateStr.substring(4, 6) + "." + dateStr.substring(0, 4)
+" "+dateStr.substring(8, 10)+":"+dateStr.substring(10, 12));
}
catch(Exception e)
{
sentDate.setText("");
}
return convertView;
}
}// @end of product adapter class.
/* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */
public void startActivityIndicatorWithThread()
{
// ==============================================================================================
// getting ilan details into arraylist.
// setting up thread.
viewOrders = new Runnable() {
public void run()
{
getMessageListFromWebService();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
profilInfoProgress.start();
// ==============================================================================================
// @end of the thread declaration.
}
public void getMessageListFromWebService()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser(context);
// getting JSON string from URL
JSONArray jsonArray = jParser.getAuthorizedInfoFromUrlToJSONArray(
WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessageList", MainActivity.getAccessToken());
// if json is null then there is a problem.
if(jsonArray == null)
{
// if json array is null then print error message.
runOnUiThread(showAlertMessage);
runOnUiThread(returnRes);
return;
}
try
{
// Eger aranilan kritere gore ilan yok ise hata mesaji basiyoruz.
if(jsonArray.length() == 0)
{
// if json array is null then print error message.
runOnUiThread(showAlertIlanYokMessage);
runOnUiThread(returnRes);
return;
}
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
// String id = c.getString(TAG_ID);
String id = c.getString("Id");
String sender = c.getString("Sender");
// String body = c.getString("Body");
String title = c.getString("Title");
String sentDate = c.getString("SentDate");
Boolean isReaded = c.getBoolean("IsRead");
Message productObject = new Message(id, sender, "", title, sentDate, isReaded);
productArray.add(productObject);
}
}
catch (Exception e)
{
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
// @end of thread.
private Runnable returnRes = new Runnable() {
public void run()
{
profilInfoProgress.stop();
adapter.notifyDataSetChanged();// refreshing data over adapter in
// list view.
}
};
// @end of thread.
private Runnable showAlertMessage = new Runnable() {
public void run()
{
// Bu hata genelde linkteki problemden, servera ulasilamamasindan
// veya timeouttan meydana gelir.
Toast.makeText(getApplicationContext(),
"Mesajlar alınamadı lütfen daha sonra tekrar deneyiniz.",
Toast.LENGTH_LONG).show();
}
};
private Runnable showAlertIlanYokMessage = new Runnable() {
public void run()
{
// Bu hata aranilan kelimeye gore ilan bulunamazsa gelir.
Toast.makeText(getApplicationContext(),
"Mesajlar bulunamadı.",
Toast.LENGTH_LONG).show();
}
};
}
public class MesajDetayActivity extends TrackedActivity {
private HoloProgressIndicator profilInfoProgress = null;
TextView titleTextView = null;
TextView senderTextView = null;
TextView dateTextView = null;
WebView bodyWebView = null;
Message messageObject = null;
String messageID = null;
ImageView kapatButton = null;
Context context;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajdetaylari);
context = this;
kapatButton = (ImageView) findViewById(R.id.kapat_button);
/* kapat button onclick listener. */
// =================================================================================================================
kapatButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
finish();
}
});
// =================================================================================================================
//Progress bar.
profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
messageID = extras.getString("messageID");
}
titleTextView = (TextView) findViewById(R.id.title_textview);
senderTextView = (TextView) findViewById(R.id.sender_textview);
dateTextView = (TextView) findViewById(R.id.date_textview);
bodyWebView = (WebView) findViewById(R.id.mesaj_webView);
// Show the ProgressDialog on this thread
profilInfoProgress.start();
// Start a new thread that will download all the data
new MakeItTask().execute();
}
// Async task.
private class MakeItTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args)
{
Log.i("MyApp", "Background thread starting");
// This is where you would do all the work of downloading your data
// getting message detay
/* connect to web service */
getMessageDetayFromWebService();
return null;
}
protected void onPostExecute(Object result)
{
// Pass the result data back to the main activity
// TakipListeActivity.this.data = result;
try
{
titleTextView.setText("Başlık: " + messageObject.getTitle());
senderTextView.setText("Gönderen: " + messageObject.getSender());
dateTextView.setText("Tarih: " + messageObject.getSentDate().substring(6, 8) + "."
+ messageObject.getSentDate().substring(4, 6) + "."
+ messageObject.getSentDate().substring(0, 4));
if(!messageObject.getBody().contains("img"))
{
bodyWebView.loadDataWithBaseURL(null, messageObject.getBody(), "text/html", "UTF-8", null);
}
}
catch (Exception e)
{
Log.e(CONNECTIVITY_SERVICE, "Mesaj Detayi bilgileri basilamadi.");
}
profilInfoProgress.stop();
}
}
/* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */
public void getMessageDetayFromWebService()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser(context);
// getting JSON string from URL
JSONObject jsonObject = jParser.getAuthorizedInfoFromUrlToJSONObject(
WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessage/" + messageID, MainActivity.getAccessToken());
// if json is null then there is a problem.
if(jsonObject == null)
{
return;
}
try
{
String title = jsonObject.getString("Title");
String id = jsonObject.getString("Id");
String sender = jsonObject.getString("Sender");
String date = jsonObject.getString("SentDate");
String body = jsonObject.getString("Body");
messageObject = new Message(id, sender, body, title, date, true);
}
catch (Exception e)
{
Log.e("BACKGROUND_PROC", e.getMessage());
}
}// @end of getIlanDetayFromWebService.
}
Intent startIntent = new Intent(view.getContext(), ActivityB.class);
startActivity(startIntent);
finish() ;
Intent startIntent = new Intent(view.getContext(), ActivityA.class);
startActivity(startIntent);
finish() ;
android:launchMode="singleTask"
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.i("Test", "Did this work???");
//TODO send notification to your server to verify this works?
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i(TAG, "On Start .....");
}
kapatButton = (ImageView) findViewById(R.id.kapat_button);
private boolean isAlwaysFinishActivitiesOptionEnabled() {
int alwaysFinishActivitiesInt = 0;
if (Build.VERSION.SDK_INT >= 17) {
alwaysFinishActivitiesInt = Settings.System.getInt(getApplicationContext().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0);
} else {
alwaysFinishActivitiesInt = Settings.System.getInt(getApplicationContext().getContentResolver(), Settings.System.ALWAYS_FINISH_ACTIVITIES, 0);
}
if (alwaysFinishActivitiesInt == 1) {
return true;
} else {
return false;
}
}
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTop"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>