2015-11-03 72 views
0

剛接觸android並遇到應用程序不在Emulator上崩潰但在手機上崩潰的情況。所以我沒有機會看到導致應用程序崩潰的原因。Android:應用程序在我的手機上崩潰,但在IntentService期間不在模擬器上

該應用程序運行的IntentService,不斷看起來圖像的文件夾中: - 上傳新的圖片到我的服務器 - 圖像複製到另一個文件夾 - 從原來的文件夾中刪除圖像 - 返回尋找下一張圖片

我已經用最小的UI設置了我的應用程序。只有2個活動:1.主要活動,以及2.設置文件夾首選項的活動。主要活動有兩個按鈕:1.啓動服務,以及2.停止服務。

當我啓動服務並將圖像複製到指定文件夾時,圖像將上傳到我的服務器,然後移動到指定的移動到電話文件夾 - 很好。但是我猜想,當程序返回查看下一個文件的文件夾時,發生了一些迫使應用程序崩潰的情況。

IntentService:

import android.app.IntentService; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.util.Base64; 
import android.widget.Toast; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.ByteArrayOutputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.FilenameFilter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLEncoder; 
import java.util.HashMap; 
import java.util.Map; 

import javax.net.ssl.HttpsURLConnection; 

public class incomingPicListener extends IntentService { 
    Bitmap photoCapturedBitmap; 
    private static final String RESULT_SUCCESS = "success"; 
    private static final String URL_SAVE_IMAGE = "http://.....php"; 
    Boolean imgsaved; 

    String fileFound; 

    public incomingPicListener() { 

     super("incomingPicListener"); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startid){ 
     Toast.makeText(incomingPicListener.this, "Service started...", Toast.LENGTH_LONG).show(); 
     System.out.println("Service Started"); 
     return super.onStartCommand(intent,flags,startid); 
    } 

