2017-08-29 13 views
0
public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "MainActivity"; 

    public static final String ANONYMOUS = "anonymous"; 
    public static final int RC_SIGN_IN = 1; 
    private static final int RC_PHOTO_PICKER = 2; 
    private String mUsername; 

    // Firebase instance variables 
    private FirebaseDatabase mFirebaseDatabase; 
    private DatabaseReference mMessagesDatabaseReference; 
    private ChildEventListener mChildEventListener; 
    private FirebaseAuth mFirebaseAuth; 
    private FirebaseAuth.AuthStateListener mAuthStateListener; 
    private FirebaseStorage mFirebaseStorage; 
    private StorageReference mChatPhotosStorageReference; 

    private SeekBar seekBar; 

    private RecyclerView recyclerView; 
    private FloatingActionButton floatingActionButton; 
    NotificationCompat.Builder notificationBuilder; 
    VideoAdapter videoAdapter; 
    List<Video> videoList; 


    NotificationManager notificationManager; 
    AlertDialog.Builder alertDialog; 
    EditText input; 

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

     mUsername = ANONYMOUS; 
     recyclerView = (RecyclerView) findViewById(R.id.recyclerview); 
     floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingactionbutton); 
     videoList = new ArrayList(); 
     // Initialize Firebase components 
     mFirebaseDatabase = FirebaseDatabase.getInstance(); 
     mFirebaseAuth = FirebaseAuth.getInstance(); 
     mFirebaseStorage = FirebaseStorage.getInstance(); 
     seekBar = (SeekBar) findViewById(R.id.seekbar); 

     mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("videomessages"); 
     mChatPhotosStorageReference = mFirebaseStorage.getReference().child("videos"); 

     mAuthStateListener = new FirebaseAuth.AuthStateListener() { 
      @Override 
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
       FirebaseUser user = firebaseAuth.getCurrentUser(); 
       if (user != null) { 
        // User is signed in 
        onSignedInInitialize(user.getDisplayName()); 
       } else { 
        // User is signed out 
        onSignedOutCleanup(); 
        startActivityForResult(
          AuthUI.getInstance() 
            .createSignInIntentBuilder() 
            .setIsSmartLockEnabled(false) 
            .setProviders(
              AuthUI.EMAIL_PROVIDER, 
              AuthUI.GOOGLE_PROVIDER) 
            .build(), 
          RC_SIGN_IN); 
       } 
      } 
     }; 





     floatingActionButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.setType("video/*"); 
       intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); 
       startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER); 


      } 
     }); 


     attachDatabaseReadListener(); 
} 


    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN) { 
      if (resultCode == RESULT_OK) { 
       // Sign-in succeeded, set up the UI 
       Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show(); 
      } else if (resultCode == RESULT_CANCELED) { 
       // Sign in was canceled by the user, finish the activity 
       Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show(); 
       finish(); 
      } 
     } else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) { 
      final Uri selectedImageUri = data.getData(); 

      String uriString = selectedImageUri.toString(); 
      File myFile = new File(uriString); 
      String path = myFile.getAbsolutePath(); 
      String displayName = null; 

      if (uriString.startsWith("content://")) { 
       Cursor cursor = null; 
       try { 
        cursor = getApplicationContext().getContentResolver().query(selectedImageUri, null, null, null, null); 
        if (cursor != null && cursor.moveToFirst()) { 
         displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); 
        } 
       } finally { 
        cursor.close(); 
       } 
      } else if (uriString.startsWith("file://")) { 
       displayName = myFile.getName(); 
      } 

      alertDialog = new AlertDialog.Builder(MainActivity.this); 
      alertDialog.setTitle("Upload"); 
      alertDialog.setMessage("Enter Name"); 

      input = new EditText(MainActivity.this); 
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.MATCH_PARENT); 
      input.setLayoutParams(lp); 
      input.setText(displayName); 
      alertDialog.setView(input); 

      alertDialog.setPositiveButton("YES", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 


          new MyAsyncTask().execute(selectedImageUri); 

         }}); 

      alertDialog.setNegativeButton("NO", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          dialog.cancel(); 
         } 
        }); 

      alertDialog.show(); 



     } 

    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     mFirebaseAuth.addAuthStateListener(mAuthStateListener); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     if (mAuthStateListener != null) { 
      mFirebaseAuth.removeAuthStateListener(mAuthStateListener); 
     } 
    } 

    private void onSignedInInitialize(String username) { 
     mUsername = username; 
     attachDatabaseReadListener(); 
    } 

    private void onSignedOutCleanup() { 
     mUsername = ANONYMOUS; 

    } 

    private void attachDatabaseReadListener() { 

     mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot snapshot) { 
       videoList.clear(); 
       for (DataSnapshot postSnapshot : snapshot.getChildren()) { 

        Video postSnapshotValue = postSnapshot.getValue(Video.class); 
        if (!videoList.contains(postSnapshotValue)) { 
         videoList.add(postSnapshotValue); 
         Log.i(TAG, "onDataChange: " + videoList); 
        } 

       } 

       videoAdapter = new VideoAdapter(videoList, MainActivity.this); 
       recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this)); 

       recyclerView.setAdapter(videoAdapter); 

      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 


      } 
     }); 
    } 


    public class MyAsyncTask extends AsyncTask<Uri, Void, Void> { 

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

     } 

     @Override 
     protected Void doInBackground(final Uri... params) { 
      final StorageReference photoRef = mChatPhotosStorageReference.child(params[0].getLastPathSegment()); 
      alertDialog.setView(input); 

       photoRef.putFile(params[0]) 
            .addOnSuccessListener(MainActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() { 
             public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
              // When the image has successfully uploaded, we get its download URL 
              // progressBar.setVisibility(View.VISIBLE); 
              Uri downloadUrl = taskSnapshot.getDownloadUrl(); 
              //String nameUrl=taskSnapshot.getMetadata().getName(); 

              Video video = new Video(input.getText().toString().trim(),downloadUrl.toString()); 
              Log.i(TAG, "onSuccess: Video Uploaded"); 
              mMessagesDatabaseReference.push().setValue(video); 
             // mMessagesDatabaseReference.push().setValue(video.getVideoUrl()); 

             } 
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() { 
           @Override 
           public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { 
            int progress = (int) ((100 * taskSnapshot.getBytesTransferred())/taskSnapshot.getTotalByteCount()); 

            seekBar.setProgress(progress); 

            notificationBuilder = new NotificationCompat.Builder(getApplicationContext()) 
              .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary)) 
              .setSmallIcon(R.mipmap.ic_launcher) 
              .setContentText("Upload in progress") 
              .setContentIntent(contentIntent(getApplicationContext())) 
              .setAutoCancel(true); 

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
             notificationBuilder.setPriority(Notification.PRIORITY_HIGH); 
            } 

            notificationManager = (NotificationManager) 
              getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); 

            for (int incr = progress; incr <= 100; incr += 5) { 


             notificationBuilder.setProgress(100, progress, false); 

             notificationManager.notify(20, notificationBuilder.build()); 

            } 
            if(progress>=100){ 
             notificationBuilder.setContentText("Upload complete").setProgress(0, 0, false); 
             notificationManager.notify(20, notificationBuilder.build()); 

            } 



           } 
          }); 




      return null; 
     } 


    } 

    private PendingIntent contentIntent(Context context) { 

     Intent startActivityIntent = new Intent(context, MainActivity.class); 
     return PendingIntent.getActivity(
       context, 
       0, 
       startActivityIntent, 
       PendingIntent.FLAG_UPDATE_CURRENT); 
    } 





} 