    @Override 
    public void onDestroy(){ 
     super.onDestroy(); 
     System.out.println("Service Stopped"); 
     Toast.makeText(incomingPicListener.this, "Service stopped...", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     SharedPreferences folderPrefs = getSharedPreferences("FolderPrefs", 0); 

     final String savedFolder = folderPrefs.getString("FolderInput", "<Empty>"); 
     final String savedTargetPhoneFolder = folderPrefs.getString("TargetPhoneFolder", "<Empty>"); 

     synchronized (this) { 
      int count = 0; 
      while (count<10) { 
       try { 
        wait(500); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 

       File dir = new File(savedFolder); 
       File[] directoryListing = dir.listFiles(new FilenameFilter() { 

        public boolean accept(File dir, String name) { 
         fileFound=name; 
         return name.toLowerCase().endsWith(".JPG"); 
        } 
       }); 
       String filepath = savedFolder+"/"+fileFound; 
       File check = new File(savedFolder+"/"+fileFound); 

       if ((!check.isDirectory()) && fileFound != null) { 
        String imagepath= savedFolder + "/" + fileFound; 
        if(setupImage(imagepath)){ 
         moveFile(imagepath, savedTargetPhoneFolder + "/" + fileFound); 
        }else{ 
         Toast.makeText(incomingPicListener.this, "Upload failed: " +imagepath, Toast.LENGTH_LONG).show(); 
        } 
       } 


      } 

     } 
    } 

    public boolean setupImage(String imgpath){ 

     photoCapturedBitmap = BitmapFactory.decodeFile(imgpath); 

     String str = getStringImage(photoCapturedBitmap); 
     HashMap HashMap = new HashMap(); 
     HashMap.put("name",fileFound); 
     HashMap.put("image", str); 
     String result = sendPostRequest(URL_SAVE_IMAGE, HashMap); 
     if (result.toLowerCase().contains(RESULT_SUCCESS)){ 
      return true; 
     }else { 
      return false; 
     } 
    } 

    public String getStringImage(Bitmap paramBitmap) 
    { 
     ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); 
     paramBitmap.compress(Bitmap.CompressFormat.JPEG, 100, localByteArrayOutputStream); 
     return Base64.encodeToString(localByteArrayOutputStream.toByteArray(), 0); 
    } 
    public void moveFile(String origFile, String trgFile){ 
     InputStream inStream = null; 
     OutputStream outStream = null; 

     try{ 

      File afile =new File(origFile); 
      File bfile =new File(trgFile); 

      inStream = new FileInputStream(afile); 
      outStream = new FileOutputStream(bfile); 

      byte[] buffer = new byte[1024]; 

      int length; 
      //copy the file content in bytes 
      while ((length = inStream.read(buffer)) > 0){ 

       outStream.write(buffer, 0, length); 

      } 

      inStream.close(); 
      outStream.close(); 

      //delete the original file 
      afile.delete(); 

      System.out.println("File is copied successful!"); 

     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
    } 


    public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) { 
     URL url; 
     StringBuilder sb = new StringBuilder(); 
     try { 
      url = new URL(requestURL); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(15000); 
      conn.setConnectTimeout(15000); 
      conn.setRequestMethod("POST"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 
      DataOutputStream os = new DataOutputStream (conn.getOutputStream()); 
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
      writer.write(getPostDataString(postDataParams)); 
      writer.flush(); 
      writer.close(); 
      os.close(); 
      int responseCode = conn.getResponseCode(); 
      if (responseCode == HttpsURLConnection.HTTP_OK) { 
       BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       sb = new StringBuilder(); 
       String response; 
       while ((response = br.readLine()) != null) { 
        sb.append(response); 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return sb.toString(); 
    } 

    public String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { 
     StringBuilder result = new StringBuilder(); 
     boolean first = true; 
     for (Map.Entry<String, String> entry : params.entrySet()) { 
      if (first) 
       first = false; 
      else 
       result.append("&"); 

      result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 
      result.append("="); 
      result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 
     } 
     return result.toString(); 
    } 
} 
enter code here 

主要活動:

import android.content.Intent; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity implements View.OnClickListener { 
    TextView status; 
    Intent loader; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     status = (TextView) findViewById(R.id.tvCurrentState); 
     Button btnPref = (Button) findViewById(R.id.bFolderLocations); 
     Button btnEnable = (Button) findViewById(R.id.bEnableProcess); 
     Button btnDisable = (Button) findViewById(R.id.bDisableProcess); 


     btnPref.setOnClickListener(this); 
     btnEnable.setOnClickListener(this); 
     btnDisable.setOnClickListener(this); 

    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.bFolderLocations: 
       startActivity(new Intent(MainActivity.this, FolderPref.class)); 
       break; 
      case R.id.bEnableProcess: 
       startService(this); 
       status.setText("Enabled"); 
       break; 
      case R.id.bDisableProcess: 
       stopService(this); 
       status.setText("Disabled"); 
       break; 
     } 


    } 

    public void startService(MainActivity view){ 

     Intent intent = new Intent(this,incomingPicListener.class); 
     startService(intent); 

    } 

    public void stopService (MainActivity view){ 
     Intent intent = new Intent(this,incomingPicListener.class); 
     stopService(intent); 
    } 
} 

這裏的清單:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.imgloader..." > 

    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name=".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> 
     <activity 
      android:name=".FolderPref" 
      android:label="@string/title_activity_folder_pref" > 
     </activity> 

     <service 
      android:name=".incomingPicListener" 
      android:exported="false" > 
     </service> 

     <activity 
      android:name=".DirectoryChooserActivity" 
      android:label="@string/title_activity_directory_chooser" > 
     </activity> 
    </application> 

</manifest> 
+0

很高興看到崩潰消息。 – mikeD

+0

我能在手機上看到嗎? –

+0

如果您的手機已連接,那麼您可以在Android Studio中看到Logcat中發生的一切。 – mikeD

回答

0

你添加了IntentService到您的清單?

<service 
    android:name="com.package.name.MyIntentService" 
    android:exported="false" > 
</service> 
+0

剛剛添加了清單,代碼就在那裏。 –

0

所以我想出瞭如何使用AS上的手機進行調試。問題是我用於fileFound的全局變量 - 我沒有重置它,所以當進程環繞時,它試圖再次加載同一個文件 - 除非它不存在,因爲我將它移動了。所以我需要從原始文件夾中刪除它後設置fileFound = null。謝謝大家的意見!

相關問題