私はフローティング操作button.Theビデオのクリックでfirebaseストレージにビデオをアップロードしていますが、ストレージにアップロードします、私は、これは.Iはわからないが、私を聞いてくださいfirebaseのバグだと思いfollコードデータベースのプッシュ、firebaseバグ

Video video = new Video(input.getText().toString().trim(),downloadUrl.toString()); 
              Log.i(TAG, "onSuccess: Video Uploaded"); 
              mMessagesDatabaseReference.push().setValue(video); 

を使用して、データベースへのビデオ名とそのダウンロードURLを押してください。 ファーストケース: ビデオをアップロードするまでビデオをfirebaseにアップロードすると、ビデオ名とダウンロードurlfirebaseデータベースにプッシュされ、ビデオがストレージにアップロードされます。 第2の場合: firebaseの動画をアップロードして他のアプリを開くと、例えばyoutubeと表示され、通知が届いたら、ビデオをアップロードした後、動画をアップロードした後に、 、firebaseは名前とビデオのURLをデータベースにプッシュしませんが、ビデオはストレージにアップロードされます。 この動作は、誰もが私を導いてくださいすることができ、なぜ..

+0

2番目の(失敗した)ケースについては、「onSuccess:Video Uploaded?」というlogcatメッセージが表示されますか?このメソッドとログステートメントをアクティビティに追加してください。 –

+0

@BobSnyderはい。 – Pritish

答えて

1

更新:?

あなたはphotoRef.putFile(params[0])に活動スコープの成功のリスナーを使用しています。 The documentationは説明する:

リスナーが自動的にonStop(中に削除されます)

あなたの活動が背景になると、それが停止し、リスナーが削除されます。最初の引数としてActivityを取らない他の形式のaddOnSuccessListener()を使用してください。


完了リスナーを被疑者setValue()に追加します。また、inputの値を記録します。私は、アクティビティが停止したときにUIオブジェクトの状態がどうなるか分かりません。コメントへの応答に基づいて

Video video = new Video(input.getText().toString().trim(),downloadUrl.toString()); 
Log.i(TAG, "onSuccess: Video Uploaded= " + input.getText()); 
mMessagesDatabaseReference.push().setValue(video, new DatabaseReference.CompletionListener() { 
    @Override 
    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { 
     if (databaseError == null) { 
      Log.d(TAG, "onComplete: SUCCESS"); 
     } else { 
      Log.e(TAG, "onComplete: FAILED ", databaseError.toException()); 
     } 
    } 
}); 

それがバックグラウンドに置かれたとき、あなたの活動が(停止ではなく)破壊取得することができるように、それが聞こえます。

+0

@BobSynder私のプロジェクトでコードを追加した後も同じことが起こります。アップロードを開始すると、私のアプリを開いたままにしておくと、Log.i(TAG、 "onSuccess:Video Uploaded =" + input.getText()) ;ビデオはアップロードされ、値はデータベースにプッシュされます。アップロード中にアプリケーションを閉じると、ビデオはfirebaseストレージにアップロードされますが、値はデータベースにプッシュされますが、ログステートメントは表示されません – Pritish

+0

" 「あなたはホーム画面に行くなど、バックグラウンドに置くことを意味しますか?その場合、アプリからのログ出力が引き続き表示されます。以前の回答では、アプリケーションが終了したときに 'onSuccess:Video Uploaded'ログメッセージが表示されています。そうですか? –

+0

"私のアプリを閉じる"とは、バックグラウンドに入れているか、アプリを閉じていることを意味します。私はonSuccessを見ることができません。 – Pritish

関連する問題